language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
// TODO : Write a program which accept one number from user and print that number of even numbers on screen. /* ALGORITHM START Accept one number from user and store it in variable. Iterate one loop till that number and print even number till that number Display the even numbers on screen STOP */ #include "header.h" int main() { int iNo = 0; printf("Enter the number : \t"); scanf("%d",&iNo); if(iNo == 0) { printf("Enter valid number!..."); } PrintEven(iNo); return 0; }
C
/* File Server (FS) invoked with: ./FS [-q FSport] [-n ASIP] [-p ASport] [-v] The FS server accepts TCP requests on the well-known port FSport, to answer User requests. */ #include "config.h" #include "connection.h" #include <arpa/inet.h> #include <dirent.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #define MAXARGS 8 #define MINARGS 1 #define MAX(a, b) a *(a > b) + b *(b >= a) void exitFS(); typedef struct user { int fd; char uid[7]; int pending; } * User; typedef struct transaction { char uid[7]; char tid[5]; char vc[5]; char fop[2]; char fname[32]; char fsize[32]; } * Transaction; int numClients = 0; int numTransactions = 0; int verbose = FALSE; int numTries = 0; char lastMessage[128]; int confirmationPending = FALSE; int messageToResend = FALSE; int endFS = FALSE; int fd_udp, fd_tcp; User *users; Transaction *transactions; fd_set rset; socklen_t addrlen_udp, addrlen_tcp; struct addrinfo hints_udp, *res_udp, hints_tcp, *res_tcp; struct sockaddr_in addr_udp, addr_tcp; char fsport[8], asport[8], asip[32]; // print if verbose mode void printv(char *message) { if (verbose == TRUE) printf("%s\n", message); } /* === error functions === */ void errorExit(char *errorMessage) { if (errno != 0) printf("ERR: %s: %s\n", errorMessage, strerror(errno)); else printf("ERR: %s\n", errorMessage); exitFS(); } void printError(char *errorMessage) { if (errno != 0) printf("ERR: %s: %s\nNot exiting...\n", errorMessage, strerror(errno)); else printf("ERR: %s\nNot exiting...\n", errorMessage); } void readGarbage(int fd, int size) { char c; int n, i; for (i = 0; i < size; i++) { n = read(fd, &c, 1); if (n == -1) printError("read()"); } } void exitFS() { int i; freeaddrinfo(res_udp); close(fd_udp); freeaddrinfo(res_tcp); close(fd_tcp); for (i = 0; i < numClients; i++) { if (users[i] != NULL) close(users[i]->fd); free(users[i]); } for (i = 0; i < numTransactions; i++) { free(transactions[i]); } printv("Ending FS..."); exit(0); } /* === sighandler functions === */ void resendHandler() { messageToResend = TRUE; } void exitHandler() { endFS = TRUE; } /* === resend messages that were not acknowledge === */ void resetLastMessage() { confirmationPending = FALSE; lastMessage[0] = '\0'; numTries = 0; alarm(0); } void assignLastMessage(char *message) { confirmationPending = TRUE; strcpy(lastMessage, message); alarm(2); } void resendMessage() { int n; messageToResend = FALSE; if (numTries++ > 2) exitFS(); n = sendto(fd_udp, lastMessage, strlen(lastMessage) * sizeof(char), 0, res_udp->ai_addr, res_udp->ai_addrlen); if (n == -1) errorExit("sendto()"); alarm(2); } /* === auxiliary functions === */ int readUntilSpace(int user, char *buffer) { char c; int i = 0, n = 0, count = 0; do { n = read(users[user]->fd, &c, 1); count += n; if (n <= 0) { close(users[user]->fd); users[user] = NULL; return count; } buffer[i++] = c; if (endFS) exitFS(); } while (c != ' ' && c != '\0' && c != '\n'); buffer[--i] = '\0'; return count; } /* === command functions === */ void sendNokReply(int fd, Transaction transaction) { int n; char reply[8]; switch (transaction->fop[0]) { case 'R': strcpy(reply, "RRT NOK"); break; case 'D': strcpy(reply, "RDL NOK"); break; case 'X': strcpy(reply, "RRM NOK"); break; default: strcpy(reply, "ERR"); } n = write(fd, reply, strlen(reply)); if (n == -1) printError("write()"); } void listFiles(int fd, Transaction transaction) { DIR *d; FILE *file; char dirpath[32], message[270], files[400], reply[512], filepath[512]; struct dirent *dir; int fsize, n_files = 0; sprintf(dirpath, "USERS/UID%s/FILES", transaction->uid); d = opendir(dirpath); if (d) { while ((dir = readdir(d)) != NULL) { if (dir->d_name[0] != '.') { sprintf(filepath, "%s/%s", dirpath, dir->d_name); if (access(filepath, F_OK) != -1) { file = fopen(filepath, "r"); fseek(file, 0, SEEK_END); fsize = ftell(file); fseek(file, 0, SEEK_SET); sprintf(message, " %s %d", dir->d_name, fsize); if (n_files == 0) strcpy(files, message); else strcat(files, message); n_files++; fclose(file); } } } closedir(d); } if (n_files == 0) { write(fd, "RLS EOF\n", 8); } else { sprintf(message, "list operation successful for UID=%s", transaction->uid); printv(message); sprintf(reply, "RLS %d%s\n", n_files, files); write(fd, reply, strlen(reply)); } } void deleteFile(int fd, Transaction transaction) { char message[128], path[64]; int n; sprintf(path, "USERS/UID%s/FILES/%s", transaction->uid, transaction->fname); if (remove(path) != 0) { n = write(fd, "RDL EOF\n", 8); if (n == -1) errorExit("write()"); return; } sprintf(message, "file %s deleted for user %s", transaction->fname, transaction->uid); printv(message); n = write(fd, "RDL OK\n", 7); if (n == -1) errorExit("write()"); } void retrieveFile(int fd, Transaction transaction) { int n, fsize, count; char message[128], buffer[128], path[64]; FILE *file; sprintf(path, "USERS/UID%s/FILES/%s", transaction->uid, transaction->fname); if ((file = fopen(path, "r")) == NULL) { sprintf(message, "Error: file %s from user %s does not exist", transaction->fname, transaction->uid); printv(message); n = write(fd, "RRT EOF\n", 8); if (n == -1) errorExit("write()"); return; } fseek(file, 0, SEEK_END); fsize = ftell(file); fseek(file, 0, SEEK_SET); sprintf(message, "file %s retrieved for user %s", transaction->fname, transaction->uid); printv(message); sprintf(message, "RRT OK %d ", fsize); n = write(fd, message, strlen(message)); if (n == -1) errorExit("write()"); do { count = fread(buffer, 1, 128, (FILE *)file); n = write(fd, buffer, count); if (n == -1) errorExit("write()"); } while (count == 128); n = write(fd, "\n", 1); if (n == -1) errorExit("write()"); fclose(file); } void uploadFile(int user, Transaction transaction) { DIR *d; FILE *file; struct dirent *dir; char message[128]; char dirpath[32], filepath[64], c; int n, i, size, n_files = 0; sscanf(transaction->fsize, "%d", &size); sprintf(dirpath, "USERS/UID%s", transaction->uid); mkdir(dirpath, 0777); sprintf(dirpath, "USERS/UID%s/FILES", transaction->uid); mkdir(dirpath, 0777); d = opendir(dirpath); if (d) { while ((dir = readdir(d)) != NULL) { if (!strcmp(dir->d_name, transaction->fname)) { readGarbage(users[user]->fd, size); n = write(users[user]->fd, "RUP DUP\n", 8); if (n == -1) errorExit("write()"); return; } if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")) n_files++; } closedir(d); } if (n_files >= 15) { readGarbage(users[user]->fd, size); n = write(users[user]->fd, "RUP FULL\n", 9); if (n == -1) errorExit("write()"); return; } sprintf(filepath, "%s/%s", dirpath, transaction->fname); file = fopen(filepath, "w"); for (i = 0; i < size; i++) { n = read(users[user]->fd, &c, 1); if (n == -1) errorExit("read()"); else if (n == 0) { printf("Error: FS closed\n"); close(users[user]->fd); users[user] = NULL; return; } if (file != NULL) fputc(c, (FILE *)file); } if (file != NULL) fclose(file); sprintf(message, "%s stored for UID=%s", transaction->fname, transaction->uid); printv(message); n = write(users[user]->fd, "RUP OK\n", 7); if (n == -1) errorExit("write()"); } void removeAll(int fd, Transaction transaction) { char message[128], dirpath[64], filepath[512]; int n; struct dirent *dir; DIR *d; sprintf(dirpath, "USERS/UID%s/FILES", transaction->uid); d = opendir(dirpath); if (d) { while ((dir = readdir(d)) != NULL) { if (dir->d_name[0] != '.') { sprintf(filepath, "%s/%s", dirpath, dir->d_name); remove(filepath); } } closedir(d); } rmdir(dirpath); sprintf(message, "operation remove done for UID=%s", transaction->uid); printv(message); n = write(fd, "RRM OK\n", 7); if (n == -1) errorExit("write()"); } /* === user manager === */ // receive new connection from user void userSession(int user) { int n, i; char buffer[128], message[128], command[5], uid[32], tid[32], fname[32], fsize[32], type[32]; if (!readUntilSpace(user, command)) return; if (users[user] == NULL) return; if (!readUntilSpace(user, uid)) return; if (!readUntilSpace(user, tid)) return; strcpy(users[user]->uid, uid); for (i = 0; i < numTransactions + 1; i++) { if (transactions[i] == NULL) { transactions[i] = (Transaction)malloc(sizeof(struct transaction)); strcpy(transactions[i]->uid, uid); strcpy(transactions[i]->tid, tid); break; } } if (i == numTransactions) { numTransactions++; transactions = (Transaction *)realloc(transactions, sizeof(Transaction) * (numTransactions + 1)); transactions[numTransactions] = NULL; } if (!strcmp(command, "RTV") || !strcmp(command, "DEL")) { if (!strcmp(command, "RTV")) { strcpy(type, "retrieve"); strcpy(transactions[i]->fop, "R"); } else if (!strcmp(command, "DEL")) { strcpy(type, "delete"); strcpy(transactions[i]->fop, "D"); } if (!readUntilSpace(user, fname)) return; sprintf(buffer, "UID=%s: %s %s", uid, type, fname); strcpy(transactions[i]->fname, fname); } else if (!strcmp(command, "UPL")) { if (!readUntilSpace(user, fname)) return; if (!readUntilSpace(user, fsize)) return; sprintf(buffer, "UID=%s: upload %s (%s Bytes)", uid, fname, fsize); strcpy(transactions[i]->fop, "U"); strcpy(transactions[i]->fname, fname); strcpy(transactions[i]->fsize, fsize); } else { if (!strcmp(command, "LST")) { strcpy(type, "list"); strcpy(transactions[i]->fop, "L"); } else if (!strcmp(command, "REM")) { strcpy(type, "remove"); strcpy(transactions[i]->fop, "X"); } sprintf(buffer, "UID=%s: %s", uid, type); } printv(buffer); sprintf(message, "VLD %s %s\n", uid, tid); n = sendto(fd_udp, message, strlen(message), 0, res_udp->ai_addr, res_udp->ai_addrlen); if (n == -1) printError("validateOperation: sendto()"); assignLastMessage(message); users[user]->pending = TRUE; } void sendInvReply(int fd, Transaction transaction) { int n; char reply[9]; switch (transaction->fop[0]) { case 'L': strcpy(reply, "RLS INV\n"); break; case 'R': strcpy(reply, "RRT INV\n"); break; case 'U': strcpy(reply, "RUP INV\n"); break; case 'D': strcpy(reply, "RDL INV\n"); break; default: strcpy(reply, "ERR\n"); } n = write(fd, reply, strlen(reply)); if (n == -1) printError("write()"); } // receive message from AS void doOperation(char *buffer) { char uid[7], tid[6], command[5]; int n, i, j, fd = 0; char fop; sscanf(buffer, "%s %s %s %c", command, uid, tid, &fop); if (!strcmp(command, "CNF")) { resetLastMessage(); for (i = 0; i < numTransactions + 1; i++) { if (!strcmp(tid, transactions[i]->tid)) break; } if (i == numTransactions + 1) { printv("Error: Transaction was not found"); return; } for (j = 0; j < numClients + 1; j++) { if (!strcmp(users[j]->uid, uid)) { fd = users[j]->fd; break; } } if (j == numClients + 1) { printv("Error: User does not exist"); for (j = 0; j < numClients + 1; j++) { if (!strcmp(users[j]->uid, transactions[i]->uid)) { sendNokReply(users[j]->fd, transactions[i]); break; } } } switch (fop) { case 'L': listFiles(fd, transactions[i]); break; case 'D': deleteFile(fd, transactions[i]); break; case 'R': retrieveFile(fd, transactions[i]); break; case 'U': uploadFile(j, transactions[i]); break; case 'X': removeAll(fd, transactions[i]); break; case 'E': sendInvReply(fd, transactions[i]); } transactions[i] = NULL; } else { n = write(fd, "ERR\n", 4); if (n == -1) printError("doOperation: write()"); } users[j]->pending = FALSE; } /* === main code === */ void fdManager() { char buffer[128]; int i, n, maxfdp1; while (1) { FD_ZERO(&rset); FD_SET(fd_udp, &rset); FD_SET(fd_tcp, &rset); for (i = 0; i < numClients; i++) { if (users[i] != NULL) { FD_SET(users[i]->fd, &rset); } } maxfdp1 = MAX(fd_tcp, fd_udp); for (i = 0; i < numClients; i++) { if (users[i] != NULL) maxfdp1 = MAX(maxfdp1, users[i]->fd); } maxfdp1++; n = select(maxfdp1, &rset, NULL, NULL, NULL); if (n == -1) { // if interrupted by signals if (endFS) exitFS(); if (messageToResend) resendMessage(); continue; } if (FD_ISSET(fd_udp, &rset)) { // receive message from AS n = recvfrom(fd_udp, buffer, 128, 0, (struct sockaddr *)&addr_udp, &addrlen_udp); if (n == -1) printError("main: recvfrom()"); buffer[n] = '\0'; doOperation(buffer); } if (FD_ISSET(fd_tcp, &rset)) { // receive new connection from user for (i = 0; i < numClients + 1; i++) { if (users[i] == NULL) { users[i] = (User)malloc(sizeof(struct user)); users[i]->pending = FALSE; if ((users[i]->fd = accept(fd_tcp, (struct sockaddr *)&addr_tcp, &addrlen_tcp)) == -1) printError("main: accept()"); break; } } if (i == numClients) { numClients++; users = (User *)realloc(users, sizeof(User) * (numClients + 1)); users[numClients] = NULL; } } if (!confirmationPending) { // receive message from User only if FS can communicate with AS for (i = 0; i < numClients; i++) { // receive command from User if (users[i] != NULL && !users[i]->pending) { if (FD_ISSET(users[i]->fd, &rset)) { userSession(i); } } } } } } int main(int argc, char *argv[]) { int i; if (argc < MINARGS || argc > MAXARGS) { printf("Usage: %s [-q FSport] [-n ASIP] [-p ASport] [-v]\n", argv[0]); printError("incorrect number of arguments"); } strcpy(fsport, FSPORT); strcpy(asport, ASPORT); strcpy(asip, ASIP); for (i = MINARGS; i < argc; i++) { if (!strcmp(argv[i], "-v")) { verbose = TRUE; } else if (!strcmp(argv[i], "-h")) { printf("Usage: %s [-q FSport] [-n ASIP] [-p ASport] [-v]\n", argv[0]); exit(0); } else if (!strcmp(argv[i], "-q")) { strcpy(fsport, argv[++i]); } else if (!strcmp(argv[i], "-p")) { strcpy(asport, argv[++i]); } else if (!strcmp(argv[i], "-n")) { strcpy(asip, argv[++i]); } } mkdir("USERS", 0777); udpConnect(asip, asport, &fd_udp, &res_udp); tcpOpenConnection(FSPORT, &fd_tcp, &res_tcp); if (listen(fd_tcp, 5) == -1) printError("TCP: listen()"); users = (User *)malloc(sizeof(User)); users[0] = NULL; transactions = (Transaction *)malloc(sizeof(Transaction)); transactions[0] = NULL; signal(SIGINT, exitHandler); signal(SIGALRM, resendHandler); fdManager(); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct a{ int id; struct a *prev, *next; }Node; //for an item of linkedlist typedef struct { Node *head, *tail; }List; void push(List *list, int id){ Node *t = (Node *) malloc(sizeof(Node)); t->id = id; t->prev = t->next = 0; if(list->head == 0) // for first item or if the list is empty { list->head = list->tail = t; } else{ list->tail->next = t; t->prev = list->tail; list->tail = t; } printf("%d has been added @%d\n",t->id, t); } int pop(List *list){ if(list->tail == 0){ printf("\nStack Underflow"); return -1; } int t = list->tail->id; list->tail = list->tail->prev; return t; } int main(){ //linkedlist List *stack = (List *) malloc(sizeof(List)); stack->head = stack->tail = 0; push(stack, 5); push(stack, 10); push(stack, 20); push(stack, 30); push(stack, 40); printf("\nPopped %d", pop(stack)); printf("\nPopped %d", pop(stack)); printf("\nPopped %d", pop(stack)); printf("\nPopped %d", pop(stack)); printf("\nPopped %d", pop(stack)); printf("\nPopped %d", pop(stack)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char Alphabet[11]="dcba"; char Buffer[101]; int Len; void Make(int Dep) { int T,L; char Local[101]; L=strlen(Buffer); memcpy(Local,Buffer,L+1); if (Dep<Len) { for (T=0; T<=L; T++) { strncpy(Buffer,Local,T); Buffer[T]=Alphabet[Dep]; strncpy(Buffer+T+1,Local+T,L-T); Buffer[L+1]='\0'; Make(Dep+1); } } else { puts(Buffer); } return; } int main() { while(EOF!=scanf("%s",Alphabet)) { Len=strlen(Alphabet); Buffer[0]='\0'; Make(0); puts(""); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* algo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jbulant <jbulant@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/22 00:05:14 by jbulant #+# #+# */ /* Updated: 2019/01/30 15:32:14 by jbulant ### ########.fr */ /* */ /* ************************************************************************** */ #include <math.h> #include <stdlib.h> #include "algo.h" #include "types.h" void ft_bresenham(t_bresenham *data) { t_ivec2 orientation; t_ivec2 direction; int error[2]; direction = IVEC2_INIT(abs(data->v1.x - data->v2.x), abs(data->v1.y - data->v2.y)); orientation = IVEC2_INIT(((data->v1.x < data->v2.x) ? 1 : -1), ((data->v1.y < data->v2.y) ? 1 : -1)); error[0] = ((direction.x > direction.y) ? direction.x : -direction.y) / 2; while (!(data->v1.x == data->v2.x && data->v1.y == data->v2.y)) { data->call(data->param, data->v1); error[1] = error[0]; if (error[1] > -direction.x) { error[0] -= direction.y; data->v1.x += orientation.x; } if (error[1] < direction.y) { error[0] += direction.x; data->v1.y += orientation.y; } } } void ft_unidir_line(t_ud_line *data) { int i; t_ivec2 local_dir; local_dir = 0; if (data->len < 0) { data->len = -data->len; local_dir[data->dir] = -1; } else local_dir[data->dir] = 1; i = 0; while (i < data->len) { data->call(data->param, data->point + (i * local_dir)); i++; } } void ft_flood(t_flood_d *f_data, t_ivec2 px) { if (f_data->condition(f_data, px)) { f_data->action(f_data, px); ft_flood(f_data, IVEC2_INIT(px.x - 1, px.y)); ft_flood(f_data, IVEC2_INIT(px.x + 1, px.y)); ft_flood(f_data, IVEC2_INIT(px.x, px.y - 1)); ft_flood(f_data, IVEC2_INIT(px.x, px.y + 1)); } } void ft_circle(t_circle *c) { int i; t_ivec2 point; i = 0; while (i <= 360 * c->radius) { point = c->pos; point.x += (int)round(sin((t_float)i) * c->radius); point.y += (int)round(cos((t_float)i) * c->radius); c->call(c->param, point); i++; } }
C
#include <stdio.h> #include <time.h> #define MAXLEN 29168 #define EOF_VALUE -49 #define NEW_LINE_VALUE -38 #define ASCII_OFFSET 48 void decode(char decode_line[MAXLEN]); // array of Look-up tables ordered from 0-4 char LUT_DIRECTORY[5][4][2] = { { "c2", "+1", "b2", "+2" },{ "a1", "a1", "e2", "+3" },{ "d1", "d1", "f2", "g2" },{ "h1", "h1", "i2", "+4" },{ "j1", "j1", "k2", "l2" } }; int main(void) { //Open dataset file FILE *fp = fopen("./encodeddataset_full.dat","r"); //Line which stores the encoded string char decode_line[MAXLEN]; //Read in line of MAXLEN fgets(decode_line, MAXLEN, (FILE*)fp); clock_t begin = clock(); // function call to encode decode(decode_line); clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("\n\nSystem execution time %f\n", time_spent); printf("System execution cycles %f\n", (double)(end - begin)); } void decode(char decode_line[MAXLEN]){ // Symbols int first_symbol_to_decode; int second_symbol_to_decode; int third_symbol_to_decode; int fourth_symbol_to_decode; // iterator int i; // Look-up table id & eof flag int lut_id = 0; // iterate over the string to decode for(i=0; i<MAXLEN; i += 4){ // Decoded symbol char *lut_result; int lut_index; // Get first and second character first_symbol_to_decode = decode_line[i] - ASCII_OFFSET; second_symbol_to_decode = decode_line[i+1] - ASCII_OFFSET; // No more charactes to decode if(first_symbol_to_decode == NEW_LINE_VALUE || first_symbol_to_decode == EOF_VALUE){ break; } // At the end of file, second symbol is functionally a 0 if(second_symbol_to_decode == NEW_LINE_VALUE || second_symbol_to_decode == EOF_VALUE){ second_symbol_to_decode = 0; // Set i to end for loop i = MAXLEN; } // Set index for look-up table lut_index = (first_symbol_to_decode << 1) + (second_symbol_to_decode); // depending on the look-up table lut_result = LUT_DIRECTORY[lut_id][lut_index]; if(lut_result[0] == '+') { // Continue to next table, which is given in the second character of the result lut_id = lut_result[1] - 48; } else { // Reset the table id lut_id = 0; // check if we are adding one or two to the length, which is the second character // only add one to the length, back up one character so we don't skip one if(lut_result[1] == '1') i -= 1; //Print out table result printf("%c", lut_result[0]); } if(i != MAXLEN){ // Get first and second character third_symbol_to_decode = decode_line[i+2] - ASCII_OFFSET; fourth_symbol_to_decode = decode_line[i+3] - ASCII_OFFSET; // No more charactes to decode if(third_symbol_to_decode == NEW_LINE_VALUE || third_symbol_to_decode == EOF_VALUE){ break; } // At the end of file, second symbol is functionally a 0 if(fourth_symbol_to_decode == NEW_LINE_VALUE || fourth_symbol_to_decode == EOF_VALUE){ second_symbol_to_decode = 0; // Set i to end for loop i = MAXLEN; } // Set index for look-up table lut_index = (third_symbol_to_decode << 1) + (fourth_symbol_to_decode); // depending on the look-up table lut_result = LUT_DIRECTORY[lut_id][lut_index]; if(lut_result[0] == '+') { // Continue to next table, which is given in the second character of the result lut_id = lut_result[1] - 48; } else { // Reset the table id lut_id = 0; // check if we are adding one or two to the length, which is the second character // only add one to the length, back up one character so we don't skip one if(lut_result[1] == '1') i -= 1; //Print out table result printf("%c", lut_result[0]); } } } }
C
#include <stdio.h> #include <stdlib.h> typedef struct { int k; int a; int b; } number; long get_gcd(long a, long b) { if (b) while ((a %= b) && (b %= a)); return a + b; } number* get_num(long a, long b) { long gcd = get_gcd(a, b); a /= gcd; b /= gcd; if (b < 0) { b = -b; a = -a; } number* new_num = (number*)malloc(sizeof(number)); if (b != 0) { new_num->k = a / b; new_num->a = a % b; if (new_num->k < 0 && a < 0) { new_num->a *= -1; } } new_num->b = b; return new_num; } void print_num(number* num) { if (num->b == 0) { printf("Inf"); return; } if (num->k < 0 || num->a < 0) { printf("("); } if (num->k != 0 && num->a != 0) { printf("%d %d/%d", num->k, num->a, num->b); } else if (num->a != 0) { // num->k == 0 printf("%d/%d", num->a, num->b); } else { printf("%d", num->k); } if (num->k < 0 || num->a < 0) { printf(")"); } } int main(int argc, char const *argv[]) { long a1, b1, a2, b2; scanf("%ld/%ld %ld/%ld", &a1, &b1, &a2, &b2); number* num1 = get_num(a1, b1); number* num2 = get_num(a2, b2); char operators[4] = {'+', '-', '*', '/'}; for (int i = 0; i < 4; i++) { number* res; print_num(num1); printf(" %c ", operators[i]); print_num(num2); printf(" = "); switch (i) { case 0: res = get_num(a1*b2 + a2*b1, b1*b2); break; case 1: res = get_num(a1*b2 - a2*b1, b1*b2); break; case 2: res = get_num(a1*a2, b1*b2); break; case 3: res = get_num(a1*b2, b1*a2); break; } print_num(res); printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <signal.h> /* ȫֱ */ union semun{ int val; struct semid_ds *ds; unsigned short *array; struct seminfo *_buf; }; int shmid,semid; key_t shmkey,semkey; //char buf[50];//Ļ int r; main() { /* 1.ڴ ź */ shmkey=ftok(".",10); semkey=ftok(".",11); //100ֽڵĹڴ shmid=shmget(shmkey,100,IPC_CREAT|IPC_EXCL|0666); if(shmid == -1) { perror("ڴʧ"),exit(-1); } //1ź semid=semget(semkey,1,IPC_CREAT|IPC_EXCL|0666); if(semid == -1) { perror("źʧ"),exit(-1); } // ʼź union semun v; v.val=0; semctl(semid,0,SETVAL,v); /* 2.عڴ */ char *buf=shmat(shmid,0,0); /* 3.źIJҽв */ struct sembuf op; op.sem_num = 0; op.sem_op=1; op.sem_flg=0; while(1) { //ӱ׼ȡ r = read(0,buf,49); if(r<=0) { break; //ctrl+d } buf[r]=0; //޸ź(ź+2֤Ľ̲) semop(semid,&op,1); } //жعڴ shmdt(buf); //ɾڴ shmctl(shmid,IPC_RMID,0); //ɾź semctl(semid,0,IPC_RMID,0); }
C
#include <stdio.h> int main() { int T; scanf("%d",&T); for(int i=0;i<T;i++) {int n; scanf("%d",&n); int a[n][n]; for(int j=0;j<n;j++) {for(int k=0;k<n;k++) {scanf("%d",&a[j][k]); } } for(int k=0;k<n;k++) {for(int j=n-1;j>=0;j--) {printf("%d ",a[j][k]); } } printf("\n"); } return 0; }
C
#include<stdio.h> #include<math.h> int main() { double num,root; printf("Enter any number to find square root:\n"); scanf("%lf",&num); root = sqrt(num); printf("\nSquare root of the %.2lf is %.2lf\n", num, root); return 0; }
C
#include<errno.h> #include<stdio.h> #include "csapp.h" #define MAX_HEAP (1 << 20) static char *mem_heap; static char *mem_brk; static char *mem_max_addr; static char *heap_listp = 0; void mem_init(void){ mem_heap = (char *)Malloc(MAX_HEAP); mem_brk = (char *)mem_heap; mem_max_addr = (char *)(mem_heap + MAX_HEAP); } void *mem_sbrk(int incr){ char *old_brk = mem_brk; if((incr < 0 || ((mem_brk + incr) > mem_max_addr))){ errno = ENOMEM; fprintf(stderr, "ERROR: mem_sbrk failed. Ran out of memory...\n"); return (void *) - 1; } mem_brk += incr; return (void*)old_brk; } #define WSIZE 4 //word size #define DSIZE 8 //double word size #define CHUNKSIZE (1 << 12) #define MAX(x, y) ((x) > (y) ? (x) : (y)) #define PACK(size, alloc) ((size) | (alloc)) //pack a size and allocated into a word /*read and write a word at address p*/ #define GET(p) (*(unsigned int *)(p)) #define PUT(p, val) (*(unsigned int *)(p) = (val)) /*read the size and allocated fields from address p, p is the header or footer*/ #define GET_SIZE(p) (GET(p) & ~0x7) #define GET_ALLOC(p) (GET(p) & 0x1) /*compute the address of p's header and footer*/ /*The header need to be setted before the footer*/ #define HDRP(bp) ((char *)(bp) - WSIZE) #define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE) /*compute the address of nexr and previous block*/ #define NEXT_BLKP(bp) ((char *)(bp) + GETSIZE(((char *)(bp) - WSIZE))) #define PREV_BLKP(bp) ((char *)(bp) - GETSIZE(((char *)(bp) - DSIZE))) int mm_init(void){ /*Create the initial empty heap*/ if((heap_listp = mem_sbrk(4*WSIZE)) == (void *) - 1) return -1; PUT(heap_listp, 0); //start PUT(heap_listp + WSIZE, PACK(DSIZE, 1)); //Prologue header PUT(heap_listp + (2*WSIZE), PACK(DSIZE, 1)); //Prologue footer PUT(heap_listp + (3*WSIZE), PACK(0, 1)); //Epilogue header /*extent the empty heap with a free block of CHUNKSIZE bytes*/ if(extend_heap(CHUNKSIZE / WSIZE) == NULL) return -1; return 0; } static void *extend_heap(size_t words){ char *bp; size_t size; /*Allocate an even number of words to maintain alignment*/ size = (words & 1) ? (words+1) * WSIZE : words * WSIZE; if((long)(bp = mem_sbrk(size)) == -1) return NULL; //extend the memory PUT(HDRP(bp), PACK(size, 0)); //new block's header PUT(FTRP(bp), PACK(size, 0)); //new block's footer PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); //new epilogue's header return coalesce(bp); } static void *coalesce(void *bp){ size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp))); size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp))); size_t size = GET_SIZE(HDRP(bp)); if(prev_alloc && next_alloc) return bp; else if(prev_alloc && !next_alloc){ size += GET_SIZE(HDRP(NEXT_BLKP(bp))); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); } else if(!prev_alloc && next_alloc){ size += GET_SIZE(FTRP(PREV_BLKP(bp))); PUT(FTRP(bp), PACK(size, 0)); PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0)); bp = prev_alloc; } else{ size += GET_SIZE(FTRP(PREV_BLKP(bp))) + GET_SIZE(HDRP(NEXT_BLKP(bp))); PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0)); PUT(FTRP(NEXT_BLKP(bp)), PACK(size, 0)); bp = prev_alloc; } return bp; } void mm_free(void *bp){ size_t size = GET_SIZE(HDRP(bp)); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); coalesce(bp); } void *mm_malloc(size_t size){ size_t asize; size_t extendsize; char *bp; if(size == 0) return NULL; if(size < DSIZE) asize = 2 * DSIZE; else asize = DSIZE * ((size + DSIZE + (DSIZE - 1)) / DSIZE); if((bp = find_fit(asize)) != NULL){ place(bp, asize); return bp; } extendsize = MAX(asize, CHUNKSIZE); if((bp = extend_heap(extendsize/WSIZE)) == NULL) return NULL; place(bp, asize); return bp; } static void *find_fit(size_t asize){ void* bp; for(bp = heap_listp; GET_SIZE(HDRP(bp)) > 0; bp = NEXT_BLKP(bp)){ if(!GET_ALLOC(HDRP(bp)) && asize < GET_SIZE(HDRP(bp))) return bp; } return NULL; } static void place(void *bp, size_t asize){ size_t csize = GET_SIZE(HDRP(bp)); if((csize - asize) >= 2 * DSIZE){ csize -= asize; PUT(HDRP(bp), PACK(asize, 1)); PUT(FTRP(bp), PACK(asize, 1)); bp = NEXT_BLKP(bp); PUT(HDRP(bp), PACK(csize, 0)); PUT(FTRP(bp), PACK(csize, 0)); }else{ PUT(HDRP(bp), PACK(csize, 1)); PUT(FTRP(bp), PACK(csize, 1)); } }
C
# include <stdlib.h> # include <stdio.h> # include <stdint.h> # include "huffman.h" # include "code.h" /*This function allocates memory for a new treeNode and returns the node. * @param s is the symbol or character in the file that the node will represent. * @param l is whether the node is a leaf node or not. * @param count is the number of occurences that symbol appears in the file . * @return tn is the treeNode. */ treeNode *newNode(uint8_t s, bool l, uint64_t count)//allocate memory for a treeNode and return { treeNode *tn = calloc(1,sizeof(treeNode)); tn->symbol =s; tn->leaf =l; tn->count =count; tn->left = NULL; tn->right = NULL; return tn; } /*This function dumps a created tree into an output file so the decoder can rebuild the same exact tree.It does a post-order traversal of the tree. * @t is the root of the file * @file is the Ofile. */ void dumpTree( treeNode *t, int file)//post order traversal { if (t->leaf)//if t is a leaf { write(file,"L",sizeof(uint8_t));//write a L to the ofile write(file,&t->symbol,sizeof(uint8_t));//followed by the symbol return; } else { dumpTree(t->left,file);//recursion to move through tree dumpTree(t->right,file); write(file,"I",sizeof(uint8_t));//write I if come across an interior node } } /*This function will join two leaf nodes together by creating an interior node. * @param l is one leaf node. * @param r is another leaf node. * @return tn is the interior node containing the summed up counts of both the leaf nodes. */ treeNode *join(treeNode *l, treeNode *r)//joins two subtrees { treeNode *tn = newNode('$',false,l->count + r->count);//creates newNode with counts of left and right tn->left = l;//set pointers correspondingly tn->right = r; return tn; } /*This function uses recursion and stacks to build the codes for each symbol in the tree. * @param t is the root of the tree * @s is the code structure being built * @table is to hold all of our codes to ge to each leaf */ void buildCode(treeNode *t, code s, code table [256])//recursion to find codes for each node post order traversal { bool check = true; uint32_t bit; if (t->leaf == true && check == true)//if tree is a leaf { table[t->symbol]= s; //copy the stack into the code table return; } else { check = pushCode(&s,0); buildCode(t->left,s, table); check = popCode(&s,&bit); check = pushCode(&s,1); buildCode(t->right,s,table); popCode(&s,&bit); } } /* This function uses the codes that were made to navigate through the huffman tree to reach the correct symbols. * @ root is the root of the huffman tree that was built * @ param t is a pointer to where the program is in the tree * @ param code are the instructions to navigate through the tree * @ return int32_t is the symbol that the code is referring too. */ int32_t stepTree(treeNode *root, treeNode **t, uint32_t code)//stepTree function used to traverse through the huffman tree { if(code ==0)//if code given is == to 0 move the node to the left pointer of the node { *t = (*t)->left; } else//if the code is 1 move the node to the right pointer of the node { *t = (*t)->right; } if ((*t)->leaf ==true)//if the node is a leaf node find the symbol and then returned the symbol { int32_t value = (*t)->symbol; *t = root; return value; } return -1;//if interior node return -1 } /*This function frees the allocated memory for a treeNode. * @param n is the node to be freed. */ void delNode(treeNode *n)//free node { free(n); } /*This function frees the memory of a whole tree using recursion. *@param t is the root of the tree. */ void delTree( treeNode *t) { if (t->leaf == true) { delNode(t); return; } else { delTree(t->left); delTree(t->right); } delNode(t);//free root }
C
#include "user.h" #include "piu.h" #include "survey.h" #include "util.h" #include "stdlib.h" #include "memory.h" #include "assert.h" // Storage of surveillance requests static int num_requests; static surveillance_request * requests_to_scan; surveillance_request* create_surveillance_request(int num_patterns, FILE* file) { int id = num_requests; requests_to_scan = (surveillance_request*)realloc(requests_to_scan, ++num_requests * (sizeof(surveillance_request))); requests_to_scan[id].id_number = id; requests_to_scan[id].write_here = file; requests_to_scan[id].num_patterns = num_patterns; requests_to_scan[id].user_patterns = calloc(num_patterns, sizeof(user)); requests_to_scan[id].piu_patterns = calloc(num_patterns, sizeof(piu)); return requests_to_scan + id; } void add_block_pattern(surveillance_request* request, int pattern_index, int user_id) { assert(request && request->num_patterns > pattern_index); add_block_id(request->user_patterns + pattern_index, user_id); } void add_follow_pattern(surveillance_request* request, int pattern_index, int user_id) { assert(request && request->num_patterns > pattern_index); add_following_id(request->user_patterns + pattern_index, user_id); } void set_piu_pattern(surveillance_request* request, int pattern_index, const char* message_substring, int poster_id, int repui_id, int repui_user_id) { assert(request && request->num_patterns > pattern_index); piu* piu_message = request->piu_patterns + pattern_index; if (message_substring) { strncpy(piu_message->piu_text_utf8, message_substring, sizeof(piu_message->piu_text_utf8)); piu_message->piu_length = strlen(piu_message->piu_text_utf8); } if(poster_id) piu_message->user_id_of_poster = poster_id; if(repui_id) piu_message->piu_id_of_repiu = repui_id; if(repui_user_id) piu_message->user_id_of_repiu; } /* A surveillance request is an array of N user-Piu patterns. If the input Piu matches one of these patterns, archive (fwrite) the Piu to the FILE handle. The input Piu matches a user-piu pattern if: 1.) The Piu text in the pattern is a substring of the input Piu’s text; AND 2.) All ids_following and ids_blocked in the user pattern are followed/blocked by the input Piu’s user; AND 3.) All of the NONZERO fields in the piu pattern match the input Piu. Values set to zero are “don’t care” inputs. */ void surveil(piu* entry) { }
C
#include <stdio.h> int cryp(char text[101]){ char result[101]; int cont = 0; for (int i = 0; text[i] != '\0'; ++i) { if(text[i] == 'a'){ cont++; result[i] = 'b'; }else{ result[i] = text[i]; } } printf("Texto Criptografado:\n"); puts(result); return cont; } int main() { char texto[101]; int cont; printf("Digite o texto:\n"); gets(texto); cont = cryp(texto); printf("Letras modificadas:\n"); printf("%d\n", cont); return 0; }
C
#include "cpu.h" int main(int argc, char *argv[]) { char *instruccionESO; unsigned int instruccion = 0; int resultadoEjecucion; cargar_archivo_de_configuracion(CONFIG_PATH); int header = 0; // Conectar con kernel if (conectar_al_kernel() == -1) { printf("No se pudo conectar con el kernel\n"); exit(1); } printf("\nConexión con kernel establecida\n"); enviar_handshake_al_kernel(); // Conectar con MSP if (conectar_al_msp() == -1) { printf("No se pudo conectar con la MSP\n"); exit(1); } printf("Conexión con MSP establecida\n"); // Me quedo esperando TCBs del kernel while(1) { // Recibe desde socket los tcbs que vienen del kernel. recv(kernel.socket, &header, sizeof(int32_t), 0); if (header == solicitudEjecucion) tcb = deserializarTCB(kernel.socket); else { printf("me mandaron fruta %d", header); exit(1); //analizar porque me mandaron fruta } if (tcb == NULL) { //ver que pasa si no recibimos nada del kernel } printf("TCB recibido. PID: %d TID: %d Quantum: %d\n", tcb->pid, tcb->tid, tcb->quantum); // Mientras el quantum no se termine y el puntero no llegue a fin de codigo, sigo pidiendo instrucciones a la memoria para ejecutar while (tcb->quantum > 0) { instruccionESO = leer_de_memoria(tcb->pid, tcb->punteroInstruccion, 4); { //ver que pasa si no recibimos nada de la MSP } memcpy(&instruccion, instruccionESO, sizeof(int)); tcb->punteroInstruccion += sizeof(int); resultadoEjecucion = ejecutar(instruccion); switch(resultadoEjecucion) { //INTE //finquantum //XXXX //error //analizar los posibles casos de finalizacion } tcb->quantum--; if (tcb->quantum == 0) { size_t size = sizeof(int32_t) * 2 + sizeof(t_tcb); char *mensajeSerializado = serializar_envio_TCB(*tcb, finQuantum); send(kernel.socket, mensajeSerializado, size, 0); free(mensajeSerializado); } usleep(retardo); } } //me pinche o algo exit(1); } // ---------------------------------------------------------------------- // Funciones privadas void cargar_archivo_de_configuracion(char *configPath) { configuracion = config_create(configPath); if (config_has_property(configuracion, "IP_MSP")) msp.ip = config_get_string_value(configuracion, "IP_MSP"); if (config_has_property(configuracion, "PUERTO_MSP")) msp.puerto = config_get_int_value(configuracion, "PUERTO_MSP"); if (config_has_property(configuracion, "IP_KERNEL")) kernel.ip = config_get_string_value(configuracion, "IP_KERNEL"); if (config_has_property(configuracion, "PUERTO_KERNEL")) kernel.puerto = config_get_int_value(configuracion, "PUERTO_KERNEL"); if (config_has_property(configuracion, "RETARDO")) retardo = config_get_int_value(configuracion, "RETARDO") * 1000; //por 1000 porque el usleep son microsegundos y el que viene en el archivo cfg son milisegundos printf("IP kernel: %s\n", kernel.ip); printf("Puerto kernel: %d\n", kernel.puerto); printf("IP MSP: %s\n", msp.ip); printf("Puerto MSP: %d\n", msp.puerto); printf("Retardo ejecución: %d milisegundos\n", retardo / 1000); } int conectar_al_kernel() { kernel.socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in direccion; direccion.sin_addr.s_addr = inet_addr(kernel.ip); direccion.sin_port = htons(kernel.puerto); direccion.sin_family = AF_INET; return connect(kernel.socket, (struct sockaddr *) &direccion, sizeof(struct sockaddr)); } int conectar_al_msp() { msp.socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in direccion; direccion.sin_addr.s_addr = inet_addr(msp.ip); direccion.sin_port = htons(msp.puerto); direccion.sin_family = AF_INET; return connect(msp.socket, (struct sockaddr *) &direccion, sizeof(struct sockaddr)); } void enviar_handshake_al_kernel() { size_t size; void *mensajeSerializado = serializar_handshake(soyCpu, &size); send(kernel.socket, mensajeSerializado, size, 0); mensajeSerializado = serializar_handshake(estructuraCpu, &size); send(kernel.socket, mensajeSerializado, size, 0); //esta actualmente manejado como 2 handshake seguidos free(mensajeSerializado); } // ---------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------- /* int enviarTCBAKernel(int socket, int codigoRetorno) { char *msgRetorno=string_new(); // Hay mensaje de retorno para las respuestas de la memoria char * mensaje = serializar_envio_TCB(*tcb, codigoRetorno, msgRetorno); if (!offlineKernel) { if ( send(socketKernel, mensaje, sizeof(*mensaje), MSG_NOSIGNAL) == -1 ){ printf("Error al enviar tcb al kernel\n"); exit(1); } free(mensaje); int32_t * tipo = malloc(sizeof(int32_t)); if (recv(socketMSP, tipo, sizeof(int32_t), 0) == -1){ printf("Error al recibir respuesta de envio de tcb al kernel\n"); exit(1); } } if (offlineKernel) return 0; else return atoi(deserializar_respuesta_solicitud(socketKernel)); } char* mapearError(int codigoError) { switch (codigoError) { case ERR_EJECUCION_DIVCERO: return "DIVR: Division por cero"; break; case ERR_EJECUCION_INSTPROT: return "No se puede ejecutar la instruccion protegida en modo usuario"; break; case MEMORIA_NOCONEXION: return "No hay conexion con la memoria"; break; case ERR_MEMORIA_MALC: return "MALC: El valor del registro A es 0"; break; case EJECUCION_TERMINAR: return "XXXX: Fin de programa"; break; case MEMORIA_INSTRINVALIDA: return "Instruccion invalida"; break; case EJECUCION_QUANTUMFINALIZADO: return "Ejecucion terminada por quantum"; break; case MEMORIA_NODATOS: return "Error de transmision de datos con la MSP"; break; } } */
C
#include "../rtv1.h" static t_double3 reinit_double() { t_double3 rgb; rgb.x = 1; rgb.y = 1; rgb.z = 1; return (rgb); } static t_double3 hex_to_double(t_env *env, t_pars *pars, char *str) { char *tmp; t_double3 rgb; double hex[6]; int i; tmp = ft_strnew(ft_strlen(str)); tmp = ft_strcpy(tmp, str); i = 0; while (tmp[i] != '\0' && i < 6) { tmp[i] = ft_toupper(tmp[i]); if (tmp[i] >= 48 && tmp[i] <= 57) hex[i] = tmp[i] - 48; else if (tmp[i] >= 65 && tmp[i] <= 70) hex[i] = tmp[i] - 55; else { pars_error(env, pars, "Mauvais typage hexadecimal.", 1); return (reinit_double()); } i++; } rgb.x = (hex[0] * 16 + hex[1]) / 255; rgb.y = (hex[2] * 16 + hex[3]) / 255; rgb.z = (hex[4] * 16 + hex[5]) / 255; return (rgb); } void check_color_light(t_env *env, t_pars *pars, t_light **light, char *value) { t_light *tmp; tmp = *light; if (ft_strcmp(value, "red") == 0) tmp->color = hex_to_double(env, pars, RED); else if (ft_strcmp(value, "blue") == 0) tmp->color = hex_to_double(env, pars, BLUE); else if (ft_strcmp(value, "green") == 0) tmp->color = hex_to_double(env, pars, GREEN); else if (ft_strcmp(value, "lightblue") == 0) tmp->color = hex_to_double(env, pars, LIGHT_BLUE); else if (ft_strcmp(value, "lightgreen") == 0) tmp->color = hex_to_double(env, pars, LIGHT_GREEN); else if (ft_strcmp(value, "orange") == 0) tmp->color = hex_to_double(env, pars, ORANGE); else if (ft_strcmp(value, "pink") == 0) tmp->color = hex_to_double(env, pars, PINK); else if (ft_strcmp(value, "purple") == 0) tmp->color = hex_to_double(env, pars, PURPLE); else tmp->color = hex_to_double(env, pars, value); if (value != NULL) free(value); } void check_color_obj(t_env *env, t_pars *pars, t_object **object, char *value) { t_object *tmp; tmp = *object; if (ft_strcmp(value, "red") == 0) tmp->color = hex_to_double(env, pars, RED); else if (ft_strcmp(value, "blue") == 0) tmp->color = hex_to_double(env, pars, BLUE); else if (ft_strcmp(value, "green") == 0) tmp->color = hex_to_double(env, pars, GREEN); else if (ft_strcmp(value, "lightblue") == 0) tmp->color = hex_to_double(env, pars, LIGHT_BLUE); else if (ft_strcmp(value, "lightgreen") == 0) tmp->color = hex_to_double(env, pars, LIGHT_GREEN); else if (ft_strcmp(value, "orange") == 0) tmp->color = hex_to_double(env, pars, ORANGE); else if (ft_strcmp(value, "pink") == 0) tmp->color = hex_to_double(env, pars, PINK); else if (ft_strcmp(value, "purple") == 0) tmp->color = hex_to_double(env, pars, PURPLE); else tmp->color = hex_to_double(env, pars, value); if (value != NULL) free(value); }
C
#include <stdio.h> int main() { int answer1, answer2; printf("Input the value of answer1: "); scanf("%d", &answer1); printf("Input the value of answer2: "); scanf("%d",&answer2); if (answer1 > answer2) { printf("answer1 is bigger"); } else if (answer1 < answer2) { printf("answer2 is bigger"); } else { printf("They are equal"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int x = 0; int y = 1; while (x < 255) { printf("%d %02x\n", x, x); int z = y; y = x + y; x = z; } return 0; }
C
#include "dht11.h" static int get_level(int time, _Bool status) { int sec = 0; while (gpio_get_level(GPIO_DHT11) == status) { if (sec > time) return -1; sec++; ets_delay_us(1); } return sec; } static void set_up_dht11(int *check) { gpio_set_direction(GPIO_DHT11, GPIO_MODE_OUTPUT); gpio_set_level(GPIO_DHT11, 0); ets_delay_us(20000); gpio_set_level(GPIO_DHT11, 1); ets_delay_us(40); gpio_set_direction(GPIO_DHT11, GPIO_MODE_INPUT); *check = get_level(80, 0); if (*check <= 0) write(2, "ERROR: set_up_dht11 0\n", 22); *check = get_level(80, 1); if (*check <= 0) write(2, "ERROR: set_up_dht11 1\n", 22); } static void get_5_byte_dht11(int *arr_byte, int *check) { for (int bit = 1, byte = 0; bit < 41; bit++) { *check = get_level(50, 0); if (*check <= 0) write(2, "ERROR: get_5_byte_dht11 0\n", 26); *check = get_level(72, 1); if (*check <= 0) write(2, "ERROR: get_5_byte_dht11 1\n", 26); if (*check > 40) { arr_byte[byte] <<= 1; arr_byte[byte] += 1; } else arr_byte[byte] <<= 1; if (bit % 8 == 0) byte++; } if (arr_byte[4] != (arr_byte[0] + arr_byte[1] + arr_byte[2] + arr_byte[3])) { write(2, "ERROR: wrong checksum\n", 22); } } int *get_data_dht11() { int check = 0; int *arr_byte = malloc(sizeof(int) * 5); bzero(arr_byte, sizeof(int) * 5); set_up_dht11(&check); get_5_byte_dht11(arr_byte, &check); return arr_byte; }
C
/* 6. Escreva um programa que pede para o usuário digitar 5 inteiros e imprime o menor desses inteiros. Deve haver apenas um scanf no código e nesse scanf deve haver apenas um %d. */ #include <stdio.h> #include <limits.h> int main() { int inteiros = 0, numero, menor, var = 0; while(inteiros < 5) { printf("Digite um numero:"); scanf("%d", &numero); if(var == 0) { menor = numero; var = 1; } if(menor > numero) { menor = numero; } inteiros++; } printf("O menor numero e: %d\n", menor); return
C
/* * Filename: makeAnagramTable.c * Author: Diana Ho * Userid: cs30xje * Description: Creats an array of struct anagram objects on the Heap * Date: February 18, 2015 * Sources of Help: PA3 Write up, Piazza, Discussion notes, friends */ /* Include files */ #include "pa3.h" #include "pa3_strings.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> /* Define variables */ /* * Function name: makeAnagramTable() * Function prototype: int makeAnagramTable( const char* filename, * struct anagramInfo* info ); * Description: This function is responsible for creating an array of struct * anagram objects on the Heap using malloc and realloc for * dynamic memory allocation and populating the struct anagramInfo * parameter with the array and number of elements. * Each struct anagram object will contain the original word read * from the dictionary file and a lowercase sorted version of * the word. * Parameters: * arg 1: const char* filename * arg 2: struct anagramInfo* info * Side Effects: None * Error Conditions: If any errors occur during processing the function should * clean up any resources and return errno. * Return Value: Returns errno if any errors occur during processing * Reutrns 0 if there are no errors */ int makeAnagramTable( const char* filename, struct anagramInfo* info ) { /* Initialize all variables */ FILE * fp; struct anagram *anagramPtr; struct anagram *new; char *strptr; // char word[SIZE]; int count = 0; int index = 0; /* Clear errno */ errno = 0; /* Attempt to open filename via fopen() */ fp = fopen( filename, FILE_OPEN_MODE ); /* If fopen() returned NULL, return errno */ if( fp == NULL ) return errno; /* Attempt to allocate memory for the first struct anagram using * malloc() or realloc() */ anagramPtr = ( struct anagram* ) malloc( sizeof( struct anagram)); /* If null is returned, close the file with fclose() and return errno */ if( anagramPtr == NULL ) { (void) fclose( fp ); return errno; } /* If memory allocation is successful, zero-fill the newly allocated * struct with memset() and copy into the word member of the struct * the first word in filename using fgets() */ (void) memset( anagramPtr, 0, sizeof( struct anagram ) ); //count++; while( fgets( anagramPtr[count].word, SIZE, fp ) != NULL ) { index = 0; /* Using strchr(), replace the newline character if present * with a null-terminator */ strptr = strchr( anagramPtr[count].word, '\n' ); if( strptr != NULL ) { *strptr = '\0'; } /* Copy the word into the sorted member of the struct converting * each character to lowercase using tolower() */ (void)strcpy( anagramPtr[count].sorted, anagramPtr[count].word ); while( index <= strlen( anagramPtr[count].sorted ) ) { anagramPtr[count].sorted[index] = tolower( anagramPtr[count].sorted[index] ); index++; } //(void)strncpy( anagramPtr[count-1].sorted, word, SIZE); /* Using qsort() and charCompare module, sort the sorted member of * the anagram struct */ qsort( anagramPtr[count].sorted, strlen( anagramPtr[count].sorted ), sizeof( char ), charCompare ); /* Use realloc() to increase the size of the dynamically allocated * array to make room for another anagram struct */ new = realloc( anagramPtr, (count + 2)*sizeof(struct anagram)); /* Check if realloc() fails */ if( new == NULL ) { /* Release any memory allocated up to this point */ free( anagramPtr ); // anagramPtr = NULL; free( new ); /* Close any open files with fclose() */ (void) fclose( fp ); /* Return errno */ return errno; } /* Else zero-fill the newly allocated struct and attempt to read * the next word into the word member. Copy the word into the sorted * member, converting each character to lowercase and then sort * the sorted member with qsort() */ anagramPtr = new; (void)memset( &(anagramPtr[count+1]), 0, sizeof( struct anagram ) ); count++; } /* Sort the dynamically allocated array of anagram structs using * qsort() and the assembly module anagramCompare */ qsort( anagramPtr, count, sizeof( struct anagram ), anagramCompare ); /* Set the number of anagrams processed into the numOfAnagrams member * of the struct anagramInfo argument */ info -> numOfAnagrams = count; /* Set the anagramPtr member to point to the array */ info -> anagramPtr = anagramPtr; /* Return 0 */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/resource.h> #include <fcntl.h> #include <ctype.h> #include "errors.h" #define SOCK_PATH "./sock" #define MAX_CLI 5 #define BUFF_SIZE 4096 //ideal 4096 #define TIMEOUT_SEC 60 #define DEBUG //--------------------------------------------------------- // this function puts a 0 on the end of string void fix_string(char *word){ word[strlen(word)-1] = '\0'; } // sends an information about functionality void help(int socket_num){ char buff[BUFF_SIZE]; sprintf(buff, "Zoznam prikazov:\n"); strcat(buff, "- info: zobrazi cas, proc. cas a pamat\n"); strcat(buff, "- help: zobrazi zoznam prikazov\n"); strcat(buff, "- run 'name': spocita pocet riadkov, slov a znakov v 'name'\n"); strcat(buff, "- quit: ukonci spojenie klienta so serverom\n"); strcat(buff, "- halt: ukonci vsetky spojenia na serveri"); try_write(write(socket_num, buff, strlen(buff))); } // sends date, time, processor time and memory usage void info(int socket_num){ char akt_cas[100]; char proc_cas[100]; char mem_use[100]; char buff[BUFF_SIZE]; int i,a; struct timeval cas; struct rusage usage; //gettimeofday(&cas, NULL); asm("movl $116, %%eax;" "push %0;" "push %%eax;" "int $0x80;" "pop %%eax;" "pop %%eax;" : : "r"(&cas) : "%eax" ); // specifying format of the message strftime(akt_cas, sizeof(akt_cas), "Datum: %d.%m.%Y Cas: %H:%M:%S", localtime((time_t *)&cas.tv_sec)); // just to make sure that processor time will be visible for (i=0;i<10000000;i++) { a = a*a; a = a % 10; } //getrusage(RUSAGE_SELF, &usage); asm("movl $117, %%eax;" "push %0;" "push %1;" "push %%eax;" "int $0x80;" "pop %%eax;" "pop %%eax;" "pop %%eax;" : : "r"(&usage), "r"(RUSAGE_SELF) : "%eax" ); // specifying format of the messages sprintf(proc_cas, "Proc. cas: %ld s, %ld us", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec); sprintf(mem_use, "Pamat: %ldkb", usage.ru_maxrss); // connect the messages sprintf(buff,"%s %s %s", akt_cas, proc_cas, mem_use); // send information to socket try_write(write(socket_num, buff, strlen(buff))); } // recieve file and count lines, words, chars and send result to socket void run(char *msg, int socket_num){ int recieved, index, i, line_num = 1, word_num = 0, char_num = 0, word = 0; char buff[BUFF_SIZE], number[15]; memset(buff, 0, BUFF_SIZE); // read while there is something to read on socket while((recieved = try_read(read(socket_num, buff, BUFF_SIZE))) > 0){ #ifdef DEBUG printf("Prijimam buffer\n"); #endif //printf("%s\n",buff); // iterate through the chars of read buffer for (i = 0; i < recieved; i++){ if (!isspace(buff[i])){ char_num++; word = 1; } else{ if (word){ word_num++; } word = 0; } if (buff[i] == '\n'){ line_num++; } } // if this read was the last if (recieved < BUFF_SIZE){ break; } // clear buffer and read 'run ' memset(buff, 0, BUFF_SIZE); try_read(read(socket_num, buff, 4)); } // specify the message memset(buff, 0, BUFF_SIZE); memset(number, 0, BUFF_SIZE); strcat(buff, "Pocet riadkov: "); sprintf(number, "%d", line_num); strcat(buff, number); strcat(buff, ", pocet slov: "); sprintf(number, "%d", word_num); strcat(buff, number); strcat(buff, ", pocet znakov: "); sprintf(number, "%d", char_num); strcat(buff, number); #ifdef DEBUG printf("Odosielam spravu\n"); #endif // send the message to socket try_write(write(socket_num, buff, strlen(buff))); } //--------------------------------------------------------- int server() { int index, line_num = 1, word_num = 0, char_num = 0, word = 0, cread; int s, i, j, ret_val, lis_socket, recieved, maxfd, cli_set[MAX_CLI]; struct sockaddr_un ad, cli; struct timeval cas; char buff[BUFF_SIZE]; char file_name[50], number[15]; fd_set fdset; FILE *fp = NULL; // clear set for clients for (i=0;i<MAX_CLI;i++){ cli_set[i] = 0; } #ifdef DEBUG printf("Zapinam server\n"); #endif if ((lis_socket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { // error while opening a socket perror("socket"); exit(1); } #ifdef DEBUG printf("Socket vytvoreny uspesne (%d)\n", lis_socket); #endif // define address and socket type ad.sun_family = AF_UNIX; strcpy(ad.sun_path, SOCK_PATH); unlink(SOCK_PATH); if (bind(lis_socket, (struct sockaddr *) &ad, sizeof(ad)) == -1) { // error while binding the socket perror("bind"); exit(1); } #ifdef DEBUG printf("Bind prebehol uspesne\n"); #endif if (listen(lis_socket, 5) == -1) { // problem listening on socket perror("listen"); exit(1); } #ifdef DEBUG printf("Listen prebehol uspesne\n"); #endif // cycle for listening for incoming messages for (;;) { #ifdef DEBUG printf("\n"); #endif // prepare variables and set up the set FD_ZERO(&fdset); FD_SET(0, &fdset); FD_SET(lis_socket, &fdset); cas.tv_sec = TIMEOUT_SEC; cas.tv_usec = 0; maxfd = lis_socket; memset(buff, 0, BUFF_SIZE); // add clients to the set and find max file desc. for (i = 0; i < MAX_CLI; i++){ if (cli_set[i] > 0){ FD_SET(cli_set[i], &fdset); } if (cli_set[i] > maxfd){ maxfd = cli_set[i]; } } #ifdef DEBUG printf("Stav klientov: "); for(i=0;i<MAX_CLI;i++){ printf("%d ", cli_set[i]); } printf("\nSpustam select\n"); #endif if ((ret_val = select(maxfd + 1, &fdset, NULL, NULL, &cas)) <= 0){ if (ret_val == 0){ printf("Nikto tu nie je.. koncim\n"); exit(0); } // problem executing select perror("select"); exit(1); } if (FD_ISSET(lis_socket, &fdset)){ // new connection incomming if ((s = accept(lis_socket, NULL, NULL)) == -1) { // problem accepting message perror("accept"); exit(1); } #ifdef DEBUG printf("Nove pripojenie (%d)\n", s); #endif // add new client to the set for (i = 0; i < MAX_CLI; i++){ if (cli_set[i] == 0){ cli_set[i] = s; break; } } } if (FD_ISSET(0, &fdset)){ // something has been writen on the stdin recieved = try_read(read(0, buff, BUFF_SIZE)); fix_string(buff); if (strcmp("help", buff) == 0) { help(0); } else if(strcmp("info", buff) == 0){ info(0); } else if (strncmp("run", buff, 3) == 0){ line_num = 1; word_num = 0; char_num = 0; word = 0; // parse file name from argument strncpy(file_name, buff + 4, strlen(buff) - 4); // open the file only for reading fp = fopen(file_name, "r"); if (fp == NULL){ printf("Subor sa nepodarilo otvorit\n"); continue; } #ifdef DEBUG printf("Subor uspesne otvoreny\n"); #endif // SAME AS IN void run(int socket_num); while((cread = fread(buff, 1, BUFF_SIZE, fp)) > 0){ #ifdef DEBUG printf("Citam zo suboru\n"); #endif // count elements in buffer for (i = 0; i < cread; i++){ if (!isspace(buff[i])){ char_num++; word = 1;} else{ if (word){ word_num++;} word = 0; } if (buff[i] == '\n'){ line_num++;} } // last read was not full buffer -> end cycle if (cread < BUFF_SIZE){ break;} } // finished reading from file #ifdef DEBUG printf("Dokoncil som citanie\n"); #endif fclose(fp); // define the message memset(buff, 0, BUFF_SIZE); strcat(buff, "Pocet riadkov: "); sprintf(number, "%d", line_num); strcat(buff, number); strcat(buff, ", pocet slov: "); sprintf(number, "%d", word_num); strcat(buff, number); strcat(buff, ", pocet znakov: "); sprintf(number, "%d", char_num); strcat(buff, number); // printf the message try_write(write(0, buff, strlen(buff))); } else if ((strcmp("quit", buff) == 0)||(strcmp("halt", buff) == 0)) { // finish all connections and end for (j = 0; j < MAX_CLI; j++){ close(cli_set[j]); } close(lis_socket); return 0; } } // iterate through clients in the set for (i = 0; i < MAX_CLI; i++){ if ((cli_set[i] != 0)&&(FD_ISSET(cli_set[i], &fdset))){ #ifdef DEBUG printf("Pokusam sa precitat (%d)\n", cli_set[i]); #endif // read message from the socket recieved = try_read(read(cli_set[i], buff, 4)); #ifdef DEBUG printf("Prijata sprava (z %d): %s\n", cli_set[i], buff); #endif if (strcmp("help", buff) == 0) { #ifdef DEBUG printf("Prijal som spravu help\n"); #endif help(cli_set[i]); } else if (strcmp("info", buff) == 0) { #ifdef DEBUG printf("Prijal som spravu info\n"); #endif info(cli_set[i]); } else if (strncmp("run", buff, 3) == 0){ #ifdef DEBUG printf("Prijal som spravu run\n"); #endif run(buff, cli_set[i]); } else if (strcmp("halt", buff) == 0) { #ifdef DEBUG printf("Prijal som spravu halt\n"); #endif // finish all connections and end for (j = 0; j < MAX_CLI; j++){ close(cli_set[j]); } close(lis_socket); return 0; } else if (strcmp("quit", buff) == 0) { #ifdef DEBUG printf("Prijal som spravu quit\n"); #endif // disconnect only the sending client close(cli_set[i]); cli_set[i] = 0; } } } } return 0; } //----------------------------------------------------------------- int client() { int ech_socket, recieved, cread; struct sockaddr_un ad; char buff[BUFF_SIZE]; char file_name[50]; FILE *fp = NULL; #ifdef DEBUG printf("Zapinam klienta\n"); #endif if ((ech_socket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { // error while opening a socket perror("socket"); exit(1); } #ifdef DEBUG printf("Socket vytvoreny uspesne (%d)\n", ech_socket); #endif // set up the type of address memset(&ad, 0, sizeof(ad)); ad.sun_family = AF_UNIX; strcpy(ad.sun_path, SOCK_PATH); #ifdef DEBUG printf("Chystam sa pripojit na server\n"); #endif if (connect(ech_socket, (struct sockaddr *) &ad, sizeof(ad)) == -1) { // error while connecting to server perror("connect"); exit(1); } #ifdef DEBUG printf("Som pripojeny na server\n"); #endif // cycle for sending commands to server for (;;) { #ifdef DEBUG printf("\n"); #endif // read command to the buffer while((cread = strlen(fgets(buff, BUFF_SIZE, stdin))) < 3){ // make sure im not reading empty line } fix_string(buff); if ((strcmp("help", buff) == 0)||(strcmp("info", buff) == 0)){ try_write(write(ech_socket, buff, 4)); } else if (strncmp("run", buff, 3) == 0){ if(strlen(buff) < 5){ printf("Tento prikaz potrebuje mat subor v argumente\n"); continue; } // parse file name from argument memset(file_name, 0, 50); strncpy(file_name, buff + 4, strlen(buff) - 4); // open the file only for reading fp = fopen(file_name, "r"); if (fp == NULL){ printf("Subor sa nepodarilo otvorit %s\n", file_name); continue; } #ifdef DEBUG printf("Subor uspesne otvoreny %s\n", file_name); #endif // read from file until the end while((cread = fread(buff, 1, BUFF_SIZE, fp)) > 0 ){ #ifdef DEBUG printf("Posielam buffer\n"); #endif if (cread < BUFF_SIZE){ // when the file is shorter than BUFF_SIZE or im finished try_write(write(ech_socket, "runs", 4)); try_write(write(ech_socket, buff, strlen(buff))); } else{ // if read the whole thing and need to read again try_write(write(ech_socket, "run ", 4)); try_write(write(ech_socket, buff, BUFF_SIZE)); } memset(buff, 0, BUFF_SIZE); } #ifdef DEBUG printf("Subor odoslany\n"); #endif fclose(fp); fp = NULL; } else if ((strcmp("quit", buff) == 0)||(strcmp("halt", buff) == 0)) { try_write(write(ech_socket, buff, 4)); #ifdef DEBUG printf("Zatvaram socket\n"); #endif close(ech_socket); exit(0); } // recieve message from server and print memset(buff, 0, BUFF_SIZE); recieved = try_read(read(ech_socket, buff, BUFF_SIZE)); #ifdef DEBUG printf("Prijal som spravu s dlzkou %d\n", recieved); #endif printf("%s\n", buff); memset(buff, 0, BUFF_SIZE); } return 0; } //----------------------------------------------------------------- int main(int argc, char *argv[]) { if ((argc == 1)||(strcmp(argv[1], "-s") == 0)) { // zapni server server(); } else if (strcmp(argv[1], "-c") == 0) { // zapni klienta client(); } else { printf("Neznamy argument...(skus -s, -c)\n"); } return 0; }
C
#ifndef UART_H #define UART_H #include <stdint.h> #include "common.h" // UART special function register offsets (add to the base address from main.h to select the UART) #define REG_UART_TX 0x00 #define REG_UART_STATUS 0x04 #define REG_UART_RX 0x08 #define REG_UART_BAUDRATE 0x0C // Bitmask of UART_STATUS #define BIT_UART_TX_BUSY (1<<0) #define BIT_UART_RX_BUSY (1<<1) #define BIT_UART_RX_ERROR_OVERRUN (1<<2) #define BIT_UART_RX_ERROR_FRAME (1<<3) // Return codes from UART_GETC() in the high byte #define UART_DATA_OK 0x0000 #define UART_NO_NEW_DATA 0xFF00 #define UART_IS_DATA_OK(x) ((x&0xFF00)==UART_DATA_OK) // data is ok when the msb 16 bits are zero //------------------------- // UART access macros //------------------------- // Setup the baudrate register #define UART_INIT(uartBaseAddr,baudRate) SET_REG(uartBaseAddr + REG_UART_BAUDRATE, (F_CLK / (baudRate * 8))) // Poll RX UART. Returns 16 bit value: high byte = status (UART_DATA_OK, UART_NO_NEW_DATA), low byte = received data value #define UART_GETC(uartBaseAddr) ( (uint16_t)(GET_REG(uartBaseAddr+REG_UART_RX)) ) // Returns > 0 If the UART is currently busy transmitting something #define UART_TX_IS_BUSY(uartBaseAddr) (GET_REG(uartBaseAddr+REG_UART_STATUS)&BIT_UART_TX_BUSY) // Send c to TX UART through FIFO. Stalls CPU if FIFO is full. #define UART_PUTC(uartBaseAddr,c) (SET_REG(uartBaseAddr+REG_UART_TX,c)) // Send c to TX UART. Blocks if UART is busy. #define UART_PUTC_BLK(uartBaseAddr,c) { while(UART_TX_IS_BUSY(uartBaseAddr)); SET_REG(uartBaseAddr+REG_UART_TX,c); } #endif
C
#include "stdio.h" int n,m,i,j,x,y,r,k,c; char map[1051][1051]; int main(){ scanf("%d%d",&n,&m); for(i = 0; i < n; i++){ scanf("%d%d", &x, &y); map[x][y] = 1; } for(k = 0; k < m; k++){ scanf("%d%d%d",&x,&y,&r); for(i = x-r>0?x-r:0,c=0; i <= x+r; i++){ for(j = y-r>0?y-r:0; j <= y+r; j++){ if(map[i][j]){ map[i][j] = 0; c++; } } } printf("%d\n", c); } }
C
#include "tp2virtual.h" unsigned lru(TabelaPagina * tabelaPagina){ int lru = tabelaPagina->referenciado[0]; int moldura = 0; //busca pela página com o menor clock for(int i = 0; i < tabelaPagina->numMolduras; i++){ if(tabelaPagina->referenciado[i] < lru){ lru = tabelaPagina->referenciado[i]; moldura = i; } } return moldura; } unsigned nru(TabelaPagina *tabelaPagina){ unsigned um = -1, dois = -1, tres = -1; //busca pela pagina que pertence a menor classe for(unsigned i = 0; i < tabelaPagina->numMolduras; i++ ){ if (tabelaPagina->referenciado[i] == 0) return i; else { if (tabelaPagina->referenciado[i] == 1 && um == -1) um = i; else if (tabelaPagina->referenciado[i] == 2 && dois == -1 && um == -1) dois = i; else if (tabelaPagina->referenciado[i] == 3 && tres == -1 && um == -1 && dois == -1) tres = i; } } if (um != -1) return um; if (dois != -1) return dois; return tres; } unsigned segundaChance(TabelaPagina *tabelaPagina, Fila *filaPaginas){ unsigned escolhido; //busca pela pagina que não foi referenciada for(unsigned i = 0; i < filaPaginas->final; i++){ if(!(filaPaginas->paginas[i].referenciado)){ escolhido = removeFila(filaPaginas, i); return escolhido; } else { //caso referenciada, desrreferenciamos e é inserida no final da fila reorganizaFila(filaPaginas, i, FALSE); i--; } } return 0; } //retorna uma posição vaga na memória unsigned escolheMoldura(TabelaPagina *tabelaPagina, Fila *filaPaginas, int substituicao){ unsigned escolhido; switch(substituicao){ case 0: escolhido = lru(tabelaPagina); break; case 1: escolhido = nru(tabelaPagina); break; case 2: escolhido = segundaChance(tabelaPagina, filaPaginas); break; } return escolhido; } //zera todos os referenciados a cada determinado tempo void resetaReferenciado(TabelaPagina *tabelaPagina){ for(int i = 0; i < tabelaPagina->numMolduras; i++ ){ switch(tabelaPagina->referenciado[i]){ case 2: tabelaPagina->referenciado[i] = 0; break; case 3: tabelaPagina->referenciado[i] = 1; break; } } }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <fcntl.h> typedef struct HistoryNode { char *command; struct HistoryNode* next; }HistoryNode; typedef struct PathNode { char *path; struct PathNode* next; }PathNode; int getInputs(char* line, char *a[128]) { char *delim = "\n \t\r\f\v"; int i = 0; char *input ; input = strtok(line, delim); while(input != NULL) { a[i] = input; i = i + 1; input = strtok(NULL, delim); } return i; } void printHistory(HistoryNode *iterator, int n) { if (iterator == NULL || n <= 0) return; printHistory(iterator->next, n-1); printf("%s\n", iterator->command); fflush(stdout); } int main(int argc, char *argv[]) { char *commandExit = "exit"; char *commandCd = "cd"; char *commandHistory = "history"; char *commandPath = "path"; char *initialPath = "/bin"; char error_message[30] = "An error has occurred\n"; if(argc <= 2) { FILE *f = NULL; if(argc == 2) { f = fopen(argv[1], "r"); if(f == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); } } else { f = stdin; } HistoryNode *head = NULL; PathNode *paths = (PathNode *)malloc(sizeof(PathNode)); paths->path = strdup(initialPath); paths->next = NULL; int numberOfCommandsCount = 0; while (1) { int redirectNum = 0, pipeNum = 0; int posOfRedirect = -1, posOfPipe = -1; int pipefd[2]; // 0 is for read, 1 is for write if (argc == 1) { printf("wish> "); fflush(stdout); } char *line = NULL; size_t buffer = 0; // Read each line of stdin if(getline(&line, &buffer, f) == EOF) { exit(0); } // As history should not include blank lines if (strcmp(line, "\n") == 0) { continue; } // Important line = strtok(line, "\n"); // History should include everything apart from only blank line numberOfCommandsCount = numberOfCommandsCount + 1; HistoryNode *newNode = (HistoryNode *)malloc(sizeof(HistoryNode)); newNode->command = strdup(line); newNode->next = head; head = newNode; char *a[128]; char *b[128]; // To account for < and | being there without spaces char *newLine = (char *) malloc ((strlen(line) + 33) * sizeof(char)); int c = 0; for(int i = 0; i < strlen(line); i++) { if(line[i] == '>' || line[i] == '|') { newLine[c++] = ' '; newLine[c++] = line[i]; newLine[c++] = ' '; continue; } newLine[c++] = line[i]; } newLine[c++] = '\0'; free(line); // Getting the inputs int args = getInputs(newLine, a); if(args == 0) { continue; } // Counting number of pipes and redirections for (int i = 0; i < args; i++) { if (strcmp(a[i], ">") == 0) { redirectNum = redirectNum + 1; posOfRedirect = i; } if (strcmp(a[i], "|") == 0) { pipeNum = pipeNum + 1; posOfPipe = i; } } // If more than 1 pipe/redirect if (redirectNum > 1 || pipeNum > 1 || (redirectNum >= 1 && pipeNum >= 1)) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } // Checking that there is only 1 file after redirect if (redirectNum == 1) { // If there is more than 1 value after > or no values before > if (args-1-posOfRedirect !=1 || posOfRedirect == 0) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } // Redirect Command is OK else { a[posOfRedirect] = NULL; } } // Checking for piping if (pipeNum == 1) { // No values before and after pipe if (args-1-posOfPipe == 0 || posOfPipe == 0) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } else { pipe(pipefd); int counter = 0; for(int i = posOfPipe + 1; i < args; i++) { b[counter] = a[i]; counter++; } b[counter] = NULL; a[posOfPipe] = NULL; } } // If exit command if(strcmp(a[0], commandExit) == 0) { if(args > 1) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } exit(0); } // If cd command else if(strcmp(a[0], commandCd) == 0) { if(args != 2) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } int resultCd = chdir(a[1]); if(resultCd != 0) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } } // If history command else if(strcmp(a[0], commandHistory) == 0) { if(args > 2) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } if (args == 1) { HistoryNode *iterator = head; printHistory(iterator, numberOfCommandsCount); iterator = NULL; } if (args == 2) { int number = ceil(atof(a[1])); // If not integer or has 'e' if ((number == 0 && a[1][0]!='0') || (strchr(a[1], 'e')!=NULL)) { write(STDERR_FILENO, error_message, strlen(error_message)); free(newLine); continue; } HistoryNode *iterator = head; printHistory(iterator, number); iterator = NULL; } } // If path command else if(strcmp(a[0], commandPath) == 0) { // Deleting previous space while(paths != NULL) { PathNode *cur = paths; paths = paths->next; free(cur); } for(int i = 1; i < args; i++) { PathNode *temp = (PathNode *)malloc(sizeof(PathNode)); temp->path = strdup(a[i]); temp->next = paths; paths = temp; } } // Commands to find inside the paths else { PathNode *temp = paths; PathNode *temp2 = paths; int flag = 0, flagForSecondChild = 0, flagExecv = 0, flagFork = 0; while(temp!=NULL) { //printf("HI\n"); char *pathToCheck = strdup(temp->path); strcat(pathToCheck, "/"); strcat(pathToCheck, a[0]); a[args] = NULL; if(access(pathToCheck, X_OK) == 0) { flag = 1; int rc = fork(); if (rc == 0) { // Reference - https://stackoverflow.com/questions/2605130/redirecting-exec-output-to-a-buffer-or-file if(redirectNum == 1) { int fd = open(a[args-1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); dup2(fd, 1); dup2(fd, 2); close(fd); } if (pipeNum == 1) { // close the read for 1st one close(pipefd[0]); // close reading end in the child dup2(pipefd[1], 1); // send stdout to the pipe dup2(pipefd[1], 2); // send stderr to the pipe close(pipefd[1]); } flagExecv = execv(pathToCheck, a); } // fork error else if (rc == -1) { flagFork = -1; } else { rc = (int) wait(NULL); if (pipeNum == 1) { while(temp2!=NULL) { char *pathToCheckForSecondChild = strdup(temp2->path); strcat(pathToCheckForSecondChild, "/"); strcat(pathToCheckForSecondChild, b[0]); if(access(pathToCheckForSecondChild, X_OK) == 0) { flagForSecondChild = 1; int forkpipe = fork(); // 2nd child if(forkpipe == 0) { close(pipefd[1]); // close writing end in the child dup2(pipefd[0], 0); // send stdin to the pipe close(pipefd[0]); flagExecv = execv(pathToCheckForSecondChild, b); } // fork error else if (forkpipe == -1) { flagFork = -1; } else { close(pipefd[1]); close(pipefd[0]); forkpipe = (int) wait(NULL); } } free(pathToCheckForSecondChild); temp2 = temp2->next; } } } } free(pathToCheck); temp = temp->next; } // Cannot access anywhere in the paths or the execv/fork returns as error if (flag == 0 || (pipeNum == 1 && flagForSecondChild == 0) || flagExecv == -1 || flagFork == -1) { // Incase the 1st one is a bad argument, we still write error message to the new file if(redirectNum == 1) { int fd = open(a[args-1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); write(fd, error_message, strlen(error_message)); close(fd); } else { write(STDERR_FILENO, error_message, strlen(error_message)); } } } // Freeing space for(int i = 0; i < args; i++) { a[i] = NULL; b[i] = NULL; } free(newLine); } } else { write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); } return 0; }
C
#include "systemf.h" void welcome(){ system("clear"); printf("--------------------------------------\n"); printf("| WELCOME TO THE GAME |\n"); printf("--------------------------------------\n"); usleep(1000000); // 1 seconde d'attente } void begin() { system("clear"); printf("--------------------------------------\n"); printf("| LET'S BEGIN |\n"); printf("--------------------------------------\n"); usleep(1000000); // 1 seconde d'attente } void listen_(int sock, char side[], int nbr_co){ printf("%s : Listen connection\n", side); if(listen(sock, nbr_co +1) < 0) { perror("listen"); exit(EXIT_FAILURE); }else{ printf("%s : Listen Created !\n", side); } } int socket_(char side[]) { printf("%s : Creating a Socket\n", side); int sock = socket(AF_INET, SOCK_STREAM, 0) ; if (sock < 0) { perror ("socket"); exit (EXIT_FAILURE); }else{ printf("%s : Socket Created !\n", side); return sock; } } int bindF(int sock, char port[], struct sockaddr_in* adresse, char side[]) { int port_ = atoi(port); printf("%s : Bind INADDR_ANY\n", side); adresse->sin_addr.s_addr = INADDR_ANY; adresse->sin_family = AF_INET; if(port_ == -1){ int port = 2345; adresse->sin_port = htons((short) port); while(bind(sock, (struct sockaddr *) adresse, sizeof(*adresse)) < 0) { port++; adresse->sin_port = htons((short) port); // port du serveur } }else{ adresse->sin_port = htons((short) atoi(port)); if (bind(sock, (struct sockaddr *) adresse, sizeof(*adresse)) < 0) { perror ("bind"); exit (EXIT_FAILURE); }else{ printf("%s : Bind Created !\n", side); } } }
C
/** * @brief Free-running timer example * @author Yiqing Huang * @date 2020/11/01 */ #include <LPC17xx.h> #include "timer.h" #include "uart_polling.h" #include "printf.h" #define TIMER1 1 void add_op(uint32_t num_op) { uint32_t x = 0; uint32_t i = 0; for ( i = 0; i < num_op; i++ ) { x++; } return; } /** * */ void get_runtime(uint8_t n_timer, void (*pfunc)(uint32_t), uint32_t num_op) { uint32_t e_tc; uint32_t e_pc; if (n_timer != 1) { // only supports timer 1 return; } LPC_TIM_TypeDef *pTimer = LPC_TIM1; pTimer->TCR = 2; // disable counter, reset counters pTimer->TCR = 1; //enable counter /* this is the operation we want to measure the time */ pfunc(num_op); pTimer->TCR = 0; //disable counter e_tc = pTimer->TC; e_pc = pTimer->PC; printf("@end: TC = %u, PC = %u. \r\n", e_tc, e_pc); return; } int main() { volatile uint8_t sec = 0; uint32_t num_op = 1; SystemInit(); __disable_irq(); timer_init_100MHZ(TIMER1); /* timer1 PCLK=100MHZ, free-running counter, no interrupts */ uart1_init(); /* uart1 is polling */ init_printf(NULL, putc); __enable_irq(); for (int i=0; i < 10; i++) { printf("repeat = %d\r\n", i); get_runtime(TIMER1, &add_op, num_op); num_op *= 10; } }
C
/* * Copyright (C) 2004-2010 Regents of the University of California. * All rights reserved. * * Author: Gautam Altekar */ #include "vkernel/public.h" #include "private.h" #define EXPECTED_MAX_ACCESS_SECTORS 200 #define EXPECTED_MAX_EP_SECTORS (EXPECTED_MAX_ACCESS_SECTORS*2) static const size_t ep_table_sz = sizeof(struct ExecPoint) * N_EP_PER_SECTOR; static const size_t access_table_sz = sizeof(struct Access) * N_ACCESS_PER_SECTOR; static struct ExecPointSector * SegmentInsnInitSector(struct Segment *seg, int sno) { struct ExecPointSector *sec; if (sno >= EXPECTED_MAX_EP_SECTORS) { LOG("WARNING: sno=%d, exceed max expected. \n", sno); } else { DEBUG_MSG(5, "Allocating insn sec %d, %d bytes\n", sno, ep_table_sz); } sec = SharedArea_Malloc(sizeof(*sec)); ASSERT(sec); List_AddTail(&sec->list, &seg->ep_sec_list); sec->t = SharedArea_Malloc(ep_table_sz); ASSERT(sec->t); sec->t_n_inuse = 0; return sec; } static INLINE struct ExecPointSector * SegmentGetExecPointTail(struct ListHead *secHead) { struct ExecPointSector * sec; if (List_IsEmpty(secHead)) { sec = NULL; } else { sec = list_entry(secHead->prev, struct ExecPointSector, list); } return sec; } /* * Returns pointer to instruction descriptor in segment storage. */ static INLINE struct ExecPoint * SegmentInsnInsert(struct Segment *seg, struct ExecPoint *in_ep) { ASSERT(seg); int sno = seg->idx_ep_sec; struct ExecPointSector *sec = SegmentGetExecPointTail(&seg->ep_sec_list); struct ExecPoint *ep; if (!sec) { sec = SegmentInsnInitSector(seg, sno); } if (sec->t_n_inuse >= N_EP_PER_SECTOR) { sno = ++seg->idx_ep_sec; ASSERT(sno == seg->idx_ep_sec); sec = SegmentInsnInitSector(seg, sno); } ASSERT(sec); ASSERT(sec->t); ep = &sec->t[sec->t_n_inuse]; *ep = *in_ep; sec->t_n_inuse++; return ep; } static INLINE uint HASH ( u64 key ) { uint kHi = (uint)(key >> 32); uint kLo = (uint)key; uint k32 = kHi ^ kLo; uint ror = 7; if (ror > 0) k32 = (k32 >> ror) | (k32 << (32-ror)); return k32 % N_ACCESS_PER_SECTOR; } static struct AccessSector * SegmentHashInitSector(struct ListHead *secHead, int sno) { int i; struct AccessSector *sec; if (sno >= EXPECTED_MAX_ACCESS_SECTORS) { LOG("WARNING: sno=%d, exceed max expected. \n", sno); } else { DEBUG_MSG(5, "Allocating hash sno %d, %d bytes\n", sno, access_table_sz); } sec = SharedArea_Malloc(sizeof(*sec)); ASSERT(sec); memset(sec, 0, sizeof(*sec)); List_AddTail(&sec->list, secHead); sec->t = SharedArea_Malloc(access_table_sz); ASSERT(sec->t); for (i = 0; i < N_ACCESS_PER_SECTOR; i++) { sec->t[i].status = Empty; } sec->t_n_inuse = 0; return sec; } static INLINE struct AccessSector * SegmentGetAccessTail(struct ListHead *secHead) { struct AccessSector * sec; if (List_IsEmpty(secHead)) { sec = NULL; } else { sec = list_entry(secHead->prev, struct AccessSector, list); } return sec; } static INLINE void SegmentInsertHash(struct ListHead *secHead, ushort *idx_sec, u64 gaddr, struct ExecPoint *ep) { int sno = *idx_sec, i; struct AccessSector *sec = SegmentGetAccessTail(secHead); if (!sec) { sec = SegmentHashInitSector(secHead, sno); } if (sec->t_n_inuse >= N_ACCESS_PER_SECTOR) { sno = ++(*idx_sec); ASSERT(sno == *idx_sec); sec = SegmentHashInitSector(secHead, sno); } ASSERT(sec); ASSERT(sec->t); sec->t_n_inuse++; i = HASH(gaddr); ASSERT(i >= 0 && i < N_ACCESS_PER_SECTOR); /* There must be a spot, otherwise sec->t_n_inuse * would be >= N_ACCESS_PER_SECTOR and we would've * rotated to a new sector already. */ while (1) { if (sec->t[i].status == Empty) { break; } i++; if (i >= N_ACCESS_PER_SECTOR) { i = 0; } } sec->t[i].status = InUse; sec->t[i].gaddr = gaddr; sec->t[i].ep = ep; } #define STRICT 1 static INLINE void SegmentAddAccess(const int isRead, struct ListHead *secHead, ushort *idx_sec, struct ExecPoint *in_ep, const ulong vaddr, const uint accessLen) { struct Segment *seg = curr_vcpu->segment; #if STRICT u64 gaddr[ARCH_MAX_ACCESS_LEN]; int i; #else u64 gaddr; #endif int accessesAtLeastOneFileByte = 0; ASSERT(accessLen > 0 && accessLen <= ARCH_MAX_ACCESS_LEN); ASSERT(current->mm->users > 0); ASSERT(seg); #if STRICT /* The access may straddle multiple vmas -- e.g., * first 2 bytes to shared memory, but last 2 bytes * to non-shared memory. This is rare, but we must * check for it. */ for (i = 0; i < accessLen; i++) { gaddr[i] = GlobalAddr_FromVirt(current->mm, vaddr+i, isRead); if (GlobalAddr_IsFileAddr(gaddr[i])) { accessesAtLeastOneFileByte = 1; } } #else /* Assume that access doesn't straddle multiple objects * (memory/file or file/file). */ gaddr = GlobalAddr_FromVirt(vaddr, isRead); if (GlobalAddr_IsFileAddr(gaddr)) { accessesAtLeastOneFileByte = 1; } #endif /* Optimization: Don't add the access to the segment if it isn't * to a file or if this is the only thread in the address space. * * XXX: rethink this carefully... * * No need to worry about mm->users changing if mm->users == 1, * since only this thread can change it. If mm->users > 1, of course * it may concurrently change -- if it decrements such that * mm->users == 1, then we may race and add the access, but no harm * done. */ if (accessesAtLeastOneFileByte || current->mm->users > 1) { int j; struct ExecPoint *ep; ep = SegmentInsnInsert(seg, in_ep); ASSERT(ep); ASSERT(ep != in_ep); if (isRead) { seg->numReads++; } else { seg->numWrites++; } for (j = 0; j < accessLen; j++) { #if STRICT SegmentInsertHash(secHead, idx_sec, gaddr[j], ep); #else SegmentInsertHash(secHead, idx_sec, gaddr+j, ep); #endif } } } void Segment_AddRead(struct ExecPoint *in_ep, ulong vaddr, uint accessLen) { struct Segment *seg = curr_vcpu->segment; SegmentAddAccess(1, &seg->read_sec_list, &seg->idx_read_sec, in_ep, vaddr, accessLen); } void Segment_AddWrite(struct ExecPoint *in_ep, ulong vaddr, uint accessLen) { struct Segment *seg = curr_vcpu->segment; SegmentAddAccess(0, &seg->write_sec_list, &seg->idx_write_sec, in_ep, vaddr, accessLen); } static struct ExecPoint * SegmentLookupAccess(u64 gaddr, const struct ListHead *secHead) { int j, k, kstart; struct AccessSector *sec; /* Find the initial probe point just once. It will be the same in all sectors and avoids multiple expensive % operations. */ k = -1; kstart = HASH(gaddr); ASSERT(kstart >= 0 && kstart < N_ACCESS_PER_SECTOR); list_for_each_entry(sec, secHead, list) { if (sec->t == NULL) { goto notfound; } k = kstart; for (j = 0; j < N_ACCESS_PER_SECTOR; j++) { if (sec->t[k].status == InUse && sec->t[k].gaddr == gaddr) { /* found it */ return sec->t[k].ep; } if (sec->t[k].status == Empty) { break; /* not found in this sector */ } k++; if (k == N_ACCESS_PER_SECTOR) { k = 0; } } } notfound: return NULL; } static void SegmentWriteRacePair(int raceFd, u64 gaddr, const struct RaceAccess *r1, const struct RaceAccess *r2) { int res; struct RacePair rr; ASSERT(raceFd >= 0); rr.gaddr = gaddr; rr.access1 = *r1; rr.access2 = *r2; Race_PrintRecord(&rr); res = write(raceFd, (void*)&rr, sizeof(rr)); ASSERT(res == sizeof(rr)); } /* * Note that if multiple bytes of instruction access intersect, * then we record the execution point of that access for each * byte. Hence the race output list is likely to have duplicates. */ static void SegmentFindIntersection(const struct Segment *a_seg, const struct ListHead *a_sectors, const struct Segment *b_seg, const struct ListHead *b_sectors) { int j; struct AccessSector *sec; ASSERT(a_sectors == &a_seg->read_sec_list || a_sectors == &a_seg->write_sec_list); ASSERT(b_sectors == &b_seg->read_sec_list || b_sectors == &b_seg->write_sec_list); list_for_each_entry(sec, a_sectors, list) { if (sec->t == NULL) { return; } for (j = 0; j < N_ACCESS_PER_SECTOR; j++) { struct Access *a = &sec->t[j]; if (a->status == InUse) { struct ExecPoint * b_ep; b_ep = SegmentLookupAccess(a->gaddr, b_sectors); if (b_ep) { ASSERT(VCPU_GetMode() & VCPU_MODE_RACEDETECT); ASSERT(NR_VCPU > 1); { struct RaceAccess r_a, r_b; r_a.loc.ep = *(a->ep); r_b.loc.ep = *b_ep; r_a.loc.task_id = a_seg->task_id; r_b.loc.task_id = b_seg->task_id; r_a.loc.vcpu_id = Segment_VCPU(a_seg)->id; r_b.loc.vcpu_id = Segment_VCPU(b_seg)->id; r_a.loc.vc = a_seg->vc; r_b.loc.vc = b_seg->vc; r_a.isRead = (a_sectors == &a_seg->read_sec_list); r_b.isRead = (b_sectors == &b_seg->read_sec_list); /* Found intersecting access. Write it to the race * file. Here we assume that a_seg is the current * task's segment. */ SegmentWriteRacePair( Segment_VCPU(a_seg)->raceFd, a->gaddr, &r_a, &r_b); //SegmentWriteRacePair(b_seg->fd, a->gaddr, &r_b, &r_a); } } } } } } void Segment_DetectRaces(const struct Segment *a_seg, const struct Segment *b_seg) { ASSERT(NR_VCPU > 1); #define DETECT(x, y) \ SegmentFindIntersection(a_seg, &a_seg->x, b_seg, &b_seg->y) /* Read-Write races. */ DETECT(read_sec_list, write_sec_list); DETECT(write_sec_list, read_sec_list); /* Write-Write races. */ DETECT(write_sec_list, write_sec_list); } struct Segment * Segment_Alloc() { struct Segment *seg; seg = SharedArea_Malloc(sizeof(*seg)); memset(seg, 0, sizeof(*seg)); List_Init(&seg->list); List_Init(&seg->ep_sec_list); List_Init(&seg->read_sec_list); List_Init(&seg->write_sec_list); seg->vcpu = curr_vcpu; seg->task_id = current->id; return seg; } static int SegmentFreeAccessSectors(struct ListHead *secHead) { int numSecsDeleted = 0; struct AccessSector *asp, *as_dummy; list_for_each_entry_safe(asp, as_dummy, secHead, list) { ASSERT(asp->t); DEBUG_MSG(5, "Freeing access sector: in_use=%d, max=%d\n", asp->t_n_inuse, N_ACCESS_PER_SECTOR); SharedArea_Free(asp->t, access_table_sz); asp->t = NULL; List_Del(&asp->list); SharedArea_Free(asp, sizeof(*asp)); numSecsDeleted++; } return numSecsDeleted; } void Segment_Free(struct Segment *seg) { #if DEBUG int vcpu_id = Segment_VCPU(seg)->id; #endif int numEpSecsDeleted = 0, numReadSecsDeleted = 0, numWriteSecsDeleted = 0; struct ExecPointSector *exp, *ex_dummy; ASSERT(vcpu_id >= 0 && vcpu_id < NR_VCPU); ASSERT(curr_vcpu->id == vcpu_id || curr_vcpu->id != vcpu_id); list_for_each_entry_safe(exp, ex_dummy, &seg->ep_sec_list, list) { ASSERT(exp->t); DEBUG_MSG(5, "Freeing ep sector: in_use=%d, max=%d\n", exp->t_n_inuse, N_EP_PER_SECTOR); SharedArea_Free(exp->t, ep_table_sz); exp->t = NULL; List_Del(&exp->list); SharedArea_Free(exp, sizeof(*exp)); numEpSecsDeleted++; } numReadSecsDeleted = SegmentFreeAccessSectors(&seg->read_sec_list); numWriteSecsDeleted = SegmentFreeAccessSectors(&seg->write_sec_list); #if DEBUG if (seg->numReads || seg->numWrites) { ASSERT(numEpSecsDeleted > 0); } else { ASSERT(numEpSecsDeleted == 0); } if (seg->numReads) { ASSERT(numReadSecsDeleted > 0); } else { ASSERT(numReadSecsDeleted == 0); } if (seg->numWrites) { ASSERT(numWriteSecsDeleted > 0); } else { ASSERT(numWriteSecsDeleted == 0); } #endif SharedArea_Free(seg, sizeof(*seg)); seg = NULL; } void Segment_OpenRaceLog(struct VCPU *vcpu, int isCreate) { int res; char *filename; filename = SharedArea_Malloc(PATH_MAX); res = snprintf(filename, PATH_MAX, "%s/vcpu-races.%d", session.dir, vcpu->id); ASSERT(res < PATH_MAX); vcpu->raceFd = syscall(SYS_open, filename, isCreate ? (O_CREAT | O_RDWR | O_TRUNC) : O_RDONLY, S_IRUSR | S_IWUSR); if (vcpu->raceFd < 0) { FATAL("can't open race log file ``%s''.\n", filename); } SharedArea_Free(filename, PATH_MAX); filename = NULL; } void Segment_CloseRaceLog(struct VCPU *vcpu) { ASSERT(vcpu->raceFd >= 0); SysOps_Close(vcpu->raceFd); vcpu->raceFd = -1; } int Segment_Init() { int i; for (i = 0; i < NR_VCPU; i++) { struct VCPU *vcpu = VCPU_Ptr(i); if (VCPU_TestMode(VCPU_MODE_RACEDETECT)) { Segment_OpenRaceLog(vcpu, 1); } else { vcpu->raceFd = -1; } } ASSERT(0 < N_EP_PER_SECTOR && N_EP_PER_SECTOR <= USHRT_MAX); ASSERT(0 < N_ACCESS_PER_SECTOR && N_ACCESS_PER_SECTOR <= USHRT_MAX); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "wise_gen.h" #include "wise_rle.h" #define SINGLE 0 #define DOUBLE 1 #define MULTI 2 #define RAW 3 #define MAXBLOCKS 2000 typedef struct block { int type; int size; unsigned char value; unsigned char value2; unsigned char *buffer; struct block *next; } block; void free_block (block *p) { if (p->type==RAW) free (p->buffer); free (p); } void free_frame (block *base) { block *p,*q; for (p=base; p!=NULL; ) { q=p; p=q->next; free_block (q); } } block *compress (unsigned char *buffer, int size) { int i,j; block *base=NULL,*p=NULL,*q=NULL; /* reading */ for (i=0; i<size; i++) { if (p==NULL) { base=(block *) safe_malloc (sizeof (block)); p=base; } else { p->next=(block *) safe_malloc (sizeof (block)); p=p->next; } p->type=SINGLE; p->value=buffer[i]; p->next=NULL; } /* preparing */ for (p=base; p!=NULL; p=p->next) { if (p->value==p->next->value) { p->size=2; p->type=MULTI; q=p->next->next; free_block (p->next); p->next=q; } else { p->buffer=(unsigned char *) safe_malloc (2); p->buffer[0]=p->value; p->buffer[1]=p->next->value; p->size=2; p->type=RAW; q=p->next->next; free_block (p->next); p->next=q; } } /* compressing */ p=base; while (p!=NULL && p->next!=NULL) { if ((p->type==RAW && p->size>=254) || (p->type==MULTI && p->size>=126)) { p=p->next; continue; } if (p->type==MULTI && p->next->type==MULTI && p->value==p->next->value && p->size+p->next->size<=126) { p->size+=p->next->size; q=p->next->next; free_block (p->next); p->next=q; continue; } if (p->type==RAW && p->next->type==RAW) { j=p->size+p->next->size; if (j>=254) { p=p->next; continue; } buffer=(unsigned char *) safe_malloc (j); for (i=0; i<p->size; i++) buffer[i]=p->buffer[i]; for (i=0; i<p->next->size; i++) buffer[i+p->size]=p->next->buffer[i]; p->size=j; p->buffer=buffer; q=p->next->next; free_block (p->next); p->next=q; continue; } p=p->next; } /* optimizing */ p=base; while (p!=NULL && p->next!=NULL) { if (p->size>=254) { p=p->next; continue; } if (p->type==RAW && p->next->type==MULTI && p->next->size==2) { j=p->size+p->next->size; if (j>=254) { p=p->next; continue; } buffer=(unsigned char *) safe_malloc (j); for (i=0; i<p->size; i++) buffer[i]=p->buffer[i]; for (i=0; i<p->next->size; i++) buffer[i+p->size]=p->next->value; p->size=j; p->buffer=buffer; q=p->next->next; free_block (p->next); p->next=q; continue; } if (p->type==RAW && p->next->type==RAW) { j=p->size+p->next->size; if (j>=254) { p=p->next; continue; } buffer=(unsigned char *) safe_malloc (j); for (i=0; i<p->size; i++) buffer[i]=p->buffer[i]; for (i=0; i<p->next->size; i++) buffer[i+p->size]=p->next->buffer[i]; p->size=j; p->buffer=buffer; q=p->next->next; free_block (p->next); p->next=q; continue; } p=p->next; } return base; } compressed *flush_pool (block *base) { block *p; int i=0; compressed *comp; comp=(compressed *) safe_malloc (sizeof (compressed)); comp->size=0; for (p=base; p!=NULL; p=p->next) if (p->type==2) comp->size+=2; else comp->size+=p->size+1; comp->buffer=(unsigned char *) safe_malloc (++comp->size); i=0; for (p=base; p!=NULL; p=p->next) { if (p->type==MULTI) { comp->buffer[i++]=(p->size/2)+0x80; comp->buffer[i++]=p->value; } else { comp->buffer[i++]=(p->size/2); memcpy (comp->buffer+i,p->buffer,p->size); i+=p->size; } } comp->buffer[i++]=0; return comp; } compressed *compress_line (unsigned char *buffer, int size) { block *base; compressed *comp; base=compress (buffer,size); comp=flush_pool (base); free_frame (base); return comp; } void free_compressed (compressed *comp) { free (comp->buffer); free (comp); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* strnstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gabriel <gabriel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/28 12:08:05 by jtoty #+# #+# */ /* Updated: 2021/02/10 12:17:46 by gabriel ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include "../libft.h" #include <stdio.h> #include <string.h> char *strnstr(const char *big, const char *little, size_t len); static void ft_print_result(char const *s) { int len; len = 0; while (s[len]) len++; write(1, s, len); } static void check_strnstr(char *big, char *little, int len) { printf("big = '%s', size = %ld\n", big, strlen(big)); printf("little = '%s', size = %ld\n", little, strlen(little)); printf("len = %d\n", len); char *str = ft_strnstr(big, little, len); if (!str) ft_print_result("NULL"); else ft_print_result(str); printf("\n"); } int main(int argc, const char *argv[]) { int arg; alarm(5); // printf("saida = %s\n", strnstr("lorem ipsum dolor sit amet", "dolor", 16)); char *s1 = "AAAAAAAAAAAAA"; size_t max = strlen(s1); char *i1 = strnstr(s1, s1, max); char *i2 = ft_strnstr(s1, s1, max); if(0) { if (i1 == i2) { printf("TEST_SUCCESS\n"); return (1); } printf("TEST_FAILED\n"); return (0); } if (argc == 1) return (0); else if ((arg = atoi(argv[1])) == 1) check_strnstr("lorem ipsum dolor sit amet", "lorem", 15); else if (arg == 2) check_strnstr("lorem ipsum dolor sit amet", "ipsum", 15); else if (arg == 3) check_strnstr("lorem ipsum dolor sit lorem ipsum dolor", "ipsum", 35); else if (arg == 4) check_strnstr("lorem ipsum dolor sit amet", "", 10); else if (arg == 5) check_strnstr("lorem ipsum dolor sit amet", "ipsumm", 30); else if (arg == 6) check_strnstr("lorem ipsum dolor sit amet", "dol", 30); else if (arg == 7) check_strnstr("lorem ipsum dolor sit amet", "consectetur", 30); else if (arg == 8) check_strnstr("lorem ipsum dolor sit amet", "sit", 10); else if (arg == 9) check_strnstr("lorem ipsum dolor sit amet", "dolor", 15); else if (arg == 10) check_strnstr("lorem ipsum dolor sit amet", "dolor", 0); return (0); }
C
#include <stdio.h> #include <math.h> int main (void) { int a; scanf("%x", &a); // 1st task printf("%d\n", a); // 2nd task printf("%x %x\n", a, a >> 2); //3rd task printf("%x %x\n", a, ~a); //4th task int b; scanf("%x", &b); printf("%x\n", a | b); //5th task }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> void main() { // Code... // int sesi = 0; // while(sesi <= 1000) { // printf("%d\n", sesi); // sesi++; // } // int bilangan; // printf("Masukan bilangan: "); // scanf("%d", &bilangan); // if(bilangan % 2 == 0) { // printf("%d adalah bilangan genap!", bilangan); // } else { // printf("%d adalah bilangan ganjil", bilangan); // } // char nama[10]; // char salam[100] = ""; // puts("Nama kamu siapa?: "); // gets(nama); // strcat(salam, "Hallo "); // strcat(salam, nama); // strcat(salam, " , selamat datang"); // puts(salam); int n; int baris = 0; int bilangan = 2; // Bilangan pertama printf("n berapa: "); scanf("%d", &n); while (baris < n) { if(bilangan % 2 == 0) { if(bilangan % 4 != 0) { printf("%d \n", bilangan); baris++; } } bilangan++; } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include "constants.h" #define debug_hex(_s, _len, _c) {int _i; fprintf(stderr, _c); for(_i = 0; _i < _len; _i++){fprintf(stderr, "%x|", _s[_i]);} fprintf(stderr, "\n");} /* SRARQ functions */ int xor(char data[], unsigned char len){ int i, x = 0; for(i = 0; i < len; i++){ x ^= (int) data[i]; } return x; } void send_packet(int socket_desc, char buf[], size_t len, const struct sockaddr *dest_addr, socklen_t addrlen){ if(DROP_PACKETS && !(rand() % 5)){ // drop 1/5 packets if(DEBUG) fprintf(stderr, "> Dropped packet. I'm so sorry\n"); return; } if(DEBUG>1) debug_hex(buf, len, ">> ") sendto(socket_desc, buf, len, 0, dest_addr, addrlen); } // Reads message from file descriptor and writes packet to destination // Format: |sequence_high|sequence_low|length|data (length bytes)|checksum| // Returns length of packet // TODO: read from buffer instead of fd? int encode_msg(int sequence, int fd, char dest[]){ int len; dest[0] = sequence >> 8; dest[1] = sequence; len = read(fd, &dest[3], MSG_LEN); dest[2] = len; dest[len+3] = xor(&dest[3], len); dest[len+4] = 0; return len+META_LEN; } // Returns -1 for invalid or zero size packet, sequence number otherwise int decode_msg(char msg[], int *len){ if(len != NULL){ *len = (unsigned char) msg[2]; } if(xor(&msg[3], (unsigned char) msg[2]) != msg[(unsigned char) msg[2]+3]){ fprintf(stderr, "Invalid packet received!\n"); return -1; } return (unsigned char) msg[2] == 0 ? -1 : 0 | (unsigned char) msg[0] << 8 | (unsigned char) msg[1]; } // Prints message to stdout void print_msg(char msg[]){ printf("%.*s", (unsigned char) msg[2], &msg[3]); }
C
#include <fcntl.h> #include "my_tar.h" int is_directory(char* name) { struct stat current_file; if (stat(name, &current_file) == 0) { if (S_ISDIR(current_file.st_mode)) { return 1; } } return 0; } int open_archive_file(tar_options* options) { int fd_archive; int flags = O_RDONLY; const mode_t DEFAULT_CREAT_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; if (options->create) flags = O_CREAT | O_WRONLY | O_TRUNC; else if (options->extract || options->list) flags = O_RDONLY; else if (options->add || options->add_if_u) flags = O_RDONLY | O_WRONLY; fd_archive = open(options->archive_name, flags, DEFAULT_CREAT_MODE); return fd_archive; }
C
#include "mpi.h" #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int n , pid, p ; // sendA , sendB are data in p0 // finalC is gathered by p0 // recA and recC are local data in all other processors int *sendA, *sendB, *finalC , *recA , *recC ; int tagn = 0 ; int tagA = 1 ; int tagB = 2 ; int tagC = 3 ; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &p); // max number of processors MPI_Comm_rank(MPI_COMM_WORLD, &pid); // our rank MPI_Status status; MPI_Comm comm1 , comm2; // p0 is reading the file if (pid ==0 ) { FILE *fp = fopen("data.txt","r"); fscanf ( fp , "%d", & n ); printf ("rows is %d \n", n ); sendA = (int*) malloc( n *n * sizeof( int* )); sendB = (int*) malloc( n *n *sizeof( int* )); finalC = (int*) malloc( n *n* sizeof( int* )); for ( int r = 0 ; r < n ; r++) for ( int c = 0 ; c < n ; c++ ) { fscanf ( fp , "%d", & sendA[r*n + c] ); //printf ("A [%d] %d \n", r*n + c , sendA[r*n + c] ); } for ( int r = 0 ; r < n ; r++) for ( int c = 0 ; c < n ; c++ ) fscanf ( fp , "%d", & sendB[r*n + c] ); fclose (fp); printf (" process 0 send create buffer \n " ) ; } // this part is added to start timing , all processors are doing this part // I decide that all process calculate the time // I was curious to see what happened MPI_Barrier(MPI_COMM_WORLD); /* barrier is needed if no necessary synchronization for the timing is ensured yet */ double start = MPI_Wtime(); /* only 1 process needs to do this */ // first broad cast the n to all others MPI_Bcast ( &n, 1 , MPI_INT , 0 , MPI_COMM_WORLD ) ; printf (" n / p is %d \n " , n/p ) ; // allocating lical data recA = (int*) malloc( n/p * n * sizeof( int* )); if (sendB == NULL ) { printf ("NULL\n"); sendB = (int*) malloc( n * n* sizeof( int* ));} recC = (int*) malloc( n /p *n * sizeof( int* )); printf (" process %d create rec buffer \n " , pid ) ; // now p0 scatter matrix sendA to all MPI_Scatter( sendA , n * n/p , MPI_INT , recA , n * n/p , MPI_INT , 0, MPI_COMM_WORLD ) ; for (int i=0; i < (n/p) ; i++) printf (" process %d A [%d] = % d \n " , pid , i , recA[i] ) ; //now p0 broadcast sendB to all others MPI_Bcast ( sendB, n*n , MPI_INT , 0 , MPI_COMM_WORLD ) ; for (int i=0; i < (n*n) ; i++) printf (" process %d sendB [%d] = % d \n " , pid , i , sendB[i] ) ; // all do this part to calculate recC as multiplicated matrix for ( int i=0 ; i< (n/p) ; i++ ) for ( int j = 0 ; j<n ; j++ ) { recC[i*n+j] = 0 ; for ( int k = 0 ; k<n ; k++ ) recC[i*n+j] += recA[i*n+k]*sendB[k*n+j]; printf (" process %d recC [%d] = % d \n" , pid , i*n+j , recC[i*n+j] ) ; } // nopw p0 will gather all result data from all prcesses MPI_Gather( recC , n*n/p , MPI_INT , finalC , n*n/p , MPI_INT , 0, MPI_COMM_WORLD ) ; // here is the last point of calculating the time MPI_Barrier(MPI_COMM_WORLD); /* barrier is needed if no necessary synchronization for the timing is ensured yet */ double end = MPI_Wtime(); /* only 1 process needs to do this */ // we write the time double time = end - start ; printf (" ********** process %d : time = % d \n" , pid , time ) ; // here p0 is writing the output into the file if (pid == 0) { FILE *out = fopen("matrix_result.txt","w"); if (out == NULL) { printf("Error opening file!\n"); exit(1); } for (int i=0; i < n ; i++) { for (int j=0; j < n ; j++) fprintf ( out ," %d " , finalC[i*n+j] ) ; fprintf ( out , "\n") ; } fclose ( out) ; } // thank u professor song jiang for reading our code precisely // I really appreciate that MPI_Finalize(); return 0; }
C
/* * vector.c * * Copyright (C) 2007-2012, Computing Systems Laboratory (CSLab), NTUA * Copyright (C) 2007-2011, Kornilios Kourtis * Copyright (C) 2011-2012, Vasileios Karakasis * Copyright (C) 2011-2012, Theodoros Gkountouvas * All rights reserved. * * This file is distributed under the BSD License. See LICENSE.txt for details. */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <math.h> #include <numa.h> #include <numaif.h> #include <sys/mman.h> #include "vector.h" enum { ALLOC_STD = 1, ALLOC_NUMA, ALLOC_MMAP, ALLOC_OTHER, }; /* * vector: align allocation to 12(=3x4) elements. * This (quick-)fixes a bug in bcrs spmv code, when the row block size * does not align with the y vector. As a results writes are * perfomed beyond the end of the y vector */ #define ALIGN_BOUND (12) #define ALIGN(ul) (ul + (ul % ALIGN_BOUND)) /* * Create a vector from an input buffer. The elements are not copied. */ VECTOR_TYPE *VECTOR_NAME(_create_from_buff)(ELEM_TYPE *buff, unsigned long size) { VECTOR_TYPE *v = malloc(sizeof(VECTOR_TYPE)); if (!v) { perror("malloc"); exit(1); } v->size = size; v->alloc_type = ALLOC_OTHER; v->elements = buff; return v; } VECTOR_TYPE *VECTOR_NAME(_create)(unsigned long size) { VECTOR_TYPE *v = malloc(sizeof(VECTOR_TYPE)); if (!v) { perror("malloc"); exit(1); } v->size = size; v->alloc_type = ALLOC_STD; v->elements = malloc(sizeof(ELEM_TYPE)*(size + 12)); if (!v->elements) { perror("malloc"); exit(1); } return v; } VECTOR_TYPE *VECTOR_NAME(_create_onnode)(unsigned long size, int node) { VECTOR_TYPE *v = alloc_onnode(sizeof(VECTOR_TYPE), node); v->size = size; v->alloc_type = ALLOC_MMAP; v->elements = alloc_onnode(sizeof(ELEM_TYPE)*size, node); return v; } VECTOR_TYPE *VECTOR_NAME(_create_interleaved)(unsigned long size, size_t *parts, int nr_parts, const int *nodes) { VECTOR_TYPE *v = alloc_onnode(sizeof(VECTOR_TYPE), nodes[0]); v->size = size; v->alloc_type = ALLOC_MMAP; v->elements = (ELEM_TYPE *) alloc_interleaved(size*sizeof(*v->elements), parts, nr_parts, nodes); return v; } void VECTOR_NAME(_destroy)(VECTOR_TYPE *v) { if (v->alloc_type == ALLOC_STD) { free(v->elements); free(v); } else if (v->alloc_type == ALLOC_NUMA) { numa_free(v->elements, sizeof(ELEM_TYPE)*v->size); numa_free(v, sizeof(VECTOR_TYPE)); } else if (v->alloc_type == ALLOC_MMAP) { munmap(v->elements, sizeof(ELEM_TYPE)*v->size); munmap(v, sizeof(VECTOR_TYPE)); } else if (v->alloc_type == ALLOC_OTHER) { /* Just free our stuff; elements are supplied from user */ free(v); } else { assert(0 && "unknown allocation type"); } } void VECTOR_NAME(_init)(VECTOR_TYPE *v, ELEM_TYPE val) { unsigned long i; for (i = 0 ; i < v->size; i++) v->elements[i] = val; } void VECTOR_NAME(_init_part)(VECTOR_TYPE *v, ELEM_TYPE val, unsigned long start, unsigned long end) { unsigned long i; for (i = start; i < end; i++) v->elements[i] = val; } void VECTOR_NAME(_init_from_map)(VECTOR_TYPE **v, ELEM_TYPE val, map_t *map) { unsigned int i; unsigned int *cpus = map->cpus; unsigned int *pos = map->elems_pos; for (i = 0; i < map->length; i++) v[cpus[i]]->elements[pos[i]] = 0; } void VECTOR_NAME(_init_rand_range)(VECTOR_TYPE *v, ELEM_TYPE max, ELEM_TYPE min) { unsigned long i; ELEM_TYPE val; for (i = 0; i < v->size; i++) { val = ((ELEM_TYPE) (rand()+i) / ((ELEM_TYPE) RAND_MAX + 1)); v->elements[i] = min + val*(max-min); } } void VECTOR_NAME(_add)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3) { unsigned long i; if (v1->size != v2->size || v1->size != v3->size) { fprintf(stderr, "v1->size=%lu v2->size=%lu v3->size=%lu differ\n", v1->size, v2->size, v3->size); exit(1); } for (i = 0; i < v1->size; i++) v3->elements[i] = v1->elements[i] + v2->elements[i]; } void VECTOR_NAME(_add_part)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3, unsigned long start, unsigned long end) { unsigned long i; if (v1->size != v2->size || v1->size != v3->size) { fprintf(stderr, "v1->size=%lu v2->size=%lu v3->size=%lu differ\n", v1->size, v2->size, v3->size); exit(1); } if (start > v1->size || end > v1->size || start > end) { fprintf(stderr, "start=%lu end=%lu v->size=%lu not compatible\n", start, end, v1->size); exit(1); } for (i = start; i < end; i++) v3->elements[i] = v1->elements[i] + v2->elements[i]; } void VECTOR_NAME(_add_from_map)(VECTOR_TYPE *v1, VECTOR_TYPE **v2, VECTOR_TYPE *v3, map_t *map) { unsigned int i; unsigned int *cpus = map->cpus; unsigned int *pos = map->elems_pos; for (i = 0; i < map->length; i++) v3->elements[pos[i]] = v1->elements[pos[i]] + v2[cpus[i]]->elements[pos[i]]; } void VECTOR_NAME(_sub)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3) { unsigned long i; assert(v1->size == v2->size && v1->size == v3->size && "vectors for sub have different size"); for (i = 0; i < v1->size; i++) v3->elements[i] = v1->elements[i] - v2->elements[i]; } void VECTOR_NAME(_sub_part)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3, unsigned long start, unsigned long end) { unsigned long i; assert(v1->size == v2->size && v1->size == v3->size && "vectors for sub have different size"); for (i = start; i < end; i++) v3->elements[i] = v1->elements[i] - v2->elements[i]; } ELEM_TYPE VECTOR_NAME(_mul)(VECTOR_TYPE *v1, VECTOR_TYPE *v2) { unsigned long i; ELEM_TYPE ret; assert(v1->size == v2->size && "vectors for mul have different size"); ret = 0; for (i = 0; i < v1->size; i++) ret += v1->elements[i] * v2->elements[i]; return ret; } ELEM_TYPE VECTOR_NAME(_mul_part)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, unsigned long start, unsigned long end) { unsigned long i; ELEM_TYPE ret; assert(v1->size == v2->size && "vectors for mul have different size"); ret = 0; for (i = start; i < end; i++) ret += v1->elements[i] * v2->elements[i]; return ret; } void VECTOR_NAME(_scale)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, double num) { unsigned long i; assert(v1->size == v2->size && "vectors for scale have different size"); for (i = 0; i < v1->size; i++) v2->elements[i] = num * v1->elements[i]; } void VECTOR_NAME(_scale_add)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3, double num) { unsigned long i; assert(v1->size == v2->size && v1->size == v3->size && "vectors for scale add have different size"); for (i = 0; i < v1->size; i++) v3->elements[i] = v1->elements[i] + num * v2->elements[i]; } void VECTOR_NAME(_scale_add_part)(VECTOR_TYPE *v1, VECTOR_TYPE *v2, VECTOR_TYPE *v3, double num, unsigned long start, unsigned long end) { unsigned long i; assert(v1->size == v2->size && v1->size == v3->size && "vectors for scale add have different size"); for (i = start; i < end; i++) v3->elements[i] = v1->elements[i] + num * v2->elements[i]; } void VECTOR_NAME(_copy)(VECTOR_TYPE *v1, VECTOR_TYPE *v2) { unsigned long i; assert(v1->size == v2->size && "vectors for copy have different size"); for (i = 0; i < v1->size; i++) v2->elements[i] = v1->elements[i]; } static inline int elems_neq(ELEM_TYPE a, ELEM_TYPE b) { if (fabs((double) (a - b) / (double) a) > 1.e-7) return 1; return 0; } int VECTOR_NAME(_compare)(VECTOR_TYPE *v1, VECTOR_TYPE *v2) { unsigned long i; if (v1->size != v2->size) { fprintf(stderr, "v1->size=%lu v2->size=%lu differ\n", v1->size, v2->size); return -2; } for (i=0; i<v1->size; i++) { if (elems_neq(v1->elements[i], v2->elements[i])) { fprintf(stderr, "element %ld differs: %10.20lf != %10.20lf\n", i, (double) v1->elements[i], (double) v2->elements[i]); return -1; } } return 0; } void VECTOR_NAME(_print)(VECTOR_TYPE *v) { unsigned long i; printf("[ "); for (i = 0; i < v->size; i++) printf("%lf ", (double) v->elements[i]); printf("]\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct record{ double cgpa; char *name; }; typedef struct record *Record; void *readfile(FILE *fp,void *arr,int *sz); int totalheap=0; int maxheap=0; void *myalloc(int n){ void *temp = malloc(n+sizeof(int)); int *first = (int*)temp; *first = n; totalheap+=n; if(maxheap<totalheap) maxheap = totalheap; /* printf("memory heap:-%llu\n",totalheap);*/ /* printf("total hea= %llu\n",maxheap);*/ return temp; } void myfree(void *temp){ int *sz = (int*)temp; --sz; totalheap-=(*sz); printf("size= %d\n",*sz); //free(temp); /* printf("memory heap:-%llu\n",totalheap);*/ /* printf("total hea= %llu\n",maxheap);*/ } void *retnext(void *ptr){ int *temp = (int*)ptr; temp++; return temp; } int main(){ printf("size of struct record;- %llu\n",sizeof(struct record)); printf("size of Record:- %llu\n",sizeof(Record)); // printf("size of Record:- %llu\n",sizeof(Record)); //printf("size of Record:- %llu\n",sizeof(Record)); Record *arr; void *szptr = myalloc(sizeof(int)); int *sz = (int*)retnext(szptr); *sz = 1; void *arrptr = (void*)myalloc(sizeof(Record)*(*sz)); arr = (Record*)retnext(arrptr); FILE *fp; fp = fopen("10.txt","r"); if(!fp){ printf("cant open file\n"); exit(1); } arrptr = readfile(fp,arrptr,sz); arr = (Record*)retnext(arrptr); int i; /* for(i=0;i<*sz;i++){*/ /* printf("name: %s cgpa = %lf\n",arr[i]->name,arr[i]->cgpa);*/ /* }*/ for(i=0;i<*sz;i++){ myfree(arr[i]->name); } myfree(arrptr); /* char name[500];*/ /* scanf("%[a-z ]\n",name);*/ /* printf("%s\n",name);*/ } void *readfile(FILE *fp,void *arrptr,int *sz){ char name[50]; double cgpa; int i=0; Record *arr = (Record*)retnext(arrptr); while(fscanf(fp,"%49[^,],%lf\n",name,&cgpa)!=EOF){ //printf("line is: %s and cgpa = %lf\n",name,cgpa); if(i>=*sz){ arrptr = realloc(arrptr,(2*(*sz)*sizeof(Record)+sizeof(int))); int *temp = (int*)arrptr; *temp = 2*(*sz); arr = (Record*)retnext(arrptr); (*sz)*=2; totalheap+=*sz; } arr[i] = (Record)myalloc(sizeof(struct record)); arr[i]->cgpa = cgpa; int len = strlen(name); arr[i]->name = (char*)myalloc((len+1)*sizeof(char)); strcpy(arr[i]->name,name); i++; } arrptr = realloc(arrptr,(sizeof(Record)*i+sizeof(int))); int *temp = (int*)arrptr; *temp = i; *sz = i; return arrptr; }
C
#include <winsock2.h> #include <stdio.h> #include <process.h> // for _beginthread() #define BUFF 1024 int Port=6666,ret; char sendbuff[BUFF]; char recvbuff[BUFF]; struct infor { SOCKET client; char name[1024]; }; struct infor info[100]; SOCKET c; struct sockaddr_in serveadd; int i=0; void thread_send() { int j; while(1) while(i) { { scanf("%s",sendbuff); if(strcmp(sendbuff,"quit") == 0) //˳ return 0; //printf("\nû2:"); for(j=0;j<i;j++) { send((info+j)->client,"",BUFF,0); send((info+j)->client,":",BUFF,0); if(send((info+j)->client,sendbuff,BUFF,0) == SOCKET_ERROR) { printf("Ϣʧ!\n"); break; } } } } } /*void thread_listen(SOCKET *arry) { serveadd.sin_port=htons(Port); serveadd.sin_family=AF_INET; serveadd.sin_addr.s_addr = inet_addr("0.0.0.0"); bind(c,(struct sockaddr*)(&serveadd),sizeof(serveadd)); listen(c,5); printf("ȴ..."); *(arry+i)=accept(c,(struct sockaddr*)(&serveadd),&serveadd); i++; }*/ void thread_recv(int k) { int j,flag; flag=k; while(1) { ret=recv((info+flag)->client,recvbuff,BUFF,0); //printf("client1 %d",newc.client); if(ret>0) { printf("%s:%s\n",(info+flag)->name,recvbuff); for(j=0;j<i;j++) { if(j!=k) { send((info+j)->client,(info+flag)->name,BUFF,0); send((info+j)->client,":",BUFF,0); if(send((info+j)->client,recvbuff,BUFF,0) == SOCKET_ERROR) { printf("Ϣʧ!\n"); break; } } } } else if(ret < 0) { printf("մ%d\n",SOCKET_ERROR); closesocket((info+flag)->client); WSACleanup(); return -1; } } } void main() { int j=0; SOCKET newc; WSADATA wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); c=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); _beginthreadex(NULL,0,&thread_send,0,NULL,0); while(1) { serveadd.sin_port=htons(Port); serveadd.sin_family=AF_INET; serveadd.sin_addr.s_addr = inet_addr("0.0.0.0");//֪ںȥѡIPַ,Ҳ԰һضIPַ󶨵׽ϣIPַӿ֮һ bind(c,(struct sockaddr*)(&serveadd),sizeof(serveadd)); listen(c,5); //printf("ȴ..."); newc=accept(c,(struct sockaddr*)(&serveadd),&serveadd); if(newc==-1) { return -1; } printf("ӳɹ\n"); ret=recv(newc,recvbuff,BUFF, 0); if(ret > 0) printf("%s:\n",recvbuff); (info+i)->client=newc; strcpy((info+i)->name,recvbuff); //printf("client %d",newc); _beginthreadex(NULL,0,&thread_recv,i,NULL,0); i++; } /* while(1) { scanf("%s",sendbuff); if(strcmp(sendbuff,"quit") == 0) //˳ break; //printf("\nû2:"); for(j=0;j<i;j++) if(send(newc,sendbuff,BUFF,0) == SOCKET_ERROR) { printf("Ϣʧ!\n"); break; } }*/ shutdown(newc, SD_BOTH); closesocket(c); closesocket(newc); WSACleanup(); } //̨Բ
C
#include <stdio.h> int somaincremental(int n1, int n2){ if(n2 == 0){ return n1; } n1++; return somaincremental(n1,n2-1); } int main(int argc, char const *argv[]) { int n1, n2; printf("Digite n1: \n"); scanf("%i",&n1); printf("Digite n2: \n"); scanf("%i",&n2); printf("%i\n",somaincremental(n1, n2)); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <time.h> #include <fcntl.h> #define PORT 1234 #define MAXDATASIZE 100 void process(FILE *fp, int sockfd); char* getMessage(char* sendline,int len, FILE* fp); int main(int argc, char *argv[]) { int sockfd; struct hostent *he; struct sockaddr_in server; if (argc !=2) { printf("Usage: %s <IP Address>\n",argv[0]); exit(1); } if ((he=gethostbyname(argv[1]))==NULL) { printf("gethostbyname() error\n"); exit(1); } if ((sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1) { perror("socket"); exit(1); } bzero(&server,sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr = *((struct in_addr *)he->h_addr); if(connect(sockfd, (struct sockaddr *)&server,sizeof(server))==-1) { perror("connect"); exit(1); } process(stdin,sockfd); close(sockfd); } void writefile(int fd,char *str) { time_t t1; struct tm *t2; char wtext[100]; t1=time(NULL); t2=localtime(&t1); sprintf(wtext,"%d-%d-%d-%d:%d:%d",t2->tm_year+1900,t2->tm_mon+1,t2->tm_mday,t2->tm_hour,t2->tm_min,t2->tm_sec); sprintf(wtext,"%s %s\n",wtext,str); write(fd,wtext,strlen(wtext)); } void process(FILE *fp, int sockfd) { char sendline[MAXDATASIZE], recvline[MAXDATASIZE]; int num; int fd; time_t t1; struct tm *t2; char cname[30]; char tmp[100]; printf("Connected to server. \n"); printf("Input client's name : "); if ( fgets(cname, 30, fp) == NULL) { printf("\nExit.\n"); return; } send(sockfd, cname, strlen(cname),0); cname[strlen(cname)-1]=0; fd=open(cname,O_WRONLY|O_CREAT|O_APPEND,0644); if(fd==-1) { perror("open"); } writefile(fd,"connection success"); while (getMessage(sendline, MAXDATASIZE, fp) != NULL) { send(sockfd, sendline, strlen(sendline),0); sendline[strlen(sendline)-1]=0; sprintf(tmp,"%s : %s",cname,sendline); writefile(fd,tmp); if ((num = recv(sockfd, recvline, MAXDATASIZE,0)) == 0) { printf("Server terminated.\n"); return; } recvline[num]='\0'; printf("Server Message: %s\n",recvline); sprintf(tmp,"server : %s",recvline); writefile(fd,tmp); if(strcmp(sendline,"bye")==0) break; } printf("\nExit.\n"); writefile(fd,"close connection"); } char* getMessage(char* sendline,int len, FILE* fp) { printf("Input string to server:"); return(fgets(sendline, MAXDATASIZE, fp)); }
C
#include <wiringPi.h> #include <wiringPiI2C.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> unsigned int readI2CRegister16bit(int addr, int reg) { wiringPiI2CWrite(addr,reg); sleep(1); unsigned int t = wiringPiI2CReadReg8(addr,reg); return t; } void main(void) { int dID = 0x20; int fd; if((fd=wiringPiI2CSetup(dID))<0){ printf("error opening i2c channel\n\r"); } wiringPiI2CWrite(fd,6); unsigned int cap = readI2CRegister16bit(fd, 0); //read capacitance register printf ("Capacitance = "); printf("%u",cap); printf(", "); unsigned int temp = readI2CRegister16bit(fd, 5); //temperature register printf ("Temperature = "); printf("%u",temp); printf(", "); wiringPiI2CWrite(fd,3); //request light measurement unsigned int light = readI2CRegister16bit(fd, 4); //read light register printf ("Temperature = "); printf("%u",light); }
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* buildBST(struct ListNode **head, int len) { if(len <= 0) return NULL; struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode)); root->left = buildBST(head, len/2); root->val = (*head)->val; *head = (*head)->next; root->right = buildBST(head, len - len/2 - 1); return root; } struct TreeNode* sortedListToBST(struct ListNode* head) { if(head == NULL) return NULL; struct ListNode *cur = head; int len = 0; while(cur != NULL) { len++; cur = cur->next; } cur = head; struct TreeNode *root = buildBST(&cur, len); return root; }
C
#include<stdio.h> #include<string.h> #include<limits.h> #include "bitshow.h" void show_bytes(byte_pointer,size_t); void show_short(short x); void show_int(int x); void show_long(long x); void show_double(double x); void show_float(float x); void show_pointer(void *x); void show_unsigned(unsigned x); int uadd_ok(unsigned x,unsigned y); int tadd_ok(int x, int y); int tsub_ok(int x,int y); int is_little_endian(); void show_bytes(byte_pointer start,size_t len) { size_t i; for (i=0;i<len;i++) printf("%.2x",start[i]); printf("\n"); } void show_short(short x){ show_bytes((byte_pointer) &x,sizeof(short)); } void show_int(int x) { show_bytes((byte_pointer) &x,sizeof(int)); } void show_long(long x){ show_bytes((byte_pointer) &x,sizeof(long)); } void show_float(float x){ show_bytes((byte_pointer) &x,sizeof(double)); } void show_double(double x){ show_bytes((byte_pointer) &x,sizeof(double)); } void show_pointer(void *x){ show_bytes((byte_pointer) &x,sizeof(void *)); } void show_unsigned(unsigned x){ show_bytes((byte_pointer) &x,sizeof(unsigned)); } int uadd_ok(unsigned x,unsigned y){ unsigned sum = x+y; return sum>=x; } int tadd_ok(int x, int y){ int sum=x+y; int pos_over = x>0&&y>0&&sum<=0; int neg_over = x<0&&y<0&&sum>=0; return !pos_over && !neg_over; } int tsub_ok(int x,int y){ if(x<0&&y==INT_MIN){ return 1; } return tadd_ok(x,-y); } int is_little_endian(){ unsigned a = 1; unsigned char *b = (unsigned char *) &a; return b[0]; }
C
/* ******************************************************** * α׷ : Main_Scene.c * ۼ : ڼ, 1 ù(ڽ, ڰ, ڼ, ں) * ۼ : 2017.05.31 * α׷ : ޴ α׷Դϴ. ******************************************************** */ #include "Main_Scene.h" void _RenderMainTitle(); // ŸƲ κ void _setTitleImage(); // ȭ鿡 ŸƲ ̹ մϴ. void _RenderMainImage(); // ŸƲ ̹ մϴ. void _RenderMainMenu(); // ޴ κ մϴ. void _RenderArrow(); // ȭǥ ׷ݴϴ. void _RemoveArrow(); // ȭǥ ݴϴ. void _RenderMadeBy(); void _inputKey(); // Ű Է մϴ. void _ArrowEvent(); char titleImage[40][142]; // ŸƲ ̹ int bMainSceneInit = 0; // ξ ε int bMainRender = 0; // Ӿ ʱȭ int order = 0; // ޴ ȣ int arrowY = 35; // ȭǥ ǥ // ʱȭݴϴ. () void InitMainScene() { if (bMainSceneInit == 0) { _setTitleImage(); bMainSceneInit = 1; } } // ѹ ׷ָ Ǵ ̹ ׷ݴϴ. void RenderMainScene() { if (bMainRender == 0) { order = -1; StartBGMusic(); _RenderMainImage(); _RenderArrow(); _RenderMainMenu(); _RenderMainTitle(); _RenderMadeBy(); bMainRender = 1; } } // ޴ Ʈ ó void UpdateMainScene() { _inputKey(); if (order == -1) { order = 0; } } void _inputKey() { char cChar, DirKey; if (_kbhit()) { cChar = _getch(); switch (cChar) { case 13: // Ű _ArrowEvent(); case -32: DirKey = _getch(); switch (DirKey) { case 72: if (order > 0) { _RemoveArrow(); order -= 1; _RenderArrow(); _RenderMainMenu(); } break; case 80: if (order < 3) { _RemoveArrow(); order += 1; _RenderArrow(); _RenderMainMenu(); } break; } break; } } } // Made by ȭ鿡 ׷ݴϴ. void _RenderMadeBy() { gotoxy(138, 18); printf("Made By All Park!"); } // ŸƲ Ǵ ̹ ɴϴ. void _setTitleImage() { FILE* fp = fopen("title_image.txt", "rb"); int i; if (fp == NULL) { printf("ddddddd"); return; } fread(titleImage, sizeof(char), 40 * 142, fp); for (i = 0; i < 40; i++) { strcpy(&titleImage[i][141], "\0"); } fclose(fp); } // ŸƲ ̹ ȭ鿡 ׷ݴϴ. void _RenderMainImage() { int i, j; gotoxy(58, 18); for (i = 0; i < 40; i++) { for (j = 0; j < 142; j++) { printf("%c", titleImage[i][j]); } printf("\n"); } } // ŸƲ ȭ鿡 ׷ݴϴ. void _RenderMainTitle() { gotoxy(55, 1); printf("\n"); gotoxy(55, 2); printf("\n"); gotoxy(55, 3); printf(" \n"); gotoxy(55, 4); printf(" \n"); gotoxy(55, 5); printf(" \n"); gotoxy(55, 6); printf(" \n"); gotoxy(55, 7); printf(" \n"); gotoxy(55, 8); printf(" \n"); gotoxy(55, 9); printf(" \n"); gotoxy(55, 10); printf(" \n"); gotoxy(55, 11); printf(" \n"); gotoxy(55, 12); printf(" \n"); gotoxy(55, 13); printf(" \n"); gotoxy(55, 14); printf("\n"); gotoxy(55, 15); printf("\n"); gotoxy(138, 45); printColoredText("[ ]", YELLOW); gotoxy(123, 47); printColoredText("Enter 糪 ̵մϴ.", YELLOW); gotoxy(121, 48); printColoredText(" ϴ ȣ Էϸ ˴ϴ.", YELLOW); } // ŸƲ ޴ մϴ. void _RenderMainMenu() { int target = (order == -1) ? 0 : order; gotoxy(114, 20); printf(""); gotoxy(114, 21); printf(" ᦢ"); gotoxy(114, 22); printf(" "); gotoxy(114, 23); printf(" "); gotoxy(114, 24); printf(" "); gotoxy(114, 25); printf(" "); gotoxy(114, 26); printf(" "); gotoxy(114, 27); printf(" "); gotoxy(114, 28); printf(" "); gotoxy(114, 29); printf(" "); gotoxy(114, 30); printf(""); gotoxy(140, 35); if (target == 0) printColoredText("ϱ", RED); else printf("ϱ"); gotoxy(140, 36); if (target == 1) printColoredText("̾ϱ", RED); else printf("̾ϱ"); gotoxy(140, 37); if (target == 2) printColoredText("", RED); else printf(""); gotoxy(140, 38); if (target == 3) printColoredText("", RED); else printf(""); } void _RenderArrow() { int target = (order == -1) ? 0 : order; gotoxy(138, arrowY + (target * 1)); printf(""); } void _RemoveArrow() { int target = (order == -1) ? 0 : order; gotoxy(138, arrowY + (order * 1)); printf(" "); } void _ArrowEvent() { switch (order) { case 0: bMainRender = 0; SetGameOrder("GameScene"); ChangeScene(GameScene); return; break; case 1: //̾ϱ bMainRender = 0; SetGameOrder("LoadGameScene"); ChangeScene(LoadGameScene); return; break; case 2: bMainRender = 0; ChangeScene(SettingScene); return; break; case 3: exit(1); break; default: break; } }
C
#include "fthread.h" #include "stdio.h" #include <stdlib.h> /* efficiency of await_n implementation */ #define CYCLES 100000 #define NUMBER 100 // less than the max number of threads void waiter (void *args) { ft_thread_await_n ((ft_event_t)args,CYCLES); fprintf (stdout, "end waiting\n"); exit (0); } int main (void) { int i; ft_scheduler_t sched = ft_scheduler_create (); for (i=0;i<NUMBER;i++) { ft_thread_create (sched,waiter,NULL,(void*)ft_event_create (sched)); } ft_scheduler_start (sched); fprintf (stdout, "start waiting\n"); ft_exit (); return 0; } /* result start waiting end waiting end result */
C
#include <cs50.h> #include <stdio.h> int shower_convert(int shower_time); int main(void) { printf("Enter length of shower in minutes "); int shower_length = get_int(); shower_convert(shower_length); printf("The equivalent amount in number of bottles is %i\n", shower_convert(shower_length)); } int shower_convert(int shower_length) { return shower_length * 1.5 * 128 / 16; }
C
/* Pointers and multi-dim arrays */ #include <stdio.h> int main() { int i, j; // Iteration int matrix[2][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} }; for (i = 0; i < 2; i++){ for (j = 0; j < 5; j++){ printf("matrix[%d][%d] address: %p Value: %d\n", i, j, &matrix[i][j], matrix[i][j] ); } } printf("address matrix : %p\n", matrix); // 100 printf("address matrix+1: %p\n", matrix + 1); // 120 printf("address matrix: %d\n", sizeof(matrix[0])); // 20 return 0; }
C
#include <stdio.h> #include "string.h" // 正确的 // #include <fun.c> 错误:<>只能包含系统库文件,当前自己写的文件只用用 “”包含 #include "fun.c" /*#include <>和#include “ ”的区别 #include <>:直接去系统文件中找对应的文件,只能用于包含系统文件。 #include “ ”: 先在当前目录中找对应的文件,如果没有再去系统文件中找。可用于包含当前目录文件和系统文件。 */ void function(int a, int b); int main(int argc, char const *argv[]) { //----------------------#include关键字---------------- char *s = (char *)"qwertyuiop"; int count = strlen(s); printf("count = %d\n",count); function(1000,332); return 0; }
C
#include<stdio.h> int fact(int n) { if(n == 0) return 1; return n * fact(n - 1); } int main() { printf("%d\n", fact(4)); return 0; }
C
#include "HD44780.h" void LCD_out_bits(uint8_t bits_to_write) { if(bits_to_write & 0x01) PORT(LCD_DATA_PORT) |= (1<<LCD_D4_PIN); else PORT(LCD_DATA_PORT) &= ~(1<<LCD_D4_PIN); if(bits_to_write & 0x02) PORT(LCD_DATA_PORT) |= (1<<LCD_D5_PIN); else PORT(LCD_DATA_PORT) &= ~(1<<LCD_D5_PIN); if(bits_to_write & 0x04) PORT(LCD_DATA_PORT) |= (1<<LCD_D6_PIN); else PORT(LCD_DATA_PORT) &= ~(1<<LCD_D6_PIN); if(bits_to_write & 0x08) PORT(LCD_DATA_PORT) |= (1<<LCD_D7_PIN); else PORT(LCD_DATA_PORT) &= ~(1<<LCD_D7_PIN); } uint8_t LCD_in_bits(void) { uint8_t tmp = 0; if(((PIN(LCD_DATA_PORT) >> LCD_D4_PIN) & 0x01) != 0) tmp |= (1 << 0); if(((PIN(LCD_DATA_PORT) >> LCD_D5_PIN) & 0x01) != 0) tmp |= (1 << 1); if(((PIN(LCD_DATA_PORT) >> LCD_D6_PIN) & 0x01) != 0) tmp |= (1 << 2); if(((PIN(LCD_DATA_PORT) >> LCD_D7_PIN) & 0x01) != 0) tmp |= (1 << 3); return tmp; } void LCD_write(uint8_t data_to_write) { DDR(LCD_DATA_PORT) |= ((1<<LCD_D4_PIN)|(1<<LCD_D5_PIN)|(1<<LCD_D6_PIN)|(1<<LCD_D7_PIN)); PORT(LCD_RW_PORT) &= ~(1<<LCD_RW_PIN); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(data_to_write >> 4); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(data_to_write); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); while(LCD_ReadStatus() & 0x80); } void LCD_just_write(uint8_t data_to_write) { DDR(LCD_DATA_PORT) |= ((1<<LCD_D4_PIN)|(1<<LCD_D5_PIN)|(1<<LCD_D6_PIN)|(1<<LCD_D7_PIN)); PORT(LCD_RW_PORT) &= ~(1<<LCD_RW_PIN); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(data_to_write >> 4); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(data_to_write); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); } void LCD_just_write_command(uint8_t commandToWrite) { PORT(LCD_RS_PORT) &= ~(1<<LCD_RS_PIN); LCD_just_write(commandToWrite); } void LCD_just_write_data(uint8_t data_to_write) { PORT(LCD_RS_PORT) |= (1<<LCD_RS_PIN); LCD_just_write(data_to_write); } uint8_t LCD_NotBusy(void) { if(LCD_ReadStatus() != 0x80) { return 1; } else { return 0; } } uint8_t LCD_read(void) { uint8_t tmp = 0; DDR(LCD_DATA_PORT) &= ~((1<<LCD_D4_PIN)|(1<<LCD_D5_PIN)|(1<<LCD_D6_PIN)|(1<<LCD_D7_PIN)); PORT(LCD_RW_PORT) |= (1<<LCD_RW_PIN); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); tmp |= (LCD_in_bits() << 4); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); tmp |= LCD_in_bits(); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); return tmp; } void LCD_write_command(uint8_t commandToWrite) { PORT(LCD_RS_PORT) &= ~(1<<LCD_RS_PIN); LCD_write(commandToWrite); } uint8_t LCD_ReadStatus(void) { PORT(LCD_RS_PORT) &= ~(1<<LCD_RS_PIN); return LCD_read(); } void LCD_write_data(uint8_t data_to_write) { PORT(LCD_RS_PORT) |= (1<<LCD_RS_PIN); LCD_write(data_to_write); } uint8_t LCD_read_data(void) { PORT(LCD_RS_PORT) |= (1<<LCD_RS_PIN); return LCD_read(); } void LCD_write_text(char * text) { while(*text != '\0' && *text != 0) { LCD_write_data(*text++); } } void LCD_goto(uint8_t x, uint8_t y) { uint8_t shift = 0; if(y >= 2) { shift = HD44780_SHIFT; } LCD_write_command(HD44780_DDRAM_SET | (shift + x + (0x40 * (y % 2)))); } void LCD_clear(void) { LCD_write_command(HD44780_CLEAR); _delay_ms(2); } void LCD_home(void) { LCD_write_command(HD44780_HOME); _delay_ms(2); } void LCD_init(void) { uint8_t i; DDR(LCD_DATA_PORT) |= ((1<<LCD_D4_PIN)|(1<<LCD_D5_PIN)|(1<<LCD_D6_PIN)|(1<<LCD_D7_PIN)); DDR(LCD_RS_PORT) |= (1<<LCD_RS_PIN); DDR(LCD_RW_PORT) |= (1<<LCD_RW_PIN); DDR(LCD_E_PORT) |= (1<<LCD_E_PIN); _delay_ms(15); PORT(LCD_RS_PORT) &= ~(1<<LCD_RS_PIN); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); PORT(LCD_RW_PORT) &= ~(1<<LCD_RW_PIN); for(i = 0; i < 3; i++) { PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(0x03); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(5); } PORT(LCD_E_PORT) |= (1<<LCD_E_PIN); LCD_out_bits(0x02); PORT(LCD_E_PORT) &= ~(1<<LCD_E_PIN); _delay_ms(1); LCD_write_command(HD44780_FUNCTION_SET | HD44780_FONT5x7 | HD44780_TWO_LINE | HD44780_4_BIT); LCD_write_command(HD44780_DISPLAY_ONOFF | HD44780_DISPLAY_OFF); LCD_write_command(HD44780_CLEAR); LCD_write_command(HD44780_ENTRY_MODE | HD44780_EM_SHIFT_CURSOR | HD44780_EM_INCREMENT); LCD_write_command(HD44780_DISPLAY_ONOFF | HD44780_DISPLAY_ON | HD44780_CURSOR_OFF | HD44780_CURSOR_NOBLINK); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utility.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bschroed <bschroed@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/23 00:22:58 by bschroed #+# #+# */ /* Updated: 2017/06/14 19:54:40 by rmatos ### ########.fr */ /* */ /* ************************************************************************** */ #include "kift.h" void handle_signal(int status) { RED; if (status == SIGSEGV) { INVERSE; fprintf(stderr, "Fork exited with SEGV\n"); } else if (status == SIGBUS) { BOLD; fprintf(stderr, "Fork exited with BUSE\n"); } else { fprintf(stderr, "Fork exited with signal code: %d\n", status); } RESET; } int init_server_save(void) { int i; FILE *fp; struct stat buf; i = 0; if (lstat("./server_history/", &buf) == -1) { printf("make server save dir\n"); mkdir("./server_history/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } if (lstat("./server_history/NUM", &buf) != -1) { fp = fopen("./server_history/NUM", "r"); fscanf(fp, "%d", &i); fclose(fp); } printf("audio count: %i\n", i); return (i); } struct s_con *init_server(int port_num) { struct s_con *conn; conn = calloc(1, sizeof(*conn)); conn->sock_fd = socket(AF_INET, SOCK_STREAM, 0); conn->servaddr.sin_family = AF_INET; conn->servaddr.sin_addr.s_addr = htons(INADDR_ANY); conn->servaddr.sin_port = htons(port_num); bind(conn->sock_fd, (struct sockaddr *)&conn->servaddr, sizeof(conn->servaddr)); printf("server initialized to port: %i\n", port_num); return (conn); } int increment_audio_count(int ac) { FILE *fp; ac++; fp = fopen("./server_history/NUM", "w"); fprintf(fp, "%d", ac); fclose(fp); printf("audio count: %i\n", ac); return (ac); } void send_history(int comm_fd) { int fd; char buff[4096]; int bytes_read; struct stat st; long size; printf("sending history..."); fd = open("./server_history/commands.transcription", O_RDONLY); bzero(&st, sizeof(st)); fstat(fd, &st); size = st.st_size; write(comm_fd, &size, sizeof(size)); bzero(buff, 4096); printf("size: %li\n", size); while ((bytes_read = read(fd, &buff, 4096))) { write(comm_fd, buff, bytes_read); printf("%s", buff); } close(fd); exit(1); }
C
/*---------------------------------------------------------------------------- File name : gnuplot_i.h Author : N. Devillard Created on : Fri Sept 26 1997 Description : C interface to gnuplot gnuplot is a freely available, command-driven graphical display tool for Unix. It compiles and works quite well on a number of Unix flavours as well as other operating systems. The following module enables sending display requests to gnuplot through simple C calls. ---------------------------------------------------------------------------*/ /* $Id: gnuplot_i.h,v 1.1 2005/10/20 23:52:24 hiram Exp $ $Author: hiram $ $Date: 2005/10/20 23:52:24 $ $Revision: 1.1 $ */ #ifndef _GNUPLOT_PIPES_H_ #define _GNUPLOT_PIPES_H_ /*--------------------------------------------------------------------------- Includes ---------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdarg.h> /* Maximal number of simultaneous temporary files */ #define GP_MAX_TMP_FILES 64 /* Maximal size of a temporary file name */ #define GP_TMP_NAME_SIZE 512 /*--------------------------------------------------------------------------- New Types ---------------------------------------------------------------------------*/ /* * This structure holds all necessary information to talk to a gnuplot * session. */ typedef struct _GNUPLOT_CTRL_ { /* command file handling */ FILE * gnucmd ; /* Plotting options */ int nplots ; /* Number of active plots at the moment */ char pstyle[32] ; /* Current plotting style */ /* temporary files opened */ char to_delete[GP_MAX_TMP_FILES][GP_TMP_NAME_SIZE] ; int ntmp ; } gnuplot_ctrl ; /*--------------------------------------------------------------------------- Function ANSI C prototypes ---------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------*/ /** @name check_X_display @memo Checks out if the DISPLAY environment variable is set. @param activate int flag @return int 1 if the variable is set, 0 otherwise. @doc This function checks out the DISPLAY environment variable to see if it exists. It does not check if the display is actually correctly configured. If you do not want to activate this check (e.g. on systems that do not support this kind of display mechanism), pass a 0 integer as the activate flag. Any other value will activate it. */ /*--------------------------------------------------------------------------*/ int check_X_display(int activate); /*-------------------------------------------------------------------------*/ /** @name gnuplot_get_program_path @memo Find out where a command lives in your PATH. @param pname Name of the program to look for. @return pointer to statically allocated character string. @doc This is the C equivalent to the 'which' command in Unix. It parses out your PATH environment variable to find out where a command lives. The returned character string is statically allocated within this function, i.e. there is no need to free it. Beware that the contents of this string will change from one call to the next, though (as all static variables in a function). The input character string must be the name of a command without prefixing path of any kind, i.e. only the command name. The returned string is the path in which a command matching the same name was found. Examples (assuming there is a prog named 'hello' in the cwd): \begin{itemize} \item gnuplot_get_program_path("hello") returns "." \item gnuplot_get_program_path("ls") returns "/bin" \item gnuplot_get_program_path("csh") returns "/usr/bin" \item gnuplot_get_program_path("/bin/ls") returns NULL \end{itemize} */ /*-------------------------------------------------------------------------*/ char * gnuplot_get_program_path(char * pname); /*-------------------------------------------------------------------------*/ /** @name gnuplot_init @memo Opens up a gnuplot session, ready to receive commands. @return Newly allocated gnuplot control structure. @doc This opens up a new gnuplot session, ready for input. The struct controlling a gnuplot session should remain opaque and only be accessed through the provided functions. */ /*--------------------------------------------------------------------------*/ gnuplot_ctrl * gnuplot_init(void); /*-------------------------------------------------------------------------*/ /** @name gnuplot_close @memo Closes a gnuplot session previously opened by gnuplot_init() @param handle Gnuplot session control handle. @return void @doc Kills the child PID and deletes all opened temporary files. It is mandatory to call this function to close the handle, otherwise temporary files are not cleaned and child process might survive. */ /*--------------------------------------------------------------------------*/ void gnuplot_close(gnuplot_ctrl * handle); /*-------------------------------------------------------------------------*/ /** @name gnuplot_cmd @memo Sends a command to an active gnuplot session. @param handle Gnuplot session control handle @param cmd Command to send, same as a printf statement. @return void @doc This sends a string to an active gnuplot session, to be executed. There is strictly no way to know if the command has been successfully executed or not. The command syntax is the same as printf. Examples: \begin{itemize} \item gnuplot_cmd(g, "plot %d*x", 23.0); \item gnuplot_cmd(g, "plot %g * cos(%g * x)", 32.0, -3.0); \end{itemize} */ /*--------------------------------------------------------------------------*/ void gnuplot_cmd(gnuplot_ctrl * handle, char * cmd, ...); /*-------------------------------------------------------------------------*/ /** @name gnuplot_setstyle @memo Change the plotting style of a gnuplot session. @param h Gnuplot session control handle @param plot_style Plotting-style to use (character string) @return void @doc The provided plotting style is a character string. It must be one of the following: \begin{itemize} \item {\it lines} \item {\it points} \item {\it linespoints} \item {\it impulses} \item {\it dots} \item {\it steps} \item {\it errorbars} \item {\it boxes} \item {\it boxeserrorbars} \end{itemize} */ /*--------------------------------------------------------------------------*/ void gnuplot_setstyle(gnuplot_ctrl * h, char * plot_style); /*-------------------------------------------------------------------------*/ /** @name gnuplot_resetplot @memo Resets a gnuplot session (next plot will erase previous ones). @param h Gnuplot session control handle. @return void @doc Resets a gnuplot session, i.e. the next plot will erase all previous ones. */ /*--------------------------------------------------------------------------*/ void gnuplot_resetplot(gnuplot_ctrl * h); /*-------------------------------------------------------------------------*/ /** @name gnuplot_plot_x @memo Plots a 2d graph from a list of doubles. @param handle Gnuplot session control handle. @param x Array of doubles. @param n Number of values in the passed array. @param title Title of the plot. @return void @doc Plots out a 2d graph from a list of doubles. The x-coordinate is the index of the double in the list, the y coordinate is the double in the list. Example: \begin{verbatim} gnuplot_ctrl *h ; double d[50] ; int i ; h = gnuplot_init() ; for (i=0 ; i<50 ; i++) { d[i] = (double)(i*i) ; } gnuplot_plot_x(h, d, 50, "parabola") ; sleep(2) ; gnuplot_close(h) ; \end{verbatim} */ /*--------------------------------------------------------------------------*/ void gnuplot_plot_x( gnuplot_ctrl * handle, double * d, int n, char * title ); /*-------------------------------------------------------------------------*/ /** @name gnuplot_plot_xy @memo Plot a 2d graph from a list of points. @param handle Gnuplot session control handle. @param x Pointer to a list of x coordinates. @param y Pointer to a list of y coordinates. @param n Number of doubles in x (assumed the same as in y). @param title Title of the plot. @return void @doc Plots out a 2d graph from a list of points. Provide points through a list of x and a list of y coordinates. Both provided arrays are assumed to contain the same number of values. \begin{verbatim} gnuplot_ctrl *h ; double x[50] ; double y[50] ; int i ; h = gnuplot_init() ; for (i=0 ; i<50 ; i++) { x[i] = (double)(i)/10.0 ; y[i] = x[i] * x[i] ; } gnuplot_plot_xy(h, x, y, 50, "parabola") ; sleep(2) ; gnuplot_close(h) ; \end{verbatim} */ /*--------------------------------------------------------------------------*/ void gnuplot_plot_xy( gnuplot_ctrl * handle, double * x, double * y, int n, char * title ) ; /*-------------------------------------------------------------------------*/ /** @name gnuplot_plot_once @memo Open a new session, plot a signal, close the session. @param title Plot title @param style Plot style @param label_x Label for X @param label_y Label for Y @param x Array of X coordinates @param y Array of Y coordinates (can be NULL) @param n Number of values in x and y. @return @doc This function opens a new gnuplot session, plots the provided signal as an X or XY signal depending on a provided y, waits for a carriage return on stdin and closes the session. It is Ok to provide an empty title, empty style, or empty labels for X and Y. Defaults are provided in this case. */ /*--------------------------------------------------------------------------*/ void gnuplot_plot_once( char * title, char * style, char * label_x, char * label_y, double * x, double * y, int n ); /*-------------------------------------------------------------------------*/ /** @name gnuplot_plot_slope @memo Plot a slope on a gnuplot session. @param handle Gnuplot session control handle. @param a Slope. @param b Intercept. @param title Title of the plot. @return void @doc Plot a slope on a gnuplot session. The provided slope has an equation of the form: \begin{verbatim} y = ax+b \end{verbatim} Example: \begin{verbatim} gnuplot_ctrl * h ; double a, b ; h = gnuplot_init() ; gnuplot_plot_slope(h, 1.0, 0.0, "unity slope") ; sleep(2) ; gnuplot_close(h) ; \end{verbatim} */ /*--------------------------------------------------------------------------*/ void gnuplot_plot_slope( gnuplot_ctrl * handle, double a, double b, char * title ) ; /*-------------------------------------------------------------------------*/ /** @name gnuplot_plot_equation @memo Plot a curve of given equation y=f(x). @param h Gnuplot session control handle. @param equation Equation to plot. @param title Title of the plot. @return void @doc Plots out a curve of given equation. The general form of the equation is y=f(x), you only provide the f(x) side of the equation. Example: \begin{verbatim} gnuplot_ctrl *h ; char eq[80] ; h = gnuplot_init() ; strcpy(eq, "sin(x) * cos(2*x)") ; gnuplot_plot_equation(h, eq, "sine wave", normal) ; gnuplot_close(h) ; \end{verbatim} */ /*--------------------------------------------------------------------------*/ void gnuplot_plot_equation( gnuplot_ctrl * h, char * equation, char * title ) ; /*-------------------------------------------------------------------------*/ /** @name gnuplot_set_xlabel @memo Sets the x label of a gnuplot session. @param h Gnuplot session control handle. @param label Character string to use for X label. @return void @doc Sets the x label for a gnuplot session. */ /*--------------------------------------------------------------------------*/ void gnuplot_set_xlabel(gnuplot_ctrl * h, char * label); /*-------------------------------------------------------------------------*/ /** @name gnuplot_set_ylabel @memo Sets the y label of a gnuplot session. @param h Gnuplot session control handle. @param label Character string to use for Y label. @return void @doc Sets the y label for a gnuplot session. */ /*--------------------------------------------------------------------------*/ void gnuplot_set_ylabel(gnuplot_ctrl * h, char * label); #endif
C
#include <stdio.h> #include <dirent.h> /* This file to use readdir function */ #include <string.h> /* String function */ #include <sys/stat.h> /* Header for mkdir function */ #include <stdlib.h> /* Malloc Calloc function */ /* Function to get file mode and convert to string */ int FILE_MODE_Get(char *fileName, char *modeStr) { int result = 0; struct stat st = {0}; result = stat(fileName, &st); if(result != 0) { printf("Cannot get status of file\n"); return -1; } /* Check pointer condition */ if(modeStr == NULL) { printf("Need to setup pointer\n"); return -1; } /* Check file is folder or directory */ modeStr[0] = S_ISDIR(st.st_mode) ? 'd' : '-'; modeStr[1] = st.st_mode & S_IRUSR ? 'r' : '-'; modeStr[2] = st.st_mode & S_IWUSR ? 'w' : '-'; modeStr[3] = st.st_mode & S_IXUSR ? 'x' : '-'; modeStr[4] = st.st_mode & S_IRGRP ? 'r' : '-'; modeStr[5] = st.st_mode & S_IWGRP ? 'w' : '-'; modeStr[6] = st.st_mode & S_IXGRP ? 'x' : '-'; modeStr[7] = st.st_mode & S_IROTH ? 'r' : '-'; modeStr[8] = st.st_mode & S_IWOTH ? 'w' : '-'; modeStr[9] = st.st_mode & S_IXOTH ? 'x' : '-'; return 0; } /* Function to operate the command */ int CMD_Operate(const char *option, const char *pathName) { /* Pointer to directiry entry */ struct dirent *de; /* DIR pointer to save open data from dir */ DIR *dr = NULL; if(pathName) { dr = opendir(pathName); } else { /* Open current dir if pathname is NULL */ dr = opendir("."); } if(dr == NULL) { printf("Could not open directory\n"); return -1; } /* Check if option is valid */ if(option) { /* Check -a option */ if(strcmp(option, "-a") == 0) { while((de = readdir(dr)) != NULL) { /* List up all file include hidden file */ printf("%s\n", de->d_name); } } else if(strcmp(option, "-l") == 0) { char *modeStr = (char*)malloc(sizeof(char)*10); char *newFileName = (char*)malloc(sizeof(char)*30); while((de = readdir(dr)) != NULL) { /* List up all file include hidden file */ if(de->d_name[0] != '.') { memset(modeStr, '-', 10); /* Need to update file name with current folder */ snprintf(newFileName, strlen(pathName) + strlen(de->d_name) + 1, "%s%s\n", pathName, de->d_name); FILE_MODE_Get(newFileName, modeStr); printf("%-12s %-20s\n", modeStr, de->d_name); } } free(modeStr); } else if((strcmp(option, "-al") == 0) || (strcmp(option, "-la") == 0)) { char *modeStr = (char*)malloc(sizeof(char)*10); char *newFileName = (char*)malloc(sizeof(char)*30); while((de = readdir(dr)) != NULL) { /* List up all file include hidden file */ memset(modeStr, '-', 10); snprintf(newFileName, strlen(pathName) + strlen(de->d_name) + 1, "%s%s\n", pathName, de->d_name); FILE_MODE_Get(newFileName, modeStr); printf("%-12s %-20s\n", modeStr, de->d_name); } free(modeStr); free(newFileName); } else { printf("Usage: 01.my_ls [-a | -l | -al]"); } } else { while((de = readdir(dr)) != NULL) { /* If the first file or foleder name has '.' that mean it is current or hidden folder */ /* So we will not list it here */ if(de->d_name[0] != '.') { printf("%s\n", de->d_name); } } } closedir(dr); return 0; } int main(int argc, char const *argv[]) { /* Check if only my_ls command, then we will check current folder */ if(argc == 1) { return CMD_Operate(NULL, NULL); } /* Pass option to the command operation */ else if(argc == 2) { return CMD_Operate(argv[1], NULL); } /* Pass option and pathname to command operation */ else if(argc == 3) { return CMD_Operate(argv[1], argv[2]); } else { printf("Usage: 01.my_ls [-a | -l | -al]"); } return 0; }
C
/** * @file SPI.c * @author Kamil Gierlach * @date December 2020 * @brief File contain definitions for SPI */ #include "SPI.h" /** *PRIVATE DEFINITION */ #define SCK 0 #define MOSI 7 #define CS 5 #define DC 7 #define RST 11 void SPI_Init(void){ //enable clock SIM->SCGC5 |= SIM_SCGC5_PORTA_MASK | SIM_SCGC5_PORTB_MASK; SIM->SCGC4 |= SIM_SCGC4_SPI0_MASK; //configure output //SPI0 PORTB->PCR[SCK] |= PORT_PCR_MUX(3); /*SCK (PTB0) */ //PTB->PDDR |= (1<<SCK); PORTA->PCR[MOSI] |= PORT_PCR_MUX(3); /*MOSI (PTA7) */ //PTB->PDDR |= (1<<SCK); //GPIO PORTA->PCR[CS] |= PORT_PCR_MUX(1); /*CS (PTA5) */ PTA->PDDR |= (1<<CS); /* Set CS pin as output*/ PTA->PSOR |= (1<<CS); /*Set active 1 on pin CS*/ PORTB->PCR[DC] |= PORT_PCR_MUX(1); /*DC (PTB7)*/ PTB->PDDR |= (1<<DC); /*set DC pin as output*/ PTB->PCOR |= (1<<DC); PORTB->PCR[RST] |= PORT_PCR_MUX(1); /*RST (PTB11)*/ PTB->PDDR |= (1<<RST); /*set RST pin as output*/ PTB->PSOR |= (1<<RST); /*Set active 1 on pin RST*/ //Config registers, turn on SPI0 as master SPI0->C1 |= SPI_C1_SPE_MASK | SPI_C1_MSTR_MASK; SPI0->C1 &= ~SPI_C1_CPHA_MASK; SPI0->BR = 35; } void SPI_write(uint8_t data){ PTA->PCOR |= (1<<CS); //reset bit //CS musi byc w spi write //male opoznienie pozwala na wyrysowanie czegokolwiek while (!(SPI0->S & SPI_S_SPTEF_MASK)); SPI0->D = data; delay_ms(1); //rysuje cos PTA->PSOR |= (1<<CS); //set bit }
C
#include <unistd.h> #include <arpa/inet.h> #include <stdio.h> #include <string.h> #define BUF_SIZE 60000 int main() { struct sockaddr_in addr; // address int rl = 0; // total lenght of the message char request[BUF_SIZE], response[BUF_SIZE]; int s = socket(AF_INET, SOCK_STREAM, 0); // socket char *rb = NULL; // response body int rbl; // response body length char * sl; // status line if (s == -1) { perror("Socket fail"); return 1; } addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr("216.58.213.100"); // Google server if (connect(s, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) == -1) { perror("Connect fail"); return 1; } sprintf(request, "GET / \r\n"); if (write(s, request, strlen(request)) == -1) { perror("Write fail"); return 1; } // read the response for(int j = 0; (j = read(s, response + rl, BUF_SIZE - rl - 1)) > 0; rl += j); response[rl] = 0; printf("%s", response); printf("\nRead %d chars", rl); }
C
#define NRANSI #include "nrutil.h" #include "linmin.h" #include <stdarg.h> #include <stdio.h> #define TOL 2.0e-4 int ncom; float *pcom,*xicom,(*nrfunc)(float []); void imprimirLogLinmin (char* s, ...) { va_list ap; FILE* archivoLog = fopen ("reconstructor.log", "a"); va_start (ap, s); vfprintf (archivoLog, s, ap); va_end (ap); fclose (archivoLog); } void linmin(float p[], float xi[], int n, float *fret, float (*func)(float [])) { float brent(float ax, float bx, float cx, float (*f)(float), float tol, float *xmin); float f1dim(float x); void mnbrak(float *ax, float *bx, float *cx, float *fa, float *fb, float *fc, float (*func)(float)); int j; float xx,xmin,fx,fb,fa,bx,ax; float promedio = 0; // GUILLE 25/04/2006 ncom=n; pcom=vector(1,n); xicom=vector(1,n); nrfunc=func; for (j=1;j<=n;j++) { pcom[j]=p[j]; xicom[j]=xi[j]; promedio += fabs (xi[j]); // GUILLE 25/04/2006 //printf ("linmin: xi[%d] = %g, promedio = %g\n", j, xi[j], promedio); } promedio /= n; // GUILLE 25/04/2006 ax=0.0; xx=1.0; // punt xx = 1e-3; // GUILLE 01/06/2007 //xx = 1e4; // helix CBI //xx = 1e-1; //gaussianas 4 //xx = 1e-5; //gaussianas 1 //xx = 1e-5; // L1622 //xx = 1e-6; //xx = 1e-8; // ROPHW //xx = 1e-17; //xx = 0.1 / promedio; // GUILLE 25/04/2006 printf ("linmin: xx = %g, promedio = %g, n = %d\n", xx, promedio, n); mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); printf ("-------finalizado mnbrak a = %g, b = %g, c = %g\n", ax, xx, bx); imprimirLogLinmin ("-------finalizado mnbrak a = %g, b = %g, c = %g\n", ax, xx, bx); imprimirLogLinmin (" fa = %g, fb = %g, fc = %g\n", fa, fx, fb); *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); imprimirLogLinmin ("-------finalizado brent xmin = %g, fret = %g\n", xmin, *fret); for (j=1;j<=n;j++) { xi[j] *= xmin; p[j] += xi[j]; //imprimirLogLinmin (" p[%d] = %g\n", j, xi[j]); } imprimirLogLinmin ("\n"); free_vector(xicom,1,n); free_vector(pcom,1,n); } #undef TOL #undef NRANSI
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include "myMacros.h" #include "Company.h" #include "AirportManager.h" #include "General.h" #include "main.h" const char* str[eNofOptions] = { "Add Flight", "Add Airport", "PrintCompany", "Print all Airports", "Print flights between origin-destination", "Sort Flights", "Search Flight" }; int main(int argc, char* argv[]) { char* airportFile = (char*)calloc(sizeof(char), MAX_STR_LEN); char* companyFile = (char*)calloc(sizeof(char), MAX_STR_LEN); if (argc != 3) return -1; sscanf(argv[1], "%s", airportFile); sscanf(argv[2], "%s", companyFile); AirportManager manager; Company company; initManagerAndCompany(&manager, &company, airportFile, companyFile); int option; int stop = 0; do { option = menu(); switch (option) { case eAddFlight: if (!addFlight(&company, &manager)) printf("Error adding flight\n"); break; case eAddAirport: if (!addAirport(&manager)) printf("Error adding airport\n"); break; case ePrintCompany: printCompany(&company, "Hachi", "Babit", "Ba", "Olam", NULL); break; case ePrintAirports: printAirports(&manager); break; case ePrintFlightOrigDest: printFlightsCount(&company); break; case eSortFlights: sortFlight(&company); break; case eSearchFlight: findFlight(&company); break; case EXIT: printf("Bye bye\n"); stop = 1; break; default: printf("Wrong option\n"); break; } } while (!stop); saveManagerToFile(&manager, MANAGER_FILE_NAME); saveCompanyToFile(&company, COMPANY_FILE_NAME); freeManager(&manager); freeCompany(&company); system("pause"); return 1; } int menu() { int option; printf("\n\n"); printf("Please choose one of the following options\n"); for (int i = 0; i < eNofOptions; i++) printf("%d - %s\n", i, str[i]); printf("%d - Quit\n", EXIT); scanf("%d", &option); //clean buffer char tav; scanf("%c", &tav); return option; } int initManagerAndCompany(AirportManager* pManager, Company* pCompany, char* airportFile, char* companyFile) { int res = initManager(pManager, airportFile); if (!res) { printf("error init manager\n"); return 0; } if (res == FROM_FILE) return initCompanyFromFile(pCompany, pManager, companyFile); else initCompany(pCompany, pManager); return 1; }
C
#include <stdio.h> int main(void) { if(remove("sample.txt") == 0) printf("sample.txt를 삭제하였습니다.\n"); else printf("sample.txt를 삭제할 수 없습니다.\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* equation_sphere.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cfeijoo <cfeijoo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/26 18:28:42 by cfeijoo #+# #+# */ /* Updated: 2014/03/26 18:46:27 by cfeijoo ### ########.fr */ /* */ /* ************************************************************************** */ #include <rt.h> #include <ray.h> #include <object.h> #include <math.h> static float sphere_equation_det(t_object *s, t_ray *ray, float *a, float *b) { t_vector ray_direction; t_point ray_origin; t_point s_origin; float radius; float c; ray_direction = ray->direction; ray_origin = ray->origin; s_origin = s->origin; radius = s->radius; *a = ray_direction.x * ray_direction.x + ray_direction.y * ray_direction.y + ray_direction.z * ray_direction.z; *b = 2 * (ray_direction.x * (ray_origin.x - s_origin.x) + ray_direction.y * (ray_origin.y - s_origin.y) + ray_direction.z * (ray_origin.z - s_origin.z)); c = (ray_origin.x - s_origin.x) * (ray_origin.x - s_origin.x) + (ray_origin.y - s_origin.y) * (ray_origin.y - s_origin.y) + (ray_origin.z - s_origin.z) * (ray_origin.z - s_origin.z) - radius * radius; return (c); } float sphere_equation(t_object *sphere, t_ray *ray) { float res; float a; float b; float c; float det; c = sphere_equation_det(sphere, ray, &a, &b); det = b * b - 4 * a * c; if (det >= 0) { det = sqrt(det); res = positive_smallest((-b + det) / (2 * a), (-b - det) / (2 * a)); return (res); } return (INFINITY); }
C
/* ** signal.c for navy in /home/benjamin.g/delivery/PSU_2016_navy ** ** Made by Benjamin GAYMAY ** Login <benjamin.g@epitech.net> ** ** Started on Thu Feb 2 16:26:45 2017 Benjamin GAYMAY ** Last update Fri Feb 3 11:13:50 2017 benoit pingris */ #include "navy.h" char *get_cell(char bool, int do_or_not) { static char my_bin[8] = "0000000\0"; static int i = 0; if (do_or_not == 1) { if (i == 7) i = 0; my_bin[i] = bool; ++i; } return (my_bin); } void catch_0() { get_cell('0', 1); } void catch_1() { get_cell('1', 1); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int main() { pid_t pid; int i; for(i = 0; i<5;i++) { pid = fork(); printf("创建了一个子进程!\n"); if(pid < 0){ perror("fork error!\n"); } else if(pid == 0) { break; } } if(i<5){ sleep(i); printf("child process %dth pid = %d, ppid = %d\n", i, getpid(), getppid()); } else{ sleep(i); printf("father process pid = %d, ppid = %d\n", getpid(), getppid()); } return 0; }
C
#include "shell.h" /* global variable for ^C handling */ unsigned int sig_flag; /** * sig_handler - handles ^C signal interupt * @uuv: unused variable (required for signal function prototype) * * Return: void */ static void sig_handler(int uuv) { (void) uuv; if (sig_flag == 0) _puts("\n$ "); else _puts("\n"); } /** * main - main function for the shell * @argc: number of arguments passed to main * @argv: array of arguments passed to main * @environment: array of environment variables * * Return: 0 or exit status, or ? */ int main(int argc __attribute__((unused)), char **argv, char **environment) { size_t len_buffer = 0; unsigned int is_pipe = 0; struct stat st; vars_t vars = {NULL, NULL, NULL, 0, NULL, 0}; vars.argv = argv; vars.env = make_env(environment); signal(SIGINT, sig_handler); if (fstat(STDIN_FILENO, &st) == -1) { perror("Fatal Error"); free_env(vars.env); exit(1); } if ((st.st_mode & S_IFMT) == S_IFIFO) is_pipe = 1; if (is_pipe == 0) _puts("$ "); sig_flag = 0; while (getline(&(vars.buffer), &len_buffer, stdin) != -1) { sig_flag = 1; vars.count++; vars.av = tokenize(vars.buffer, "\n \t\r"); if (vars.av && vars.av[0]) if (check_for_builtins(&vars) == NULL) check_for_path(&vars); free(vars.buffer); free(vars.av); sig_flag = 0; if (is_pipe == 0) _puts("$ "); vars.buffer = NULL; } if (is_pipe == 0) _puts("\n"); free_env(vars.env); free(vars.buffer); exit(vars.status); }
C
// // Created by hao on 18-5-23. // #ifndef UDGADJMATRIXTRAVERSE_UDG_ADJ_MATRIX_H #define UDGADJMATRIXTRAVERSE_UDG_ADJ_MATRIX_H #include <stdio.h> #include "circular_queue.h" #define MAXVEX 100 // 最大顶点数 #define INFINIFY 65535 // 用 65535 代表无限大 #define TRUE 1 #define FALSE 0 #define LENGTH(a) (sizeof(a) / sizeof(a[0])) typedef char VertexType; // 顶点类型 typedef int EdgeType; // 边上的权值类型 typedef int Boolean; Boolean visited[MAXVEX]; typedef struct { VertexType vexs[MAXVEX]; // 顶点表 EdgeType arc[MAXVEX][MAXVEX]; // 邻接矩阵,可看做边表 int numVertexes, numEdges; // 图中当前的顶点数和边数 }MGraph; /* 通过输入构建图的邻接矩阵结构 */ void CreateMGraph(MGraph *G); /* 获取顶点坐标 */ int GetPosition(MGraph G, VertexType ch); /* 创建示例图 */ void CreateMGraphExample(MGraph *G); /* 邻接矩阵的深度优先递归算法 */ void DFS(MGraph G, int i); /* 邻接矩阵的深度遍历操作 */ void DFSTraverse(MGraph G); /* 邻接矩阵的广度遍历算法 */ void BFSTraverse(MGraph G); #endif //UDGADJMATRIXTRAVERSE_UDG_ADJ_MATRIX_H
C
/*-----------------------------------------------------------------------*/ /* Low level disk I/O module skeleton for FatFs (C)ChaN, 2014 */ /*-----------------------------------------------------------------------*/ /* If a working storage control module is available, it should be */ /* attached to the FatFs via a glue function rather than modifying it. */ /* This is an example of glue functions to attach various exsisting */ /* storage control modules to the FatFs module with a defined API. */ /*-----------------------------------------------------------------------*/ #include "diskio.h" /* FatFs lower layer API */ #include <stdint.h> #include "stm32_sdio_common.h" #include "stm32_sdio_sd.h" #define SDIOTIMEOUT 0xFFFF; DWORD systemTime = ((2013UL-1980) << 25) // Year = 2013 | (2UL << 21) // Month = Feb | (12UL << 16) // Day = 12 | (10U << 11) // Hour = 10 | (30U << 5) // Min = 30 | (0U >> 1) // Sec = 0 ; /*-----------------------------------------------------------------------*/ /* Get Drive Status */ /*-----------------------------------------------------------------------*/ DSTATUS disk_status ( BYTE pdrv /* Physical drive nmuber to identify the drive */ ) { if (pdrv) return STA_NOINIT; /* Supports only single drive */ return 0; } /*-----------------------------------------------------------------------*/ /* Inidialize a Drive */ /*-----------------------------------------------------------------------*/ DSTATUS disk_initialize ( BYTE pdrv /* Physical drive nmuber to identify the drive */ ) { return 0; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ DRESULT disk_read ( BYTE pdrv, /* Physical drive nmuber to identify the drive */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address in LBA */ UINT count /* Number of sectors to read */ ) { // Read the data from the Card //printf("---rd sect %d count %d\r\n",sector,count); //watchdog.reload(); memset(buff, 0xFF, 512 * count); /* if(count>1) { */ if( SD_ReadMultiBlocks((BYTE*)buff, sector*512, 512, count) != SD_OK ) return RES_ERROR; if( SD_WaitReadOperation() != SD_OK ) return RES_ERROR; /* } else { if( SD_ReadBlock((BYTE*)buff, sector*512, 512) != SD_OK ) return RES_ERROR; if( SD_WaitReadOperation() != SD_OK ) return RES_ERROR; } */ #ifdef NOSDIOTIMEOUT while(SD_GetStatus() != SD_TRANSFER_OK); #else uint32_t timeout = SDIOTIMEOUT; while( (SD_GetStatus() != SD_TRANSFER_OK) && (timeout>0) ) { timeout--; } if(timeout==0) return RES_ERROR; #endif return RES_OK; } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ #if _USE_WRITE DRESULT disk_write ( BYTE pdrv, /* Physical drive nmuber to identify the drive */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address in LBA */ UINT count /* Number of sectors to write */ ) { // Write the data from the Card //printf("---wr sect %d count %d\r\n",sector,count); /* for(int i=0;i<10;i++) { printf("%c",buff[i]); } printf("\r\n"); */ //watchdog.reload(); /* if(count>1) { */ if( SD_WriteMultiBlocks((uint8_t*)buff, sector*512, 512, count) != SD_OK ) return RES_ERROR; if( SD_WaitWriteOperation() != SD_OK ) return RES_ERROR; /* for(int i=0;i<count;i++) { if( SD_WriteBlock((uint8_t*)buff, sector*512*(i+1), 512) != SD_OK ) return RES_ERROR; if( SD_WaitWriteOperation() != SD_OK ) return RES_ERROR; } */ /* } else { if( SD_WriteBlock((uint8_t*)buff, sector*512, 512) != SD_OK ) return RES_ERROR; if( SD_WaitWriteOperation() != SD_OK ) return RES_ERROR; } */ #ifdef NOSDIOTIMEOUT while(SD_GetStatus() != SD_TRANSFER_OK); #else uint32_t timeout = SDIOTIMEOUT; while( (SD_GetStatus() != SD_TRANSFER_OK) && (timeout>0) ) { timeout--; } if(timeout==0) return RES_ERROR; #endif return RES_OK; } #endif /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ #if _USE_IOCTL DRESULT disk_ioctl ( BYTE pdrv, /* Physical drive nmuber (0..) */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { DRESULT res = RES_OK; switch (cmd) { case CTRL_SYNC: // make sure we have availability res = RES_OK; break; case CTRL_TRIM: // make sure we have availability res = RES_OK; break; case GET_SECTOR_COUNT : // Get number of sectors on the disk (DWORD) { IWDG_ReloadCounter(); SD_CardInfo SDCardInfo; SD_GetCardInfo(&SDCardInfo); *(DWORD*)buff = SDCardInfo.CardCapacity / 512; res = RES_OK; break; } case GET_SECTOR_SIZE : // Get R/W sector size (WORD) *(WORD*)buff = 512; res = RES_OK; break; case GET_BLOCK_SIZE : // Get erase block size in unit of sector (DWORD) *(DWORD*)buff = 1; res = RES_OK; } return res; } #endif /*-----------------------------------------------------------------------*/ /* Get current time */ /*-----------------------------------------------------------------------*/ DWORD get_fattime () { return systemTime; } void set_fattime (DWORD t) { systemTime = t; }
C
//ALGROTIMOS P2 - Melisa Dimitry Beltrán #include <stdio.h> #include <math.h> #include <sys/time.h> #include <inttypes.h> #include <stdlib.h> #include <time.h> #include <malloc.h> #define UMBRAL 1 double microsegundos() { struct timeval t; if (gettimeofday(&t, NULL) < 0 ) return 0.0; return (t.tv_usec + t.tv_sec * 1000000.0); } void inicializar_semilla() { srand(time(NULL)); } //Se generan números pseudoaleatorio entre -n y +n y vector de longitud n void aleatorio(int v [], int n) { int i, m = 2*n + 1; for (i = 0; i < n; i++){ v[i] = (rand() % m) - n; } } void ascendente(int v [], int n) { int i; for (i = 0; i < n; i++){ v[i] = i; } } void descendente(int v [], int n) { int i; for (i = 0; i < n; i++){ v[i] = n - i; } } void imprimir_vector(int v [], int n) { int i; for (i = 0; i < n; i++){ printf("%d ",v[i]); } } void ord_ins (int v [], int n) { int i, j, x; for (i = 1; i < n; i++) { x = v[i]; j = i - 1; while (j >= 0 && v[j] > x) { v[j+1] = v[j];; j--; } v[j+1] = x; } } void intercambiar (int v1[],int i, int j){ int v0; v0 = v1[i]; v1[i] = v1[j]; v1[j] = v0; } void Mediana3 (int v [],int i, int j) { int k; k = ((i + j)/ 2); if (v[k] > v[j]) { intercambiar(v,k,j); } if (v[k] > v[i]) { intercambiar(v,k,i); } if (v[i] > v[j]) { intercambiar(v,i,j); } } void rapida_aux (int v [], int izq, int der) { int i, j, pivote; if (izq + UMBRAL <= der) { Mediana3 (v, izq, der); pivote = v[izq]; i = izq; j = der; do { do { i = i + 1; } while (v[i] < pivote); do { j = j - 1; } while (v[j] > pivote); intercambiar(v, i, j); } while (i < j); intercambiar(v, i, j); intercambiar(v, izq, j); rapida_aux(v, izq, j - 1); rapida_aux(v, j + 1, der); } } void ord_rapida(int v [], int n) { rapida_aux(v, 0, n - 1); if (UMBRAL > 1) { ord_ins(v, n); } } void test_a1 (int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 3; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); t1 = microsegundos(); ord_ins (v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t<500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); ord_ins(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / pow(n,0.6); y = t / pow(n,1.0); z = t / pow(n,1.2); printf("%30d %15f %c %18f %15f %19f %15d\n", n, t, asterisco, x, y, z, it); } void test_a2(int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 2; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); t1 = microsegundos(); ord_ins (v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t < 500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); ord_ins(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / pow(n,1.8); y = t / pow(n,2.0); z = t / pow(n,2.2); printf("%30d %15f %c %18f %15f %19f %15d\n", n, t, asterisco, x, y, z, it); } void test_a3 (int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 2; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); t1 = microsegundos(); ord_ins (v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t < 500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); ord_ins(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / pow(n,1.8); y = t / pow(n,2.0); z = t / pow(n,2.2); printf("%30d %15f %c %18f %15f %19.7f %15d\n", n, t, asterisco, x, y, z, it); } void test_b1 (int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 2; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); t1 = microsegundos(); ord_rapida(v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t < 500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); ascendente(v,n); ord_rapida(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / n; y = t / (n*log(n)); z = t / pow(n,2); printf("%30d %15f %c %18f %15f %19.9f %15d\n", n, t, asterisco, x, y, z, it); } void test_b2 (int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 2; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); t1 = microsegundos(); ord_rapida(v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t<500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); descendente(v,n); ord_rapida(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / n; y = t / (n*log(n)); z = t / pow(n,2); printf("%30d %15f %c %18f %15f %19.9f %15d\n", n, t, asterisco, x, y, z, it); } void test_b3 (int n){ int * v, i, it = 1; char asterisco = ' '; double t,t1,t2,t3,x,y,z; for (i = 0; i < 2; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); t1 = microsegundos(); ord_rapida(v,n); t2 = microsegundos(); t = t2 - t1; free(v); if (t<500){ it = 1000; do { t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); free(v); } t2 = microsegundos(); t3 = (t2-t1) / i; //Guardamos ese tiempo t1 = microsegundos(); for(i = 0; i < it; i++) { v = (int *) malloc (sizeof(int)*n); aleatorio(v,n); ord_rapida(v,n); free(v); } t2 = microsegundos(); asterisco = '*'; t = ((t2-t1) / i) - t3; it = it*10; } while (((t2-t1) - t3 * i) < 500); } } x = t / n; y = t / (n*log(n)); z = t / pow(n,2.0); printf("%30d %15f %c %18f %15f %19.8f %15d\n", n, t, asterisco, x, y, z, it); } int test_0 (){ int n=15; int * v = malloc (sizeof(int)*n); printf ("\n...TEST ORDENACION POR INSERCION...\n\n"); printf("Ordenacion por insercion con inicializacion aleatoria: \n"); inicializar_semilla(); aleatorio(v,n); imprimir_vector(v,n); printf("\n"); ord_ins(v,n); imprimir_vector(v,n); printf("\n\n"); printf("Ordenacion por insercion con inicializacion descendente: \n"); descendente(v,n); imprimir_vector(v,n); printf("\n"); ord_ins(v,n); imprimir_vector(v,n); free(v); printf("\n\n"); return 0; } int test_1 (){ int n=15; int * v = malloc (sizeof(int)*n); printf ("\n...TEST ORDENACION RAPIDA...\n\n"); printf("Ordenacion rápida con inicializacion aleatoria: \n"); inicializar_semilla(); aleatorio(v,n); imprimir_vector(v,n); printf("\n"); ord_rapida(v,n); imprimir_vector(v,n); printf("\n\n"); printf("Ordenacion rápida con inicializacion descendente: \n"); descendente(v,n); imprimir_vector(v,n); printf("\n"); ord_rapida(v,n); imprimir_vector(v,n); printf("\n\n"); free(v); return 0; } void sacarTablas_parte1() { int n; int guiones; printf("\n\nALGORITMO DE ORDENACIÓN POR INSERCIÓN: \n"); printf("\nTiempos v. asc(n) %12s %15s %20s %15s %19s %15s\n", "n", "Tiempo", "sub. n^0.6","ajust. n","sobre. n^1.2", "Iter(*)"); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2) { test_a1(n); } printf("\nTiempos v. desc(n) %12s %15s %20s %15s %19s %15s\n", "n", "Tiempo", "sub. n^1.8","ajust. n^2","sobre. n^2.2", "Iter(*)" ); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2) { test_a2(n); } printf("\nTiempos v. al(n) %14s %15s %20s %15s %19s %15s\n", "n", "Tiempo", "sub. n^1.8","ajust. n^2","sobre. n^2.2", "Iter(*)" ); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2){ test_a3(n); } printf("\nLos tiempos acompañados de un asterisco (*) han sido "); printf("medidos con un numero de iteraciones variable en un bucle\n"); } void sacarTablas_parte2() { int n, guiones; printf("\n\nALGORITMO DE ORDENACiÓN RÁPIDA: \n"); printf("(El umbral utilizado ha sido %d)\n",UMBRAL); printf("\nTiempos v. asc(n) %12s %15s %20s %18s %19s %13s\n", "n", "Tiempo", "sub. n ","ajust. n(log n)","sobre. n^2", "Iter(*)" ); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2) { test_b1(n); } printf("\nTiempos v. desc(n) %12s %12s %20s %20s %16s %15s\n", "n", "Tiempo", "sub. n","ajust. n(log n)","sobre. n^2", "Iter(*)"); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2) { test_b2(n); } printf("\nTiempos v. al(n) %12s %15s %21s %18s %19s %13s\n", "n", "Tiempo", "sub. n ","ajust. n(log n)","sobre. n^2", "Iter(*)"); for (guiones = 0; guiones < 121; guiones++) { printf("-"); } printf("\n"); for (n = 500;n < 32001; n = n * 2) { test_b3(n); } printf("\nLos tiempos acompañados de un asterisco (*) han sido "); printf("medidos con un numero de iteraciones variable en un bucle\n"); } void test() { test_0(); test_1(); } void sacar_Tablas() { sacarTablas_parte1(); sacarTablas_parte2(); } int main() { test(); sacar_Tablas(); return 0; }
C
#include <stdio.h> void message(void) { printf("Have Fun With Programming!\n"); } int main(void) { int i; for(i=1;i<=7;i++) { printf("%2d:",i); message(); } }
C
#include <stdio.h> int main() { double pi; double raio; pi = 3.14159; scanf("%lf", &raio); double area = pi*raio*raio; printf("A=%.4lf\n", area); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../lib/sqlite3.h" #include "header.h" int debitMoney(sqlite3 *db, double amount, char *operationDate, int clientID, int accountID) { char *operationName; double balance; int operationID; int exitCode; sqlite3_stmt *statement; const char *selectBalance="select balance from Account where client_id=? and account_id=?"; const char *updateBalance="update Account set balance=? where client_id=? and account_id=?"; const char *insertOperation="insert into Operation(operation_name) values(?)"; const char *selectOperationID="select operation_id from Operation where operation_name=? limit 1"; const char *selectOperationIDLast="select operation_id from Operation Order by operation_id DESC limit 1"; const char *insertLOG="insert into Log(log_date, operation_id, account_id) values(?,?,?)"; operationName="debit"; if(sqlite3_prepare(db, selectBalance, -1, &statement, 0)!= SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 1, clientID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 2, accountID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } exitCode=sqlite3_step(statement); if(exitCode==SQLITE_DONE) { printf("Wrong accountId or clientId!\n"); return -1; } else if(exitCode==SQLITE_ROW) balance=sqlite3_column_double(statement, 0); if(balance<amount) { printf("It's not enough money on your account!!\n"); return -1; } if(sqlite3_prepare(db, updateBalance, -1, &statement, 0)!= SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_double(statement, 1, balance - amount)) { printf("Could not bind double: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 2, clientID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 3, accountID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } if(sqlite3_step(statement)==SQLITE_DONE) { printf("Balance updated!! You've debit %.3lf $\n", amount); } if(sqlite3_prepare(db, selectOperationID, -1, &statement, 0)!= SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_text(statement, 1, operationName, strlen(operationName), SQLITE_STATIC)) { printf("Could not bind text: %s\n", sqlite3_errmsg(db)); return -1; } exitCode=sqlite3_step(statement); if(exitCode==SQLITE_ROW) operationID=sqlite3_column_int(statement, 0); else if(exitCode==SQLITE_DONE) { if(sqlite3_prepare(db, insertOperation, -1, &statement, 0)!=SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_text(statement, 1, operationName, strlen(operationName), SQLITE_STATIC)) { printf("Could not bind text: %s\n", sqlite3_errmsg(db)); return -1; } if(sqlite3_step(statement)==SQLITE_DONE) { printf("Row into Operation table inserted!!\n"); } if(sqlite3_prepare(db, selectOperationIDLast, -1, &statement, 0)!=SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if(sqlite3_step(statement)==SQLITE_ROW) operationID=sqlite3_column_int(statement, 0); } if(sqlite3_prepare(db, insertLOG, -1, &statement, 0)!= SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_text(statement, 1, operationDate, strlen(operationDate), SQLITE_STATIC)) { printf("Could not bind text: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 2, operationID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 3, accountID)) { printf("Could not bind integer: %s\n", sqlite3_errmsg(db)); return -1; } if(sqlite3_step(statement)==SQLITE_DONE) printf("LOG table updated!!\n"); sqlite3_close(db); return 0; } int getUserInfo(sqlite3 *db, int clientID) { char *email; char *fullName; char *nickName; char *password; int block; int exitCode; sqlite3_stmt *statement; const char *selectClient="select * from Client where client_id=?"; if(sqlite3_prepare(db, selectClient, -1, &statement, 0)!= SQLITE_OK) { printf("Could not prepare statement: %s\n", sqlite3_errmsg(db)); return -1; } if (sqlite3_bind_int(statement, 1, clientID)) { printf("Could not bind text: %s\n", sqlite3_errmsg(db)); return -1; } exitCode=sqlite3_step(statement); if(exitCode==SQLITE_ROW) { fullName=(char*)sqlite3_column_text(statement, 1); printf("Full name: %s\n", fullName); email=(char*)sqlite3_column_text(statement, 2); printf("E-mail: %s\n", email); nickName=(char*)sqlite3_column_text(statement, 3); printf("Nick: %s\n", nickName); password=(char*)sqlite3_column_text(statement, 4); printf("Password: %s\n", password); block=sqlite3_column_int(statement, 5); printf("Is blocked: %d\n", block); } else if(exitCode==SQLITE_DONE) printf("Wrong client id!\n"); sqlite3_finalize(statement); sqlite3_close(db); }
C
/***************************************************************************** * | File : LCD_APP.c * | Author : Waveshare team * | Function : Hardware underlying interface * | Info : * Used to shield the underlying layers of each master * and enhance portability *---------------- * | This version: V1.0 * | Date : 2018-01-11 * | Info : Basic version * ******************************************************************************/ #ifndef __LCD_1IN3_H #define __LCD_1IN3_H #include <stdint.h> #define LCD_HEIGHT 240 #define LCD_WIDTH 240 #define HORIZONTAL 0 #define VERTICAL 1 typedef struct { uint16_t WIDTH; uint16_t HEIGHT; uint8_t SCAN_DIR; } LCD_ATTRIBUTES; extern LCD_ATTRIBUTES LCD; void LCD_Start(uint8_t orientation); void LCD_Clear(uint16_t Color); void LCD_Display(uint16_t *Image); void LCD_DisplayWindows(uint16_t Xstart, uint16_t Ystart, uint16_t Xend, uint16_t Yend, uint16_t *Image); void LCD_DisplayPoint(uint16_t X, uint16_t Y, uint16_t Color); void LCD_Terminate(int signo); void LCD_Init(void); void LCD_Exit(void); #endif
C
#include<stdio.h> typedef struct person{ char name[50]; int age , salary; } person; int main() { person person1; printf("Enter your name:"); scanf("%s",person1.name); printf("Enter your age:"); scanf("%d",&person1.age); printf("Enter your salary:"); scanf("%d",&person1.salary); printf("=========================\n"); printf("%s\n",person1.name); printf("Age : %d , salary : %d",person1.age,person1.salary); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "diff_tensor.h" /*--------------------------------------------------------------------------*/ /* */ /* COHERENCE-ENHANCING ANISOTROPIC DIFFUSION FILTERING */ /* */ /* (Joachim Weickert, 6/2000) */ /* */ /*--------------------------------------------------------------------------*/ /* features: - explicit scheme - presmoothing at noise scale: convolution-based, Neumann b.c. - presmoothing at integration scale: convolution-based, Dirichlet b.c. */ /* ------------------------------------------------------------------------ */ void PA_trans (float a11, /* coeffs of (2*2)-matrix */ float a12, /* coeffs of (2*2)-matrix */ float a22, /* coeffs of (2*2)-matrix */ float *c, /* 1. comp. of 1. eigenvector, output */ float *s, /* 2. comp. of 1. eigenvector, output */ float *lam1, /* larger eigenvalue, output */ float *lam2) /* smaller eigenvalue, output */ /* Principal axis transformation. */ { float help, norm; /* time savers */ /* eigenvalues */ help = sqrt (pow(a22-a11, 2.0) + 4 * a12 * a12); *lam1 = (a11 + a22 + help) / 2.0; *lam2 = (a11 + a22 - help) / 2.0; /* eigenvectors */ *c = 2.0 * a12; *s = a22 - a11 + help; /* normalized eigenvectors */ norm = sqrt (*c * *c + *s * *s); if (norm >= 0.0000001) { *c = *c / norm; *s = *s / norm; } else { *c = 1.0; *s = 0.0; } return; } /* PA_trans */ /* ----------------------------------------------------------------------- */ void PA_backtrans (float c, /* 1. comp. of 1. eigenvector */ float s, /* 2. comp. of 1. eigenvector */ float lam1, /* 1. eigenvalue */ float lam2, /* 2. eigenvalue */ float *a11, /* coeff. of (2*2)-matrix, output */ float *a12, /* coeff. of (2*2)-matrix, output */ float *a22) /* coeff. of (2*2)-matrix, output */ /* Principal axis backtransformation of a symmetric (2*2)-matrix. A = U * diag(lam1, lam2) * U_transpose with U = (v1 | v2) v1 = (c, s) is first eigenvector */ { *a11 = c * c * lam1 + s * s * lam2; *a22 = lam1 + lam2 - *a11; /* trace invariance */ *a12 = c * s * (lam1 - lam2); return; } /* PA_backtrans */ /*--------------------------------------------------------------------------*/ void diff_tensor (float C, /* contrast parameter */ float alpha, /* linear diffusion fraction */ long nx, /* image dimension in x direction */ long ny, /* image dimension in y direction */ float **dxx, /* in: structure tensor el., out: diff. tensor el. */ float **dxy, /* in: structure tensor el., out: diff. tensor el. */ float **dyy) /* in: structure tensor el., out: diff. tensor el. */ /* Calculates the diffusion tensor of CED by means of the structure tensor. */ { long i, j; /* loop variables */ float beta; /* time saver */ float c, s; /* specify first eigenvector */ float mu1, mu2; /* eigenvalues of structure tensor */ float lam1, lam2; /* eigenvalues of diffusion tensor */ beta = 1.0 - alpha; for (i=1; i<=nx; i++) for (j=1; j<=ny; j++) { /* principal axis transformation */ /* SUPPLEMENT CODE */ /* calculate eigenvalues */ /* SUPPLEMENT CODE */ /* principal axis backtransformation */ /* SUPPLEMENT CODE */ } return; } /* diff_tensor */ /*--------------------------------------------------------------------------*/
C
#include <stdio.h> #include <stdlib.h> int main() { char name[20]; int age; int classYear; char hairColor[20]; int heightInInches; char eyeColor[20]; printf("Enter your name: "); scanf("%s", name); printf("Enter your age: "); scanf("%d", &age); printf("Enter your class year: "); scanf("%d", &classYear); printf("Enter your hair color: "); scanf("%s", hairColor); printf("Enter your height in inches: "); scanf("%d", &heightInInches); printf("Enter your eye color: "); scanf("%s", eyeColor); printf("\nName: %s \nAge: %d \nClass year: %d \nHair color: %s \nHeight in inches: %d \nEye color: %s \n", name, age, classYear, hairColor, heightInInches, eyeColor); return 0; }
C
/** @file halt.c @brief This file contains all the checks for dynamical states that result in the termination of the program. @author Rory Barnes ([RoryBarnes](https://github.com/RoryBarnes/)) @date Mar 7 2014 */ #include "vplanet.h" int fiNumHalts(HALT *halt,MODULE *module,int iBody) { /* Count the number of halts VPLANET will check for during the integration */ int iModule; // Dummy variable iterating over modules int iNumHalts=0; // Counts number of halts /* Multi-module halts */ if (halt->bMerge) iNumHalts++; if (halt->dMinObl >= 0) iNumHalts++; if (halt->dMaxEcc < 1) iNumHalts++; if (halt->dMaxMutualInc > 0) iNumHalts++; if (halt->dMinSemi > 0) iNumHalts++; if (halt->dMinEcc > 0) iNumHalts++; if (halt->bPosDeDt) iNumHalts++; /* XXX not implemented yet. if (halt->dMinIntEn > 0) iNumHalts++; */ for (iModule=0;iModule<module->iNumModules[iBody];iModule++) module->fnCountHalts[iBody][iModule](halt,&iNumHalts); return iNumHalts; } void InitializeHalts(CONTROL *control,MODULE *module) { // Malloc memory for halt function pointers int iBody; control->fnHalt=malloc(control->Evolve.iNumBodies*sizeof(fnHaltModule*)); for (iBody=0;iBody<control->Evolve.iNumBodies;iBody++) { control->Halt[iBody].dMaxMutualInc = 0; } } /****************** HALTS *********************/ int HaltMinObl(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { /* Halt simulation if body reaches minimum obliquity. */ if (body[iBody].dObliquity < halt->dMinObl) { if (io->iVerbose >= VERBPROG) { printf("HALT: Body %s's Obliquity = ",body[iBody].cName); fprintd(stdout,body[iBody].dObliquity,io->iSciNot,io->iDigits); printf(", < minimum obliquity = "); fprintd(stdout,halt->dMinObl,io->iSciNot,io->iDigits); printf(" at %.2e years.\n",evolve->dTime/YEARSEC); } return 1; } return 0; } /* Maximum Eccentricity? */ int fniHaltMaxEcc(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { // XXX is EccSq defined here /* Halt simulation if body reaches maximum orbital eccentricity. */ if (sqrt(pow(body[iBody].dHecc,2)+pow(body[iBody].dKecc,2)) >= halt->dMaxEcc) { if (io->iVerbose >= VERBPROG) { printf("HALT: e[%d] = ",iBody); fprintd(stdout,sqrt(pow(body[iBody].dHecc,2)+pow(body[iBody].dKecc,2)),io->iSciNot,io->iDigits); printf(", > max e = "); fprintd(stdout,halt->dMaxEcc,io->iSciNot,io->iDigits); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } return 0; } int HaltMinEcc(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { /* Halt simulation if body reaches minimum eccentricity. */ if (sqrt(pow(body[iBody].dHecc,2)+pow(body[iBody].dKecc,2)) <= halt->dMinEcc) { if (io->iVerbose >= VERBPROG) { printf("HALT: e = "); fprintd(stdout,sqrt(body[iBody].dEccSq),io->iSciNot,io->iDigits); printf(", < min e = "); fprintd(stdout,halt->dMinEcc,io->iSciNot,io->iDigits); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } return 0; } int HaltMinSemi(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { /* Halt simulation if body reaches minimum Semi-Major Axis? */ if (body[iBody].dSemi <= halt->dMinSemi) { if (io->iVerbose >= VERBPROG) { printf("HALT: a = "); fprintd(stdout,sqrt(body[iBody].dEccSq),io->iSciNot,io->iDigits); printf(", < min a = "); fprintd(stdout,halt->dMinSemi,io->iSciNot,io->iDigits); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } return 0; } /* Minimum Internal Power? XXX Rewrite with radheat and thermint written int HaltMinIntEn(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update,int iBody) { if (body[iBody].dIntEn <= halt->dMinIntEn) { if (io->iVerbose >= VERBPROG) { printf("HALT: e = "); fprintd(stdout,body[iBody].dIntEn,io->iSciNot,io->iDigits); printf(", < min e = "); fprintd(stdout,halt->dMinIntEn,io->iSciNot,io->iDigits); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } return 0; } */ /* Positive de/dt? */ int HaltPosDeccDt(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { /* XXX This needs to be redone with Hecc and Kecc if (update[iBody].daDeriv[update[iBody].iEcc] > 0 && halt->bPosDeDt) { if (io->iVerbose >= VERBPROG) { printf("HALT: de/dt = "); fprintd(stdout,update[iBody].daDeriv[update[iBody].iEcc],io->iSciNot,io->iDigits); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } */ return 0; } int HaltMerge(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update, fnUpdateVariable ***fnUpdate,int iBody) { /* Halt if two bodies, i.e. planet and star, merge? */ /* Sometimes integration overshoots and dSemi becomes NaN -> merger */ if (body[iBody].dSemi != body[iBody].dSemi) { if (halt->bMerge) { if (io->iVerbose > VERBPROG) { printf("HALT: Merge at %.2e years!\n",evolve->dTime/YEARSEC); printf("Numerical merger: %s's dSemi became a NaN! Try decreasing dEta by " "a factor of 10.\n",body[iBody].cName); } return 1; } else { if (io->iVerbose > VERBPROG) { printf("Bodies %s and %s merged at %.2e years!\n",body[0].cName, body[iBody].cName,evolve->dTime/YEARSEC); } fdMergePlanet(body,update,fnUpdate,iBody); } } // Is iBody not using binary? if (!body[iBody].bBinary) { if (body[iBody].dSemi*(1.-sqrt(body[iBody].dEccSq)) <= (body[0].dRadius + body[iBody].dRadius)) { /* Merge! */ if (halt->bMerge) { if (io->iVerbose > VERBPROG) { printf("HALT: Bodies %s and %s merged at %.2e years!\n",body[0].cName, body[iBody].cName,evolve->dTime/YEARSEC); } return 1; } else { if (io->iVerbose > VERBPROG) { printf("Bodies %s and %s merged at %.2e years!\n",body[0].cName, body[iBody].cName,evolve->dTime/YEARSEC); } fdMergePlanet(body,update,fnUpdate,iBody); } } // Check for merge when planet is using binary // This also checks if stars merged, for simplicity } else if (body[iBody].bBinary == 1 && body[iBody].iBodyType == 0) { // Using binary, is planet double max_radius = max(body[0].dRadius,body[1].dRadius); if ((body[iBody].dSemi*(1.-sqrt(body[iBody].dEccSq)) <= (body[1].dSemi + max_radius + body[iBody].dRadius)) && halt->bMerge) { /* Merge! */ if (io->iVerbose > VERBPROG) { printf("HALT: Merge at %.2e years! %e,%d\n",evolve->dTime/YEARSEC,body[iBody].dEccSq,iBody); printf("cbp.dSemi: %e, bin.dSemi: %e, max_radius: %e\n",body[iBody].dSemi/AUM,body[1].dSemi/AUM,max_radius/AUM); } return 1; } } else if (body[iBody].bBinary && body[iBody].iBodyType == 1 && iBody == 1) {// Did binary merge? // Merge if sum of radii greater than binary perihelion distance if ((body[0].dRadius + body[1].dRadius >= (1.0 - body[1].dEcc)*body[1].dSemi) && halt->bMerge) { if (io->iVerbose > VERBPROG) { fprintf(stderr,"Binary merged at %.2e years! Semimajor axis [km]: %e.\n",evolve->dTime/YEARSEC,body[iBody].dSemi); fprintf(stderr,"Stellar radii [km]: %e, %e. \n",body[0].dRadius,body[1].dRadius); } return 1; } } return 0; } /******************* Verify *************************/ void VerifyHalts(BODY *body,CONTROL *control,MODULE *module,OPTIONS *options) { /* Verify halt functions to ensure they are valid and make sense given the * enabled modules and the system architecture */ int iBody,iModule,iHalt,iHalt0,iHaltNow; // Dummy counting variables int iHaltMaxEcc=0; // Counts number of halt max eccentricity int iNumMaxEcc=0; // Counts number of max eccentricity occurences for (iBody=0;iBody<control->Evolve.iNumBodies;iBody++) { // First calculate how many halts for this body // First get all the simple cases control->Halt[iBody].iNumHalts = fiNumHalts(&control->Halt[iBody],module,iBody); /* This needs to become module->VerifyCountHaltMaxEccModule? Only necessary if DISTORB called */ /* Some bodies may have additional halts because of a halt for a different body. E.g., distorb requires MaxEcc set for all bodies */ if (control->Halt[iBody].dMaxEcc < 1) { iHaltMaxEcc=iBody; // Body # that has HaltMaxEcc iNumMaxEcc++; // How many files contain HaltMaxEcc? } } if (iHaltMaxEcc) { // HaltMaxEcc was set in at least 1 file, but can only be in 1 if (iNumMaxEcc > 1 && control->Io.iVerbose >= VERBERR) { fprintf(stderr,"ERROR: %s set in %d files; should only be set in one. The maximum value for the eccentricity of all non-primary body will be MAXECCDISTORB\n.",options[OPT_HALTMAXECC].cName,iNumMaxEcc); exit(EXIT_INPUT); } // Now add 1 to each iNumHalts for (iBody=1;iBody<control->Evolve.iNumBodies;iBody++) { if (iBody != iHaltMaxEcc) { control->Halt[iBody].iNumHalts++; } } } if (control->Halt[0].dMaxMutualInc > 0) { if (control->Evolve.iNumBodies == 0) { fprintf(stderr, "ERROR: %s set, but only 1 body present.\n", options[OPT_HALTMAXMUTUALINC].cName); exit(EXIT_INPUT); } } // Now malloc and assign fnHalt function vector for (iBody=0;iBody<control->Evolve.iNumBodies;iBody++) { control->fnHalt[iBody] = malloc(control->Halt[iBody].iNumHalts*sizeof(fnHaltModule)); // Now assign the function vector iHaltNow=0; if (control->Halt[iBody].bMerge) control->fnHalt[iBody][iHaltNow++] = &HaltMerge; if (control->Halt[iBody].dMinObl >= 0) control->fnHalt[iBody][iHaltNow++] = &HaltMinObl; if (control->Halt[iBody].dMaxEcc < 1) control->fnHalt[iBody][iHaltNow++] = &fniHaltMaxEcc; if (control->Halt[iBody].dMaxMutualInc > 0) { /* Note the different approach here. These fn live in their module file. We set initially to DistOrb since it cannot be applied to the central body. SpiNBody, however, can be, so if SpiNBody is set, change to that halt function. */ control->fnHalt[iBody][iHaltNow++] = &fbHaltMaxMutualIncDistorb; if (body[iBody].bSpiNBody) { control->fnHalt[iBody][iHaltNow++] = &fbHaltMaxMutualIncSpiNBody; } } if (control->Halt[iBody].dMinSemi > 0) control->fnHalt[iBody][iHaltNow++] = &HaltMinSemi; if (control->Halt[iBody].dMinEcc > 0) control->fnHalt[iBody][iHaltNow++] = &HaltMinEcc; if (control->Halt[iBody].bPosDeDt) control->fnHalt[iBody][iHaltNow++] = &HaltPosDeccDt; /* XXX Should be changed with thermint completed if (control->Halt[iBody].dMinIntEn > 0) control->fnHalt[iBody][iHaltNow++] = &HaltMinIntEn; */ for (iModule=0;iModule<module->iNumModules[iBody];iModule++) module->fnVerifyHalt[iBody][iModule](body,control,options,iBody,&iHaltNow); /* XXX This needs to become VerifyMultiBodyHalts, as should only be applied if DISTORB called. This problem is hard! */ if (iHaltMaxEcc) { if (iBody != iHaltMaxEcc) { control->Halt[iBody].dMaxEcc = control->Halt[iHaltMaxEcc].dMaxEcc; control->fnHalt[iBody][iHaltNow++] = &fniHaltMaxEcc; } } } } /************** Check for Halts *********************/ int fbCheckHalt(BODY *body,CONTROL *control,UPDATE *update, fnUpdateVariable ***fnUpdate) { int iBody,iHalt; for (iBody=0;iBody<control->Evolve.iNumBodies;iBody++) { for (iHalt=0;iHalt<control->Halt[iBody].iNumHalts;iHalt++) { if (control->fnHalt[iBody][iHalt](body,&control->Evolve, &control->Halt[iBody],&control->Io,update,fnUpdate,iBody)) { return 1; } } } return 0; }
C
/*พงษธร,ดัชนีมวลกาย*/ //ดัชนีมวลกาย #include<stdio.h> void main(){ system("cls"); float h, w, bmi; printf("Enter a no of height : "); scanf("%f",&h); printf("Enter a no of weight : "); scanf("%f",&w); h = h / 100; bmi = (w/(h*h)); printf("bmi = %.2f\n",bmi); if(bmi >= 30) { printf("Fat"); } else if(bmi >= 25){ printf("Overload"); } else if(bmi >= 20){ printf("Healthy"); } else{ printf("below the rating"); } }
C
/* Name: Nick Klabjan * CS login: klabjan * Section(s): Lecture 1 * * Filename: cache1D.c */ int arr[100000]; // global array of integers of size 100,000 int main() { // iterates through the array for (int i = 0; i < 100000; i++) *(arr+i) = i; // sets the value of each element in the array as the index return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> // 프로세스 생성해서 한줄씩 프린트, 터미널 clear하는 테스트 char javafile[30][100], cfile[30][100]; int main(void){ pid_t pid; int status, ret_val; FILE *javafp, *cfp; int javasize, csize; javafp = fopen("../javafile/q1.java", "r"); cfp = fopen("./q1.c", "r"); fseek(javafp, 0, SEEK_END); javasize = ftell(javafp); rewind(javafp); fseek(cfp, 0, SEEK_END); csize = ftell(cfp); rewind(cfp); printf("%d %d\n", javasize, csize); char ch; int i=0, javaline=0, cline=0; while((ch = fgetc(javafp)) != EOF){ javafile[javaline][i] = ch; i++; if(ch == '\n'){ javafile[javaline][i] = 0; javaline ++; i=0; } } javafile[javaline][i] = 0; i = 0; while((ch = fgetc(cfp)) != EOF){ cfile[cline][i] = ch; i++; if(ch == '\n'){ cfile[cline][i] = ch; cline ++; i=0; } } cfile[cline][i] = 0; // fread(javafile, 1, javasize, javafp); // fread(cfile, 1, csize, cfp); for(int j=0; j<javaline; j++){ system("clear"); if((pid = fork()) == 0){ // 자식 프로세스 for(int k=0; k<j; k++){ printf("%s", javafile[k]); } sleep(1); exit(0); } if(pid > 0){ for(int k=0; k<j; k++){ printf("%s", cfile[k]); } printf("--------------------------------\n"); ret_val = wait(&status); } } // printf("%s\n%s\n",javafile, cfile); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define K 6 #define N 5 int main(int argc, char *argv[]) { int a[K][N], n, count = 0; srand(time(NULL)); printf_s("n = "); scanf_s("%d", &n); for (int i = 0; i < K; ++i, printf_s("\n")) { for (int j = 0; j < N; ++j) { a[i][j] = rand() % 290; if (a[i][j] > n) count++; printf_s("%d\t", a[i][j]); } } printf_s("\ncount = %d\n", count); return 0; }
C
#include "stm32f10x_type.h" #include "buffer.h" uint32 receive_buffer_pool_map = 0; uint8 *receive_buffer_pool[RECEIVE_BUFFER_COUNT]; uint8 BUFFER[MAX_BUFFER_LENGTH]; uint16 buffer_size[RECEIVE_BUFFER_COUNT] = { 12, 12, 12, 25, 25, 25, 55, 55, 55, 100, 100, 100 }; uint32 READ_INT32(int offset,void *addr) { uint8 *p; p=(uint8 *)(((uint8 *)addr) + offset); return ((*p)+ ((*(p+1))<<8)+ ((*(p+2))<<16)+ ((*(p+3))<<24)); } void WRITE_INT32(int offset,void *addr,uint32 data) { uint8 *p; p=(uint8 *)(((uint8 *)addr) + offset); *p++ = data & 0xFF; *p++ = (data>>8) & 0xFF; *p++ = (data>>16) & 0xFF; *p = (data>>24) & 0xFF; } uint8 *malloc_buffer(uint16 size) { uint8 i; for(i=0; i<RECEIVE_BUFFER_COUNT; i++) { if(size <= buffer_size[i]) break; } if(i == RECEIVE_BUFFER_COUNT) return NULL; //enter critical for(; i<RECEIVE_BUFFER_COUNT; i++) { if((receive_buffer_pool_map & (1<<i)) != 0) { receive_buffer_pool_map &= (~(1<<i)); break; } } //exit critical if(i == RECEIVE_BUFFER_COUNT) return NULL; return receive_buffer_pool[i]; } static uint8 search_buffer_index(uint8 *buff, uint8 begin, uint8 end) { uint8 middle; if(begin == end) { if(receive_buffer_pool[begin] == buff) { return begin; } else { return 0; } } middle = (begin+end)/2; if(receive_buffer_pool[middle] == buff) { return middle; } else if(receive_buffer_pool[middle] < buff) { return search_buffer_index(buff, middle+1, end); } else { return search_buffer_index(buff, begin, middle-1); } } void free_buffer(uint8 *buff) { uint8 i; i = search_buffer_index(buff, 0, RECEIVE_BUFFER_COUNT-1); if(i != 0) { receive_buffer_pool_map |= (1<<i); } else { if(receive_buffer_pool[0] == buff) receive_buffer_pool_map |= 1; } } void buffer_init(void) { uint8 i, count=0; uint8 *buffer = BUFFER; #if RECEIVE_BUFFER_COUNT == 32 receive_buffer_pool_map = 0xFFFFFFFF; #else receive_buffer_pool_map = (1<<RECEIVE_BUFFER_COUNT) - 1; #endif for(i=0; i<BUFFER1_COUNT; i++) { buffer_size[count] = BUFFER1_LENGTH; receive_buffer_pool[count++] = buffer; buffer += BUFFER1_SPACE_LENGTH; } for(i=0; i<BUFFER2_COUNT; i++) { buffer_size[count] = BUFFER2_LENGTH; receive_buffer_pool[count++] = buffer; buffer += BUFFER2_SPACE_LENGTH; } for(i=0; i<BUFFER3_COUNT; i++) { buffer_size[count] = BUFFER3_LENGTH; receive_buffer_pool[count++] = buffer; buffer += BUFFER3_SPACE_LENGTH; } for(i=0; i<BUFFER4_COUNT; i++) { buffer_size[count] = BUFFER4_LENGTH; receive_buffer_pool[count++] = buffer; buffer += BUFFER4_SPACE_LENGTH; } }
C
#include <stdio.h> void ClearLineFromReadBuffer(void); int main() { char perID[7]; // ex) 911105'\0' 7 迭 ʿ. char name[10]; fputs("ֹιȣ 6ڸ: ", stdout); // Ϳ fgets(perID, sizeof(perID), stdin); // ִ ũ 7 byte Ű Է . /************/ ClearLineFromReadBuffer(); // Է ۸ . ׳ о. ȯ. /************/ fputs("̸ Է: ", stdout); // Ϳ fgets(name, sizeof(name), stdin); // ִ ũ 10 byte Ű Է . printf("ֹιȣ: %s \n", perID); printf("̸: %s \n", name); return 0; } void ClearLineFromReadBuffer(void) { while (getchar() != '\n'); // ڿ 'Ű' ö Read Ǿ. , ʰ ׳ . } /* Լ : int fflush(FILE * stream); 0 ȯ, н EOF ȯ int fflush(stdout); // ͷ ۸ Լ! (stdout: ǹ) // **۸ ٴ , ( ½Ѷ ǹ) */
C
// Programs using command-line arguments rely on the user's memory of how to use them // correctly. Rewrite the program in Listing 13.2 so that, instead of using command-line // arguments, it prompts the user for the required information. #include <stdio.h> #include <stdlib.h> #define MAX 20 void replace(char * str, char target, char rep) { while (*str) { if (*str == target) *str = rep; str++; } } int main(void) { FILE * fd_dest; FILE * fd_sour; char name_dest[MAX]; char name_sour[MAX]; unsigned int count; int ch; count = 1; puts("Hi, this program compresses your source file to one third of the size"); puts("And writes it in destination file"); puts("Let's start!\nEnter name of destination file"); fgets(name_dest, MAX - 1, stdin); replace(name_dest, '\n', '\0'); if ((fd_dest = fopen(name_dest, "w")) == NULL) { fprintf(stderr, "error: can not open file [%s]\n", name_dest); exit(1); } else printf("file [%s] was open\n", name_dest); puts("OK, now enter name of source file"); fgets(name_sour, MAX - 1, stdin); replace(name_sour, '\n', '\0'); if ((fd_sour = fopen(name_sour, "r")) == NULL) { fprintf(stderr, "error: can not open file [%s]\n", name_sour); exit(1); } else printf("file [%s] was open\n", name_sour); while ((ch = getc(fd_sour)) != EOF) { if ((count % 3) == 0) putc(ch, fd_dest); count++; } if ((fclose(fd_dest)) != 0) { fprintf(stderr, "error: can not close file [%s]\n", name_dest); exit(1); } else printf("file [%s] was close\n", name_dest); if ((fclose(fd_sour)) != 0) { fprintf(stderr, "error: can not close file [%s]\n", name_sour); exit(1); } else printf("file [%s] was close\n", name_sour); puts("Good buy"); return (0); }
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> #include<string.h> #define bool char #define true 1 #define false 0 #define MAX(a,b) (a>b?a:b) #define MIN(a,b) (a<b?a:b) /** * Return an array of size *returnSize. //["i", "love", "leetcode", "i", "love", "coding"], k = 2 * Note: The returned array must be malloced, assume caller calls free(). */ char *arrayOfStrings[] = {"i", "love", "leetcode", "i", "love", "coding"}; char *tmpWords[] = {" ", " " , " ", " ", " ", " "}; void merge(char** words, char l, char mid, char r); void mergeSort(char** words, char left, char right) { if(left < right) { int mid = (left + right)/2; mergeSort(words,left, mid); mergeSort(words,mid+1, right); merge(words, left, mid+1, right); } } void merge(char** words, char l, char mid, char r) { int leftEnd = mid; int left = l; int right = mid; int rightEnd = r; int i = 0; int j = 0; while((left < leftEnd) && ( right <= rightEnd)) { if(strcmp(words[left], words[right]) <= 0) { tmpWords[i] = words[left]; i++; left++; } else if(strcmp(words[left], words[right]) > 0) { tmpWords[i] = words[right]; i++; right++; } } while(left < leftEnd) { tmpWords[i] = words[left]; i++; left++; } while(right <= rightEnd) { tmpWords[i] = words[right]; i++; right++; } j = 0; for(i=l; i < r+1 ; i++) { //printf("%s ", tmpWords[j]); words[i] = tmpWords[j]; j++; } //printf("\r\n\r\n"); //free(tmpWords); } char** topKFrequent(char** words, int wordsSize, int k, int* returnSize) { int i = 0; mergeSort(words, 0, wordsSize-1); return words; } int main() { int retSize = 0; int i = 0; int j = 0; for(i=0 ; i<6; i++) { printf("%s ",arrayOfStrings[i]); } printf("\r\n"); topKFrequent(arrayOfStrings,6, 2, &retSize); for(i=0 ; i<6; i++) { printf("%s ",arrayOfStrings[i]); } printf("\r\n"); for(i=0 ; i<6; i++) { if(arrayOfStrings[i] == arrayOfStrings[i+1]) { tmpWords[j] = arrayOfStrings[i]; j++; if(j==2) break; } } for(i=0 ; i<2; i++) { printf("%s ",tmpWords[i]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #define PI 3.14 void main(void) { /* printf("Hello world!\n"); //area of square int h,area_square; printf("enter h of the square :"); scanf("%d",&h); if(h>0) { area_square=h*h; printf("the area of square = %d \n",area_square); } else printf("sorry, h must b > 0\n"); printf("------------------------------------\n"); //area of rectangle int width,hight,area_rectangle; printf("please enter the width of rectangle :"); scanf("%d",&width); printf("please enter the hight of rectangle :"); scanf("%d",&hight); if(width>0 && hight>0) { area_rectangle=width*hight; printf("the area of rectangle = %d \n",area_rectangle); } printf("------------------------------------\n"); //area of circle float r; float area_circle; printf("please enter the radius of circle :"); scanf("%f",&r); area_circle=PI * r *r; printf("the area of circle = %7.2f \n",area_circle); printf("------------------------------------\n"); //area of triangle int height_triangle,base; int area_triangle; printf("please enter the height of triangle :"); scanf("%d",&height_triangle); printf("please enter the base of triangle :"); scanf("%d",&base); area_triangle=(height_triangle*base)/2; printf("the area of triangle = %d \n",area_triangle); printf("------------------------------------\n"); printf(" sum two integer numbers \n"); int num1,num2; int sum=0; printf("please enter number 1 :"); scanf("%d",&num1); printf("please enter number 2 :"); scanf("%d",&num2); sum=num1+num2; printf("the sum of two integers numbers = %d\n",sum); printf("------------------------------------\n"); printf("determine number positive or negative or zero\n"); int number; printf("please enter the number : "); scanf("%d",&number); if(number > 0) { printf("%d is a positive number .\n",number); } else if (number< 0) { printf("%d is a negative number .\n",number); } else printf("%d is zero .\n",number); printf("------------------------------------\n"); printf("determine number odd or even...\n "); int n; printf("enter the number :"); scanf("%d",&n); if(n %2 ==0) printf("%d is even number \n",n); else printf("%d is odd number \n",n); printf("------------------------------------\n"); */ printf("pay amount customer using fewest number of coins ..\n"); printf("------------------------------------\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> void foo(int a,int b) { int d= (b+=4)-(a*=2); // a=12 , b=3 , d= -9 a=(d^=2); // a=-11 , b=3 , d=-11 d=(b/=4)*(a-=3); // a=-14 , b=0 , d=0 } int main() { //wpisz wartosci zmiennych po wykonaniu danej linijki kodu int a = 162410; //tu wpisz swoj numer indeksu int b=a%9; int c=b%4; foo(b+1,c-2); return 0; }
C
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #pragma once #include <stddef.h> #include "ResultCode.h" struct DynamicArray { size_t capacity; // as number of elements size_t size; // as number of elements void* elements; }; typedef struct DynamicArray DynamicArray; DynamicArray makeDynamicArray(); void destructDynamicArray( DynamicArray* dynArr, size_t elementTypeSize ); void assertValidDynamicArray( const DynamicArray* dynArr, size_t elementTypeSize ); ResultCode addToDynamicArrayBack( DynamicArray* dynArr, void* elementToAdd, size_t elementTypeSize ); size_t getDynamicArraySize( const DynamicArray* dynArr, size_t elementTypeSize ); const void* getDynamicArrayElementAt( const DynamicArray* dynArr, size_t index, size_t elementTypeSize ); void removeDynamicArrayElementAt( DynamicArray* dynArr, size_t index, size_t elementTypeSize ); size_t getDynamicArrayCapacity( const DynamicArray* dynArr, size_t elementTypeSize ); ResultCode changeDynamicArrayCapacity( DynamicArray* dynArr, size_t newCapacity, size_t elementTypeSize ); void removeAllDynamicArrayElements( DynamicArray* dynArr, size_t elementTypeSize ); #define ELASTIC_APM_ASSERT_VALID_DYNAMIC_ARRAY( ElementType, dynArr ) \ ELASTIC_APM_ASSERT_VALID_OBJ( assertValidDynamicArray( (dynArr), sizeof( ElementType ) ) ) #define ELASTIC_APM_FOR_EACH_DYNAMIC_ARRAY_ELEMENT( ElementType, elementPtrVar, dynArr ) \ for ( ElementType* elementPtrVar = (ElementType*)((dynArr)->elements), * elementsEnd = ((ElementType*)((dynArr)->elements)) + (dynArr)->size ; \ (elementPtrVar) != elementsEnd ; \ ++(elementPtrVar) ) #define ELASTIC_APM_MAKE_DYNAMIC_ARRAY( ElementType ) \ ((DynamicArray){ .capacity = 0, .size = 0, .elements = NULL }) #define ELASTIC_APM_DESTRUCT_DYNAMIC_ARRAY( ElementType, dynArr ) \ destructDynamicArray( (dynArr), sizeof( ElementType ) ) #define ELASTIC_APM_ADD_TO_DYNAMIC_ARRAY_BACK_IF_FAILED_GOTO( ElementType, dynArr, elementToAdd ) \ ELASTIC_APM_CALL_IF_FAILED_GOTO( addToDynamicArrayBack( (dynArr), (elementToAdd), sizeof( ElementType ) ) ) #define ELASTIC_APM_GET_DYNAMIC_ARRAY_SIZE( ElementType, dynArr ) \ getDynamicArraySize( (dynArr), sizeof( ElementType ) ) #define ELASTIC_APM_GET_DYNAMIC_ARRAY_ELEMENT_AT( ElementType, dynArr, index, outPtr ) \ do { \ outPtr = (ElementType*)( getDynamicArrayElementAt( (dynArr), (index), sizeof( ElementType ) ) ); \ } while( 0 ) #define ELASTIC_APM_REMOVE_DYNAMIC_ARRAY_ELEMENT_AT( ElementType, dynArr, index ) \ removeDynamicArrayElementAt( (dynArr), (index), sizeof( ElementType ) ) #define ELASTIC_APM_GET_DYNAMIC_ARRAY_CAPACITY( ElementType, dynArr ) \ getDynamicArrayCapacity( (dynArr), sizeof( ElementType ) ) #define ELASTIC_APM_CHANGE_DYNAMIC_ARRAY_CAPACITY_IF_FAILED_GOTO( ElementType, dynArr, newCapacity ) \ ELASTIC_APM_CALL_IF_FAILED_GOTO( changeDynamicArrayCapacity( (dynArr), (newCapacity), sizeof( ElementType ) ) ) #define ELASTIC_APM_REMOVE_ALL_DYNAMIC_ARRAY_ELEMENTS( ElementType, dynArr ) \ removeAllDynamicArrayElements( (dynArr), sizeof( ElementType ) )
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <string.h> #include <dirent.h> #include <fcntl.h> #define KEEP_VIDEO_NUM (6*24*2) char *get_current_dir_name(void); int readFileList(char *basePath) { unsigned int i = 0; DIR *dir; struct dirent *ptr; char base[1000]; char tmp[5] = {0}; if ((dir=opendir(basePath)) == NULL) { perror("Open dir error..."); exit(1); } while ((ptr=readdir(dir)) != NULL) { if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir continue; else if(ptr->d_type == 8){ ///file printf("d_name:%s/%s\n",basePath,ptr->d_name); printf("tmp = %s\n", ptr->d_name); } else if(ptr->d_type == 10) ///link file printf("d_name:%s/%s\n",basePath,ptr->d_name); else if(ptr->d_type == 4) ///dir { memset(base,'\0',sizeof(base)); strcpy(base,basePath); strcat(base,"/"); strcat(base,ptr->d_name); readFileList(base); } } closedir(dir); return 1; } void test_read_file_list(void) { DIR *dir; char basePath[1000]; ///get the current absoulte path memset(basePath,'\0',sizeof(basePath)); getcwd(basePath, 999); printf("the current dir is : %s\n",basePath); ///get the file list /* memset(basePath,'\0',sizeof(basePath)); */ /* strcpy(basePath,"./XL"); */ readFileList(basePath); return; } unsigned int find_and_remove(void) { int fd; int ret; unsigned int items; unsigned int length; unsigned int i; char name[26] = {0}; char command_rm[29] = {0}; char buf[1024*1024] = {0}; system("find *.h264 -> find.txt"); fd = open("find.txt", O_RDONLY); ret = read(fd, buf, 1024*1024); length = strlen(buf); items = length / 26; if (items > KEEP_VIDEO_NUM){ memcpy(command_rm, "rm ", 3); memcpy(&command_rm[3], &buf[0], 25); /* printf("command_rm = %s\n", command_rm); */ system(command_rm); } return items; } /* 86400000 һСʱһ */ /* 14400000 10һ */ int main(int argc, char** argv) { /* time_t tNow =time(NULL); time_t tEnd = tNow + 1800; struct tm ptm = { 0 }; struct tm ptmEnd = { 0 }; localtime_r(&tNow, &ptm); localtime_r(&tEnd, &ptmEnd); char szTmp[50] = {0}; strftime(szTmp,50,"%H:%M:%S",&ptm); char szEnd[50] = {0}; strftime(szEnd,50,"%H:%M:%S",&ptmEnd); printf("%s \n",szTmp); printf("%s \n",szEnd); system("PAUSE"); */ /* system("raspivid -w 320 -h 240 -p 0 -t 1000 -o video.h264"); */ /* sleep(2); */ /* test_read_file_list(); return 0; */ unsigned int items; struct tm *t; time_t tt; time(&tt); t = localtime(&tt); char *dir = malloc(1024); memset(dir, 0, sizeof(dir)); dir = (char*)get_current_dir_name(); memcpy(&dir[strlen(get_current_dir_name())], "/output", strlen("/output")); printf("dir = %s\n", dir); /* printf("%4d%02d%02d %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); */ char filename[100] = {0}; char commond_line[100] = {0}; sprintf(filename, "%4d_%02d_%02d__%02d_%02d_%02d.h264", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); /* printf("filename = %s\n", filename); */ unsigned int i; /* 1440 10log */ for (i = 0; i < 14400; i++){ time(&tt); t = localtime(&tt); memset(filename, 0, sizeof(filename)); sprintf(filename, "%4d_%02d_%02d__%02d_%02d_%02d.h264", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); /* printf("filename = %s\n", filename); */ /* raspivid -op 100 -f -rot 180 -w 1280 -h 1024 -p 0 -t 14400000 -o video.h264 */ memcpy(commond_line, "raspivid -p 1080,850,160,120 -rot 180 -w 800 -h 600 -t 600000 -o video.h264", strlen("raspivid -p 1080,850,160,120 -rot 180 -w 800 -h 600 -t 600000 -o video.h264")); memcpy(&commond_line[strlen("raspivid -p 1080,850,160,120 -rot 180 -w 800 -h 600 -t 600000 -o ")], filename, strlen(filename)); printf("commond_line = %s\n", commond_line); system(commond_line); do{ items = find_and_remove(); printf("items = %d\n", items); }while (items > KEEP_VIDEO_NUM); /* sleep(10); */ } return 0; }
C
#include "bases.h" /* The function is obsolete from the previous excersise void func1(const vector* x, vector* fx, matrix* jacobian){ double A=10000; fx->data[0]=A*x->data[0]*x->data[1]-1;// A*x*y = 1 , fx->data[1]=exp(-1*x->data[0])+exp(-1*x->data[1])-1-1/A;//exp(-x) + exp(-y) = 1 + 1/A, double j11 = A * x->data[1] ; // df1/dx double j12 = A * x->data[0]; // df1/dy double j21 = -exp(-1*x->data[0]); // df2/dx double j22 = -exp(-1*x->data[1]); // df2/dy add_matrix_value(jacobian, 0,0,j11); add_matrix_value(jacobian, 0,1,j12); add_matrix_value(jacobian, 1,0,j21); add_matrix_value(jacobian, 1,1,j22); //we don't need to return anything }*/ double func2(vector* x, vector* fx, matrix* Hesse){ //the name of these func-s are ugly, anyways solution should be (a,a^2) where in our case a=1, so (1,1) double x1=x->data[0]; double x2=x->data[1]; //f(x,y) = (1-x)^2+100(y-x^2)^2 is the function, gradient: df/dx=-2*(1-x)+100*2*(y-x^2)*(-2x), and df/dy=200(y-x^2) fx->data[0]=-2*(1-x1)+100*2*(x2-x1*x1)*-2*x1; fx->data[1]=200*(x2-x1*x1); double j11=2+400*x2+1200*x1*x1; double j12=-400*x1; double j21=-400*x1;//it would be strange if these two wouldn't match double j22=200; add_matrix_value(Hesse, 0,0,j11); add_matrix_value(Hesse, 0,1,j12); add_matrix_value(Hesse, 1,0,j21); add_matrix_value(Hesse, 1,1,j22);//I mean, I kinda kept most of the things, so don't really bother renaming j-s... return (1-x1)*(1-x1)+100*(x2-x1*x1)*(x2-x1*x1); } double func3(vector* x, vector* fx, matrix* jacobian){ /*It has one local maximum at x = − 0.270845 { x=-0.270845} { x=-0.270845} and y = − 0.923039 { y=-0.923039} { y=-0.923039} where f ( x , y ) = 181.617 { f(x,y)=181.617} { f(x,y)=181.617}, and four identical local minima: f ( 3.0 , 2.0 ) = 0.0 , { f(3.0,2.0)=0.0, } f(3.0,2.0)=0.0, f ( − 2.805118 , 3.131312 ) = 0.0 , { f(-2.805118,3.131312)=0.0, } f(-2.805118,3.131312)=0.0, f ( − 3.779310 , − 3.283186 ) = 0.0 , { f(-3.779310,-3.283186)=0.0, } f(-3.779310,-3.283186)=0.0, f ( 3.584428 , − 1.848126 ) = 0.0. { f(3.584428,-1.848126)=0.0. } f(3.584428,-1.848126)=0.0. from wikipedia. We should find exactly one of these */ double x1=x->data[0]; double x2=x->data[1]; //f(x,y) = (x^2+y-11)^2+(x+y^2-7)^2, gradient: df/dx=2*2*(x^2+y-11)*x+2*(x+y^2-7) df/dy=2(x^2+y-11)+2*2*(x+y^2-7)*y fx->data[0]=4*(x1*x1 + x2 - 11)*x1 + 2*(x1 + x2*x2 - 7); fx->data[1]=2*(x1*x1 + x2 - 11) + 4*(x1 + x2*x2 - 7)*x2; double j11= 12*x1*x1 + 4*x2-42; //printf("j11 = %g \n", j11 ); double j12 = 4*(x1+x2); double j21 = 4*(x1+x2); double j22 = 4*x1+12*x2*x2-26; add_matrix_value(jacobian, 0,0,j11); add_matrix_value(jacobian, 0,1,j12); add_matrix_value(jacobian, 1,0,j21); add_matrix_value(jacobian, 1,1,j22);// so... jacobian = Hesse now, I just don't want to rename return (x1*x1+x2-11)*(x1*x1+x2-11)+(x1+x2*x2-7)*(x1+x2*x2-7); } /* void func1_noJ(const vector* x, vector* fx){ double A=10000; fx->data[0]=A*x->data[0]*x->data[1]-1;// A*x*y = 1 , fx->data[1]=exp(-1*x->data[0])+exp(-1*x->data[1])-1-1/A;//exp(-x) + exp(-y) = 1 + 1/A, //we don't need to return anything //obsolete function }*/ double func2_noH( vector* x, vector* fx){ //the name of these func-s are ugly, anyways solution should be (a,a^2) where in our case a=1, so (1,1) double x1=x->data[0]; double x2=x->data[1]; //f(x,y) = (1-x)^2+100(y-x^2)^2 is the function, gradient: df/dx=-2*(1-x)+100*2*(y-x^2)*(-2x), and df/dy=200(y-x^2) fx->data[0]=-2*(1-x1)+100*2*(x2-x1*x1)*-2*x1; fx->data[1]=200*(x2-x1*x1); return (1-x1)*(1-x1)+100*(x2-x1*x1)*(x2-x1*x1); } double func3_noH(vector* x, vector* fx){ /*It has one local maximum at x = − 0.270845 { x=-0.270845} { x=-0.270845} and y = − 0.923039 { y=-0.923039} { y=-0.923039} where f ( x , y ) = 181.617 { f(x,y)=181.617} { f(x,y)=181.617}, and four identical local minima: f ( 3.0 , 2.0 ) = 0.0 , { f(3.0,2.0)=0.0, } f(3.0,2.0)=0.0, f ( − 2.805118 , 3.131312 ) = 0.0 , { f(-2.805118,3.131312)=0.0, } f(-2.805118,3.131312)=0.0, f ( − 3.779310 , − 3.283186 ) = 0.0 , { f(-3.779310,-3.283186)=0.0, } f(-3.779310,-3.283186)=0.0, f ( 3.584428 , − 1.848126 ) = 0.0. { f(3.584428,-1.848126)=0.0. } f(3.584428,-1.848126)=0.0. from wikipedia. We should find exactly one of these*/ double x1=x->data[0]; double x2=x->data[1]; //f(x,y) = (x^2+y-11)^2+(x+y^2-7)^2, gradient: df/dx=2*2*(x^2+y-11)*x+2*(x+y^2-7) df/dy=2(x^2+y-11)+2*2*(x+y^2-7)*y fx->data[0]=4*(x1*x1 + x2 - 11)*x1 + 2*(x1 + x2*x2 - 7); fx->data[1]=2*(x1*x1 + x2 - 11) + 4*(x1 + x2*x2 - 7)*x2; return (x1*x1+x2-11)*(x1*x1+x2-11)+(x1+x2*x2-7)*(x1+x2*x2-7); } double buildingvector_norm(matrix* m, int number_of_vector){ double eredm; for (int i=0;i<m->rows;i++){ eredm+=(extr_matrix_value(m, number_of_vector, i)*extr_matrix_value(m, number_of_vector, i)); } return sqrt(eredm); } matrix* qr_gs_inverse( matrix* Q, matrix* R){ matrix* Qt=transpose(Q); matrix* Rt=invert_upper_triangular(R); matrix * object=matrix_multiplication(Rt, Qt); matrix_free(Qt); matrix_free(Rt); return object; } matrix * GramSchmidt (matrix* original){ matrix * R = matrix_alloc(original->cols, original->cols); double* buffer_vector=malloc(sizeof(double)*original->rows); for (int i=0;i<original->cols;i++){ for (int j=0;j<original->rows;j++){ buffer_vector[j]=extr_matrix_value(original, i, j);//this is the ai "vector", the i. column of the A matrix } /* if (i==0){ for (int l=0;l<original->rows;l++){ printf("buffer_vector %g \n", buffer_vector[l] ); } }*/ double Rii=buildingvector_norm(original,i);//i need this multiple times, so don't really want to calculate it separately add_matrix_value(R,i,i,Rii); for (int j=0;j<original->rows;j++){ buffer_vector[j]/=Rii;//normalisation of the vector add_matrix_value(original, i, j, buffer_vector[j]); } for (int j=i+1;j<original->cols;j++){ double Rij=0; for (int k=0;k<original->rows;k++){ Rij+=extr_matrix_value(original, j, k)*buffer_vector[k];//this is the aj "vector", the j. column of the A matrix } add_matrix_value(R,j,i,Rij); add_matrix_value(R,i,j, 0); // print_matrix(R); for (int k=0;k<original->rows;k++){ double new_val=extr_matrix_value(original, j, k); new_val-=buffer_vector[k]*Rij; add_matrix_value(original, j, k, new_val);//this is the aj "vector", the j. column of the A matrix } } } return R; } vector* qr_gs_solve(matrix* Q, matrix* R, vector* b){ matrix* Qt=transpose(Q); vector* object=matrix_vector_appl(Qt, b); for (int i=b->n-1;i>-1;i--){ // printf("Rx(%d) %lg\n",i,object->data[i] ); double buffer=0; for (int j=i+1;j<b->n;j++){ buffer+=extr_matrix_value(R, j, i)*object->data[j]; // printf("Buffer: %lg\n", buffer ); } object->data[i]=(object->data[i]-buffer)/extr_matrix_value(R, i,i); // printf("Rx(%d) now:%lg\n",i,object->data[i] ); } matrix_free(Qt); return object; } vector* least_squares_fit(double funs(int i, double x), int free_par, vector* x_data, vector* y_data, vector* dy_data, matrix* covariance) { int n=x_data->n; matrix* A = matrix_alloc(n,free_par); vector* b = vector_alloc(n); matrix* I = matrix_alloc(free_par, free_par); //identity matrix generated by default for (int i=0;i<n;i++){ b->data[i]=y_data->data[i]/dy_data->data[i]; for(int k=0;k<free_par;k++){ add_matrix_value(A, k, i, funs(k, x_data->data[i])/dy_data->data[i]); } } matrix* R=GramSchmidt(A); //now A is Q vector* sol=qr_gs_solve(A,R,b);//solution vector - the three coefficients //covariance matrix? cov=R inverse* R inverse^transpose //for that, I'll need the inverse of R, which we fortunately do have //R is an upper triangular matrix, and we have an "invert upper triangular matrix" function from back at the Gram Schmidt excersise matrix* R_inverse=invert_upper_triangular(R); matrix* RiT=transpose(R_inverse); //here comes the problem, that all my funcs are not void, looking back that would've been more fortunate. matrix* covariance_mtx=matrix_multiplication( R_inverse,RiT); mimic_mtrx(covariance_mtx, covariance); //free everything matrix_free(A); matrix_free(I); matrix_free(R); matrix_free(R_inverse); matrix_free(RiT); matrix_free(covariance_mtx); vector_free(b); return sol; } int newton( double f(vector* x, vector* df, matrix* H), /* f: objective function, df: gradient, H: Hessian matrix H*/ vector* xstart, /* starting point, becomes the latest approximation to the root on exit */ double eps /* accuracy goal, on exit |gradient|<eps */ ){ int step=0; int dims=xstart->n; matrix* H=matrix_alloc(dims, dims); vector* gradient=vector_alloc(dims); double norm1=eps+0.1;//so the loop will start while (norm1>eps){ double fx=f(xstart, gradient, H); norm1=vector_norm(gradient); matrix* R=GramSchmidt(H); vector* dx=qr_gs_solve(H, R, gradient); double lambda=1; //now scale dx with lambda for (int i=0;i<dx->n;i++){ xstart->data[i]-=dx->data[i];//here Lambda is 1, so we only need to substract dx from x } double Armijo=vector_vector_product(dx, gradient);//This variable is only interesting to satisfy the armijo condition. I'm not sure whether I should recalc it or not, but I will assume the gradient doesn't change that badly while (f(xstart, gradient, H) > (fx+ 0.00001*lambda*Armijo) && lambda> 0.015625) { lambda=lambda/2; for (int i=0;i<dx->n;i++){ xstart->data[i]+=dx->data[i]*lambda; } } f(xstart, gradient, H);//recalc norm1=vector_norm(gradient);//finally recalc matrix_free(R); vector_free(dx); step++; } matrix_free(H); vector_free(gradient); return step; } /*void calc_jacobian(void f(const vector* x, vector* fx ), matrix* J, vector* x, vector* fx, double dx, vector* calls, int which){ vector* fx_dx=vector_alloc(x->n); for (int i = 0; i < x->n; i++){ x->data[i]+=dx; f(x, fx_dx);calls->data[which]++; x->data[i]-=dx; for (int j = 0; j < x->n; ++j) { double df_jdx_i = (fx_dx->data[j] - fx->data[j]) / dx; add_matrix_value(J, j, i, df_jdx_i); } } vector_free(fx_dx); } */ //here comes the B void broydens(matrix* H_inv, matrix* H_new, vector* y, vector* s, double lambda){ int n = H_inv->rows; for (int i=0; i<s->n;i++){ s->data[i]=s->data[i]*lambda*-1; } double alpha = 0.0; vector* object=matrix_vector_appl(H_inv, s); alpha= vector_vector_product(y, object); //printf("y: %g %g object: %g %g\n",y->data[0], y->data[1], object->data[0], object->data[1] ); if (alpha< 0.003 && alpha> 0.003) { //if we don't like the result, make the H_inv into eigenm. matrix_reset(H_inv); vector_free(object); // printf("Broyden out\n" ); return; } vector* H_inv_y = matrix_vector_appl(H_inv, y); vector* pszeu = vector_alloc(n); for (int i=0; i<s->n;i++){ pszeu->data[i]=s->data[i]-H_inv_y->data[i]; } // printf("s %g %g \n H_inv_y %g %g \n ",s->data[0],s->data[1], H_inv_y->data[0], H_inv_y->data[1] ); //printf("pszeu %g %g \n object %g %g \n ",pszeu->data[0],pszeu->data[1], object->data[0], object->data[1] ); matrix* add=vector_vector_matrix(pszeu, object); //print_matrix(add); mtx_scalar_scale(add, -1.00/alpha); // print_matrix(add); matrix_addition(H_inv, add); vector_free(H_inv_y); vector_free(pszeu); vector_free(object); matrix_free(add); } int qsi_newton( double f(vector* x, vector* df), /* f: objective function, df: gradient, H: Hessian matrix H*/ vector* xstart, /* starting point, becomes the latest approximation to the root on exit */ double eps /* accuracy goal, on exit |gradient|<eps */ ){ int step=0; int dims=xstart->n; matrix* H_inv=matrix_alloc(dims, dims);//this is already an identity matrix, since this is how I allocate matrix* H=matrix_alloc(dims, dims); vector* gradient=vector_alloc(dims); vector* gradient_save=vector_alloc(dims); double norm1=eps+0.1; while (norm1>eps && step<100000){//just for safety measures // printf("x is at the start: %g %g\n", xstart->data[0], xstart->data[1] ); double fx=f(xstart, gradient); norm1=vector_norm(gradient); // printf(" this is the gradient: %g %g\n",gradient->data[0], gradient->data[1] ); /* matrix* R=GramSchmidt(H); vector* dx=qr_gs_solve(H, R, gradient);*/ vector* dx=matrix_vector_appl(H_inv, gradient); double lambda=1.0; //now scale dx with lambda for (int i=0;i<dx->n;i++){ xstart->data[i]-=dx->data[i];//here Lambda is 1, so we only need to substract dx from x } // printf("armijo\n" ); double Armijo=vector_vector_product(dx, gradient);//This variable is only interesting to satisfy the armijo condition. I'm not sure whether I should recalc it or not, but I will assume the gradient doesn't change that badly while (f(xstart, gradient_save) > (fx+ 0.0001*lambda*Armijo) && lambda> 0.015625/*1e-5*/) { lambda=lambda/2.0; for (int i=0;i<dx->n;i++){ xstart->data[i]+=dx->data[i]*lambda; } } // printf("out the inner while\n" ); f(xstart, gradient_save);//recalc norm1=vector_norm(gradient_save);//finally recalc //matrix_free(R); for (int i=0;i<dims;i++){ gradient_save->data[i]*=-1; gradient->data[i]+=gradient_save->data[i]; gradient->data[i]*=-1; } // printf("calling the Broydens, %d\n", dx->n ); broydens(H_inv, H, gradient, dx, lambda); // printf("called the Broydens\n" ); for (int i=0;i<dims; i++){ gradient_save->data[i]=gradient->data[i]; } step++; vector_free(dx); } matrix_free(H_inv); matrix_free(H); vector_free(gradient); return step; } double custom_func(vector*x, vector*fx){ double A=x->data[0]; double T=x->data[1]; double B=x->data[2]; //I hardcode the data - i Know it is not elegant the least bit, but I kinda don't have time not to hardcode it if I can double t[] = {0.23,1.29,2.35,3.41,4.47,5.53,6.59,7.65,8.71,9.77}; double y[] = {4.64,3.38,3.01,2.55,2.29,1.67,1.59,1.69,1.38,1.46}; double e[] = {0.42,0.37,0.34,0.31,0.29,0.27,0.26,0.25,0.24,0.24}; int N = sizeof(t)/sizeof(t[0]); double dA=0, dB=0, dT=0, ddA=0, ddB=0, ddT=0;//these values for the gradients double value=0; double data=0; double dif=0; for (int i=0;i<N;i++){ value=A*exp(-t[i]/T)+B; data=y[i]; dif+=(value-data)/e[i]*(value-data)/e[i]; //the gradients analitically dA=exp(-t[i]/T); dT=A*t[i]*exp(-t[i]/T)/(T*T); dB=1; ddA+=2*(value-data)*dA*(e[i]*e[i]); ddB+=2*(value-data)*dB*(e[i]*e[i]); ddT+=2*(value-data)*dT*(e[i]*e[i]); } //update the greadients fx->data[0]=ddA; fx->data[1]=ddT; fx->data[2]=ddB; return dif; }
C
#include <signal.h> #include <stdio.h> #include <unistd.h> int count = 0; void my_sig_handler(int sig) { count++; } int main(int argc, char **argv) { struct sigaction sa; sa.sa_handler = &my_sig_handler; sa.sa_flags = 0; sigfillset(&sa.sa_mask); if(sigaction(SIGINT,&sa,NULL) == -1) { printf("Error installing sighandler. Exiting\n"); return 1; } while(count < 10) { printf("Waiting for SIGINT. Count:%d\n",count); sleep(10); } printf("Enough SIGINTs. Exiting\n"); return 0; }
C
#include<stdio.h> #include<conio.h> int main() { int n1,n2,i,p,flag=0; clrscr(); printf("enter the two numbers\n"); scanf("%d%d",&n1,&n2); p=n1*n2; for(i=1;i<=p/2;i++) { if(i*i==p) { flag=1; break; } } if(flag==1) { printf("yes\n"); } else { printf("no\n"); } getch(); return 0; }
C
/* * ecp_cpy.c * * Created on: Nov 20, 2015 * Author: tslld */ #include "ecdsa.h" #include "ec.h" #include "ec_point.h" /** Make a copy of the point P. * \param R pointer to an ec_point structure * \param P pointer to an ec_point structure * \return 1 if successful, 0 if failed */ int ec_point_cpy(ec_point dest, ec_point src){ int ok = 0; if ((src == NULL) || (dest == NULL)) { fprintf(stdout, "Error ! Destination or source operator is NULL.\n"); return (ok); } mpz_set(dest->x, src->x); mpz_set(dest->y, src->y); dest->infinity = src->infinity; ok = 1; return (ok); }
C
#include <stdio.h> int main() { float lc = 0; int c; while((c = getchar()) != EOF){ if (c == '\n') ++lc; } printf("%0.f\n", lc); }
C
/* * helper_fcns.c * author: Eli Pandolfo * * some helper functions called by eval_expr.c */ #include "deque.h" /* duplicates a character with malloc */ char *ft_chardup(char c) { char *str; str = malloc(2); str[0] = c; str[1] = 0; return (str); } /* checks if a char is an operator (+, -, *, /, %) */ int is_op(char c) { if (c == '+' || c == '-' || c == '/' || c == '*' || c == '%') return (1); else return (0); } /* returns the next number in a string expression given the expression and a postion index */ char *next_num(char *exp, int c) { int length; int d; char *num; length = 0; d = c; while (exp[d] != ' ' && exp[d] != '(' && exp[d] != ')' && exp[d] && (!is_op(exp[d]) || (exp[d] == '-' && (exp[d + 1] >= '0' && exp[d + 1] <= '9')))) { length++; d++; } num = (char *)malloc(length + 1); d = 0; while (d < length) num[d++] = exp[c++]; num[d] = '\0'; return (num); } /* performs a numerical operation on 2 ints */ int operate(char *c, int op1, int op2) { if (*c == '+') return (op2 + op1); else if (*c == '-') return (op2 - op1); else if (*c == '*') return (op2 * op1); else if (*c == '/') return (op2 / op1); else if (*c == '%') return (op2 % op1); else return (0); } /* assigns precedence to operators (* / %, then + -) */ int prec(char op) { int precedence; precedence = 0; if (op == '*' || op == '/' || op == '%') precedence = 2; else if (op == '+' || op == '-') precedence = 1; return (precedence); }
C
/*************************************************/ /* Author : Abdullah Muhammad */ /* Date : 14/3/2018 */ /* Version: V01 2 */ /*************************************************/ /******************************************************/ static Task* RTO_SysTasks [RTO_u8_TASKS_NUM]={(Task*)0}; /*this is the 0 address in the ram .there is noting */ /*called null as it is a #define and it can have any */ /*possible value i wil initialize all the tasks with 0*/ /*and when i found 0 it means this task is not present*/ /*and the zero addres is the first global variable */ /*adrress. */ /******************************************************/ void RTO_voidInitialize(void) { } void RTO_voidCreatTask(Task* Copy_u8Task,u8 Copy_u8Priority) { RTO_SystTasks[Copy_u8Priority]=Copy_u8Task } void RTO_voidDeleteTask(u8 Copy_u8Priority) { RTO_SystTasks[Copy_u8Priority]=(TASK*)0; } void RTO_voidSuspendTask(u8 Copy_u8Priority) { RTO_SystTasks[Copy_u8Priority] -> state =RTO_u8_SUSPENDED; } void RTO_voidContinueTask(u8 Copy_u8Priority) { RTO_SystTasks[Copy_u8Priority] -> state =RTO_u8_RUNNING; } static void RTO_voidScheduler(void) { for (i=0;i<RTO_u8_TASKS_NUM;i++) // { if(RTO_SysTasks[i] !=(Task*)0) { if(RTO_SysTasks[i] -> State != RTO_u8_SUSPENDED) /*cyclometic complexity :is the number of nested */ /*loop or if,and it is not a good thing as every */ /*scope opens a new stack */ { if (RTO_SystTasks[i] -> FirstDelay) == 0) //run the task { Run Task(); //run the task RTO_SysTasks[i] -> FirstDelay = RTO_SysTasks[i] -> Periodicity; // periodicty -1 } else { (RTO_SysTasks[i] -> FirstDelay) -- ; } } } else { /*No task to do*/ } } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include "stp_print.h" #define update_ctx(ctx,bytes) { \ ctx->buf+=bytes; \ ctx->buf_size -= bytes; } static char* indent(char* buf, int buf_size, const char* msg, int level) { memset(buf,0,buf_size); for(int i=0; i<level; i++) { strcat(buf," "); } strcat(buf,msg); return buf; } static int print_field_value(stp_print_context_t* ctx, stp_print_table_t* table, int level, const char* line_fmt) { int bytes = 0; char valbuf[32]; char name_col[32]; table->v.val.func(valbuf, sizeof(valbuf), table->v.val.ptr, table->format); bytes = snprintf(ctx->buf, ctx->buf_size, line_fmt, // name indent(name_col, sizeof(name_col), table->name, level), // type table->type_name, // value valbuf); update_ctx(ctx,bytes); return bytes; } static int print_field_struct(stp_print_context_t* ctx, stp_print_table_t* table, int level) { int bytes = 0; bytes = table->v.st.func(ctx->buf, ctx->buf_size, table->v.st.ptr, table->name, table->type_name, level, ctx->max_name_colum_width); update_ctx(ctx,bytes); return bytes; } static int print_top(stp_print_context_t* ctx, int level, const char* line_fmt) { int bytes; char namebuf[16]; char valbuf[16]; if(ctx->data!=NULL) sprintf(valbuf,"(%p)",ctx->data); else sprintf(valbuf,"%p",ctx->data); bytes = snprintf(ctx->buf, ctx->buf_size, line_fmt, indent(namebuf,sizeof(namebuf),ctx->data_name,level), ctx->data_type_name, valbuf); update_ctx(ctx,bytes); return bytes; } int stp_do_print(stp_print_context_t* ctx, int level) { char line_fmt[32]; int bytes = 0; memset(ctx->buf, 0, ctx->buf_size); snprintf(line_fmt, sizeof(line_fmt), "%%-%0ds %%-12s %%-s\n", ctx->max_name_colum_width); bytes += print_top(ctx,level,line_fmt); for(int i=0; i<ctx->num_field; i++) { if(ctx->table[i].is_value) { bytes += print_field_value(ctx, &ctx->table[i], level+1, line_fmt); } else { bytes += print_field_struct(ctx, &ctx->table[i], level+1); } } return bytes; } int stp_do_print_int(char* buf, int buf_size, void* ptr, char* fmt) { return snprintf(buf,buf_size,fmt,*((int*)ptr)); } int stp_do_print_short(char* buf, int buf_size, void* ptr, char* fmt) { return snprintf(buf,buf_size,fmt,*((short*)ptr)); } int stp_do_print_char(char* buf, int buf_size, void* ptr, char* fmt) { return snprintf(buf,buf_size,fmt,*((char*)ptr)); } int stp_do_print_string(char* buf, int buf_size, void* ptr, char* fmt) { return snprintf(buf,buf_size,"\"%s\"",*((char**)ptr)); } int stp_do_print_ptr(char* buf, int buf_size, void* ptr, char* fmt) { return snprintf(buf,buf_size, "%p", *((void**)ptr)); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main (int argc, char *argv[]){ int n; int *vet; int i; pid_t pid[2]; n = atoi (argv[1]); vet = (int *)malloc(n * sizeof(int)); if (vet == NULL) { printf("Allocatin Error.\n"); exit(1); } printf("Binary Numbers:\n"); for(i=0;i<n;i++){ if((pid[0]=fork())){ //padre che aspetta if((pid[1]=fork())){ //padre che aspetta //waitpid(pid[1],(int*)NULL,0); //waitpid(pid[0],(int*)NULL,0); waitpid(pid[1],(int*)NULL,NULL); waitpid(pid[0],(int*)NULL,NULL); exit(1); }else{ vet[i]=0; } }else{ vet[i]=1; } } for(i=0;i<n;i++){ fprintf(stdout, "%d", vet[i]); } fprintf(stdout, "\n"); free(vet); return 0; }
C
#include <stdbool.h> #include <stdlib.h> #include "types/word.h" #include "types/instruction.h" #include "types/location.h" #include "types/wordType.h" #include "types/memoryMap.h" #include "types/private/memoryMap.h" MemoryMap *createMemoryMap(int maxWords) { MemoryMap *map = malloc(sizeof(MemoryMap)); map->words = malloc(maxWords * sizeof(Word*)); map->maxWords = maxWords; map->isFilled = isMemoryMapFilled; map->addInstruction = addMemoryMapInstruction; map->addData = addMemoryMapData; map->free = freeMemoryMap; return map; } bool isMemoryMapFilled(MemoryMap *this, Location *loc, WordType type) { Word *word = this->words[loc->address]; if (word == NULL) { return false; } if (type == DataWord || type != word->type) { return true; } if (word->instructions[loc->address] != NULL) { return true; } return false; } void addMemoryMapInstruction(MemoryMap *this, Instruction *instr, Location *loc) { Word *word = this->words[loc->address]; if (word == NULL) { word = createWord(InstructionWord); this->words[loc->address] = word; } word->instructions[loc->position] = instr; } void addMemoryMapData(MemoryMap *this, long long data, Location *loc) { Word *word = this->words[loc->address]; if (word == NULL) { word = createWord(DataWord); this->words[loc->address] = word; } word->data = data; } void freeMemoryMap(MemoryMap *this) { for (int i = 0; i < this->maxWords; i++) { if (this->words[i] != NULL) { this->words[i]->free(this->words[i]); } } free(this->words); free(this); }
C
struct heap; //pushes data onto the heap; returns -1 if error otherwise 1 int Push_Data(struct heap ** provided, void ** data); //Delete's the heap and it's internal allocations but not the data void Delete_Heap(struct heap ** provided); //Not destructive in the normal sense; but free's the data as well void Delete_Heap_Destructive(struct heap ** provided, void (*free_Data)(void *)); //Sets the sorting function for the heap, expects 1 or 0 depending on if the second element is larger or smaller //If max-heap actual greater value, if min heap smaller value should be returned 1 int Set_Sort(struct heap ** provided, int (*Data_Sorting)(void *,void*));
C
//Write a program in C to find the length of a string without using library function. #include<stdio.h> int main(){ char str[] = {"string"}; int count = 0; while(str[count] != '\0'){ count++; } printf("%d", count); return 0; }
C
#include "holberton.h" /** * print_alphabet_x10 - return void * Return: void (success) * void - is return type */ void print_alphabet_x10(void) { int i; for (i = 0; i < 10; i++) { char j; for (j = 'a'; j <= 'z'; j++) _putchar(j); _putchar('\n'); } }
C
#include <stdio.h> /*用的是主函数中a,b的地址对其初始化 可以实现a,b的值得交换*/ /*void swap(int *a,int *b) { int temp; temp = *a; *a = *b; *b = temp; }*/ /*用的是主函数中a,b的地址对其初始化 但在本函数中实现的是地址之间的交换 , * a,b的值并没有交换*/ /*void swap(int *a,int *b) { int *temp = NULL; temp = a; a = b; b = temp; }*/ void swap(int a,int b)//用的是主函数中的a,b给其初始化 { int temp; temp = a; a = b; b = temp; } int main(int argc, const char *argv[]) { int a = 3; int b = 5; /* swap(&a,&b);*/ swap(a,b); printf("a = %d\n",a); printf("b = %d\n",b); return 0; }