language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/************************************************************************* > File Name: util.c > Author: lax > Mail: xingkungao@gmail.com > Created Time: Thu 05 Jun 2014 09:16:43 AM CST ************************************************************************/ #include "interCode.h" Operand* newOperand(OperandKind kind, int value) { Operand* op = (Operand*)malloc(sizeof(Operand)); op->kind = kind; switch (kind) { case Variable: case Address: op->u.var_no = value; break; case Constant: case Lbl: case Dereference: op->u.val = value; } return op; } Operand* newTemp() { return newOperand(Variable, tempCnt++); } Operand* newLabel() { return newOperand(Lbl, labelCnt++); } Operand* newVar(int val) { return newOperand(Variable, val); } Operand* newConst(int val) { return newOperand(Constant, val); } Operand* newAddr(int val) { return newOperand(Address, val); } Operand* newDeref(int val) { return newOperand(Dereference, val); } InterCodes* newCallCode(Operand* op, char* name) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = Call; code->u.call.name = (char*)malloc(32 * sizeof(char)); strcpy(code->u.call.name, name); code->u.call.result = op; InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* newAssignCode(Operand* left, Operand* right) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = Assign; code->u.assign.left = left; code->u.assign.right = right; InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* newBinopCode(CodeKind type, Operand* result, Operand* op1, Operand* op2) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = type; code->u.binop.result = result; code->u.binop.op1 = op1; code->u.binop.op2 = op2; InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* newUniopCode(CodeKind type, Operand* op) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = type; code->u.uniop.op = op; InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* newDecCode(Operand* op, int size) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = Decl; code->u.dec.addr = op; code->u.dec.size = size; InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* newFuncCode(char *name) { InterCode *code = (InterCode*)malloc(sizeof(InterCode)); code->kind = Func; code->u.funcdec.name = (char*)malloc(32 * sizeof(char)); strcpy(code->u.funcdec.name, name); InterCodes *codes = (InterCodes*)malloc(sizeof(InterCodes)); codes->code = code; codes->prev = codes->next = codes; return codes; } InterCodes* codesConcat(int n, ...) { if (!n) return NULL; int i; va_list codeList; va_start(codeList, n); InterCodes *codes = va_arg(codeList, InterCodes*); InterCodes *ptr, *last, *p; /** pay attention to null pointers in args*/ for (i = 1; i < n; i++) { ptr = va_arg(codeList,InterCodes*); if (!codes) codes = ptr; else if (ptr){ /* ptr->next = codes; ptr->prev = codes->prev; ptr->prev->next = ptr; ptr->next->prev = ptr; */ p = ptr->prev; codes->prev->next = ptr; last = codes->prev; ptr->prev->next = codes; ptr->prev = last; codes->prev = p; } } va_end(codeList); return codes; }
C
/* Jordan Chalupka 0928258 */ #ifndef __LIST_ADT__ #define __LIST_ADT__ #include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct listNode { int nodeValue; struct listNode * next; } node; node * createList (void); /* Pre: None Post: An initialized list ADT */ void destroyList (node *); /* Pre: Initialized list ADT Post: Memory freed for list ADT */ void addFront (node *, int); /* Pre: Initialized list ADT Post: New node added to front of list ADT, length increased by one */ int getFrontValue (node *); /* Pre: Initialized list ADT Post: None */ int getLength (node *); /* Pre: Initialized list ADT Post: None */ void printList (node *); /* Pre: Initialized list ADT Post: None */ void removeFront (node *); /* Pre: Initialized list ADT Post: Node removed from the front of the list ADT, length decreased by one */ int isInit (node *); /* Pre: Pointer to initialized or uninitialized list ADT Post: None */ #endif
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> long long int koong(long long int n) { int i; if(n < 2) return 1; if(n == 2) return 2; if(n == 3) return 4; else {long long int arr[68] = {0, }; arr[0] = 1; arr[1] = 1; arr[2] = 2; arr[3] = 4; for(i=4; i<=n; i++) { arr[i] = arr[i-1] + arr[i-2] + arr[i-3] + arr[i-4]; } return arr[n]; } } main() { int t; int i; long long int n; scanf("%d", &t); for(i=0; i<t; i++) { scanf("%lld", &n); printf("%lld\n", koong(n)); } }
C
#include <stdio.h> int main(void) { char s[100]; int i,n,alp=0,num=0; gets(s); n=strlen(s); for(i=0;i<n;i++) { if(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z') { alp=1; } if(s[i]>=1&&s[i]<=100) { num=1; } } if(alp==1&&num==1) { printf("\nyes"); } else { printf("\nno"); } return 0; }
C
#include "disk.h" #include <string.h> #include <stdio.h> #include <stdlib.h> static const char* s_help_options = "Accepta o singura comanda, cu exceptia lui --priority\n" "Usage: da [OPTION]... [DIR]...\n" "Analyze the space occupied by the directory at [DIR]\n" "-a, --add analyze a new directory path for disk usage\n" "-p, --priority set priority for the new analysis (works only with -a argument)\n" "-S, --suspend <id> suspend task with <id>\n" "-R, --resume <id> resume task with <id>\n" "-r, --remove <id> remove the analysis with the given <id>\n" "-i, --info <id> print status about the analysis with <id> (pending, progress, done)\n" "-l, --list list all analysis tasks, with their ID and the corresponding root path\n" "-p, --print <id> print analysis report for those tasks that are \"done\"\n"; // link pe github https://github.com/Vector2025/disk_analyser int main(int argc, char* argv[]) { #define GET_INT_ARG atoi(argv[argpos+1]) #define IS_COMMAND(short, long) \ ((str_command=long,0) || strcmp(argv[argpos], short ) == 0 || strcmp(argv[argpos], long) == 0) #define ASSERT_HAS_ARG(index) \ if((argc - 1) < index){ \ printf("comanda %s are nevoie de un argument\n", str_command); \ exit(-1); \ } int command_arg_pos = 2; const int default_priority = 2; int argpos = 1; const char* str_command = ""; // folosit de macrouri if(argc == 1 || IS_COMMAND("-h", "--help")){ printf("%s", s_help_options); exit(0); } else if(IS_COMMAND("-a", "--add")) { ASSERT_HAS_ARG(command_arg_pos); argpos++; const char* path = argv[argpos]; int priority = 2; if((argc - 1) >= 3){ argpos++; if(IS_COMMAND("-p", "--priority")){ ASSERT_HAS_ARG(4); priority = GET_INT_ARG; if(priority < 1 || priority > 3){ printf("prioritate invalida: %d, trebuie sa fie 1, 2 sau 3\n", priority); exit(EXIT_FAILURE); } } else { printf("command %s nu poate fi executata, abort...\n", argv[argpos]); } } proc_add(path, priority); } else if(IS_COMMAND("-S", "--suspend")) { ASSERT_HAS_ARG(command_arg_pos); proc_suspend(GET_INT_ARG); } else if(IS_COMMAND("-R", "--resume")) { ASSERT_HAS_ARG(command_arg_pos); proc_resume(GET_INT_ARG); } else if(IS_COMMAND("-r", "--remove")) { ASSERT_HAS_ARG(command_arg_pos); proc_remove(GET_INT_ARG); } else if(IS_COMMAND("-i", "--info")) { ASSERT_HAS_ARG(command_arg_pos); proc_info(GET_INT_ARG); } else if(IS_COMMAND("-p", "--print")) { ASSERT_HAS_ARG(command_arg_pos); proc_print(GET_INT_ARG); } else if(IS_COMMAND("-l", "--list")) { proc_list(); } else if(IS_COMMAND("-p", "--priority")) { printf("--priority merge doar cu --add "); } else { printf("comanda: %s nu exista, --help pentru comenzi\n", argv[argpos]); } }
C
/* * kurro_buffer.c * * Created on: Nov 24, 2018 * Author: miftakur */ #include <ring_buffer.h> void ring_buffer_read_str(Ring_Buffer_t *buffer, char *str) { char c; while (buffer->head != buffer->tail) { c = ring_buffer_read(buffer); if (c == -1) break; else *str++ = c; } } void ring_buffer_write(Ring_Buffer_t *buffer, char c) { uint16_t i = (buffer->head + 1) % RING_BUFFER_SIZE; if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } char ring_buffer_read(Ring_Buffer_t *buffer) { if (buffer->head == buffer->tail) return -1; else { char c = buffer->buffer[buffer->tail]; buffer->tail = (buffer->tail + 1) % RING_BUFFER_SIZE; return c; } } bool ring_buffer_available(Ring_Buffer_t *buffer) { return (buffer->head != buffer->tail); }
C
#ifndef F_CPU #define F_CPU 16000000UL // 16 MHz clock speed #endif #include <avr/io.h> #include <util/delay.h> #define LED 5 #define LSHIFT(x) (1 << x) //Shift bits left by x int main(void) { DDRB = 0b00100000; //Set PB5 pin to out PORTB |= LSHIFT(LED); // Turn on the LED while(1) { PORTB ^= LSHIFT(LED); //Toggle the LED switch _delay_ms(3000); } }
C
#include"dk_tool.h" int** create_matrix(int row, int col) { int** matrix = (int**)malloc(sizeof(int*) * row); for (int i = 0; i < row; i++) { *(matrix + i) = (int*)malloc(sizeof(int) * col); } return matrix; } void delete_matrix(int** matrix, int row) { if (matrix == NULL) { return; } for (int i = 0; i < row; i++) { free(*(matrix + i)); } free(matrix); } void fill_matrix(int** matrix, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { *(*(matrix + i) + j) = rand() % 10; } } } void print_matrix(int** matrix, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%d ", *(*(matrix + i) + j)); } printf("\n"); } } int** diff_matrix(int** matrix1, int** matrix2, int row, int col) { int** new_matrix = create_matrix(row,col); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { *(*(new_matrix + i) + j) = *(*(matrix1 + i) + j) - *(*(matrix2 + i) + j); } } return new_matrix; }
C
// void free(void *ptr); // void *malloc(int size); // int printf(const char *format, ...); #include <stdio.h> /* The following #ifdef and its contents need to remain as-is. */ #ifndef TYPE #define TYPE short TYPE sentinel = -1234; #else extern TYPE sentinel; #endif /* typedefs needed for this task: */ typedef struct node_t { TYPE payload; struct node_t *next; } node; typedef struct range_t { unsigned int length; TYPE *ptr; } range; int lengthOf(node *list) { int i=0; while(list) { list = list->next; i++; } return i; } range convert(node *list) { int i = 0; int length = lengthOf(list); range ans; ans.length = length; ans.ptr = malloc(sizeof(TYPE) * length); while (list) { ans.ptr[i] = list->payload; list = list->next; i++; } return ans; }
C
#include<stdio.h> int main( int argc, char ** argv ) { long long int mine = 0, oppo = 0; while( scanf( "%lld %lld", &mine, &oppo ) != EOF ) { printf("%lld\n", (mine > oppo ) ? mine-oppo : oppo-mine ); } return 0; }
C
#define DLL_EXPORT // for export #include "dll.h" #ifdef __cplusplus extern "C" { #endif void CColorImage(void* buffer, int width, int height, BYTE b, BYTE g, BYTE r) { int x, y; BYTE* buf = (BYTE*)buffer; for (y = 0; y < height; ++y) { for (x = 0; x < width; ++x) { *buf = (BYTE)((b + *buf) >> 1); ++buf; *buf = (BYTE)((g + *buf) >> 1); ++buf; *buf = (BYTE)((r + *buf) >> 1); ++buf; ++buf; } } } int Lim(double x, double y, int limit) { int i, c = 0; double px = 0, py = 0, nx, ny; for (i = 0; i < limit; ++i) { nx = px * px - py * py + x; ny = 2 * px * py + y; if (nx * nx + ny * ny > 4.0) { c = i + 1; break; } else { px = nx; py = ny; } } if (c == 0) { c = limit; } return c; } void CCalcMandel(void* buf, int width, int height, int limit, double scale) { BYTE* data = (BYTE*)buf; int t, x, y; for (y = 0; y < height; ++y) { for (x = 0; x < width; ++x) { t = Lim(x / scale - 2, y / scale - 1, limit); if (t < limit) { t <<= 4; if (t > 0xff) { t = 0xff; } } else { t = 0; } *data = t; ++data; *data = 0; ++data; *data = 0; ++data; ++data; } } } #ifdef __cplusplus } #endif
C
// // Created by qwelzqwelz on 2019/12/25. // #ifndef EXP6_SET_H #define EXP6_SET_H // 集合-结点 typedef struct { char *name; } Node; // 集合 typedef struct { Node **nList; int size; int maxSize; } Set; // 集合-初始化 Set *setInit(int setSize); // 集合-检测某元素是否在集合中 int setHas(Set *s, Node *n); // 集合-添加元素 int setAdd(Set *s, Node *n); // 集合-删除元素 int setDelete(Set *s, Node *n); // 集合-深拷贝 Set *setCopy(Set *s); // 集合-判断集合是否为空 int setIsEmpty(Set *s); // 集合-根据数据获取集合的某一元素 Node *setGetNodeByData(Set *s, char *name); // 集合-打印全部元素 void setPrint(Set *s); #endif //EXP6_SET_H
C
#include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include "tcp.h" #include "aht20.h" #include "http.h" /* * Performs different actions based on integer id, which was provided by the * checkRequest function in http.h. New server features may be added here. */ void interface(int connfd, int id) { double humidity, temp; char content[BUF_LEN]; switch(id) { case 0: measure(&humidity, &temp); sprintf(content, "Humidity: %f%%\r\nTemperature: %f C", humidity, temp); httpResponse(200, "OK", content, connfd); break; case 1: if(soft_reset()) httpResponse(500, "Internal Server Error", "The sensor failed to reset.", connfd); else httpResponse(200, "OK", "Sensor reset successfully.", connfd); break; case 2: if(check_status()) httpResponse(200, "OK", "Sensor is busy.", connfd); else httpResponse(200, "OK", "Sensor is idle.", connfd); break; default: httpResponse(500, "Internal Server Error", "Something went wrong.", connfd); } } int main(int num_args, char **args) { int listenfd, connfd, sensorfd; socklen_t clientlen; struct sockaddr_storage clientaddr; char client_hostname[NI_MAXHOST], client_servicename[NI_MAXSERV]; //buffers to store client name info //check usage if(num_args != 2) { fprintf(stderr, "error: usage is %s <port>\n", args[0]); exit(0); } //open socket if( (listenfd = open_listenfd(args[1])) < 0) { fprintf(stderr, "error: failed to open port %s for listening\n", args[1]); exit(1); } //initialize i2c sensor if ( (sensorfd=open(I2C_BUS, O_RDWR)) < 0 ) { perror("Failed to open i2c bus"); exit(1); } if( init_sensor(sensorfd) ) exit(1); //server loop while(1) { char buff[BUF_LEN]; //used to store messages for reads int req_num; clientlen = sizeof(struct sockaddr_storage); if( (connfd = accept(listenfd, (SA *)&clientaddr, &clientlen)) < 0 ) { fprintf(stderr, "accept error\n"); exit(1); } getnameinfo((SA *)&clientaddr, clientlen, client_hostname, NI_MAXHOST, client_servicename, NI_MAXSERV, 0); printf(">> Server: Connection established with %s:%s!\n", client_hostname, client_servicename); //read client's message read(connfd, buff, BUF_LEN); printf(">> From client: %s\n", buff); //process client's request if( (req_num = checkRequest(buff, connfd)) >= 0 ) { interface(connfd, req_num); } close(connfd); } close(listenfd); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> //The backbone of quicksort is the partition function int partition(int a[], int j, int r) { /*Here I take the last element position to be the pivot element.The basic idea is to place the pivot element in its right position such that all elements before pivot element are less or equal to itself and all elements after pivot element are greater than itself.... Creating a partition... */ int pivot = r; //last element position int i = j - 1; /*Hotfix for initial iteration/recursion .. keeping i at -1 ensures that we dont Skip the first element...*/ int temp; while (j < r) { if (a[j] <= a[pivot]) { i++; //First increment i because i was sitting at -1 at the beginning of the recursion temp = a[i]; /* Swapping a[i] with a[j] for a[j]<a[pivot]*/ a[i] = a[j]; a[j] = temp; } j++; //increment j till pivot-1 as we want to position pivot element } /*At this stage i either lags behind or is equal to j The position where (i+1) is now is the actual position where the pivot element should be... So we swap them.. */ temp = a[i+1]; a[i+1] = a[pivot]; a[pivot] = temp; return i + 1; } void quicksort(int a[], int lb, int ub) { int part; if (lb <= ub) { part = partition(a, lb, ub); quicksort(a, lb, part-1); //calling quicksort on first half of the array quicksort(a, part+1, ub); //calling quicksort on the second half of the array } } int main() { int n,i; printf("Enter No of elements \n"); scanf("%d",&n); int a[10000]; //sample array printf("Enter elements \n"); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("Before Sorting :"); for (int i = 0; i < n; i++) { printf("%d ", a[i]); } printf("\n After Sorting :"); quicksort(a, 0, n-1); for (int i = 0; i < n; i++) { printf("%d ", a[i]); } return 0; }
C
/** * @file main.c * @author Yimou Cao * @date 10/09/2017 * Course: CSCI503 * Lab: 3 */ // unix socket #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include "utils.h" #define SOCK_PATH "/tmp/ymtemp_socket" #define X_MILLION 1 int main(int argc, char *argv[]) { unsigned int x_million = X_MILLION; int parse_status = parse_args(argc, argv, &x_million); if ( parse_status < 0) { exit(EXIT_FAILURE); } printf("The program would test sending %d million messages\n", x_million); // return 0; int pid; pid = fork(); if (pid < 0) { printf("fork fail\n"); exit(EXIT_FAILURE); } if ( pid == 0 ) { //I am the child process and I'm sending sleep(1); // wait for server to set up (server listening) int s, len; struct sockaddr_un remote; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("client: socket error"); exit(EXIT_FAILURE); } printf("Client: trying to connect...\n"); remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (connect(s, (struct sockaddr *)&remote, len) == -1) { perror("client: connect error"); exit(EXIT_FAILURE); } printf("Client: connected.\n"); // set up counter unsigned long sum = 0; unsigned long counter = x_million * 1000000; /* initialize random number generator */ time_t t; srand((unsigned) time(&t)); int r; // get the start time double start_time = get_cur_time(); // printf("Sending starts at: %f s\n", start_time); // send the starting time if (send(s, &start_time, sizeof(start_time), 0) == -1) { perror("client: send error"); exit(EXIT_FAILURE); } // send messages while(counter--) { r = rand(); if (send(s, &r, sizeof(r), 0) == -1) { perror("client: send error"); exit(EXIT_FAILURE); } sum += r; // printf("client: send: %d\n", r); } printf("Sender: sum: %lu\n", sum); close(s); exit(EXIT_SUCCESS); } else { // I am the parent process and I'm receiving int status; // for waiting child int s, s2, len; socklen_t t; struct sockaddr_un local, remote; int buff; double time_buff; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("server: socket error"); exit(1); } local.sun_family = AF_UNIX; strcpy(local.sun_path, SOCK_PATH); unlink(local.sun_path); len = strlen(local.sun_path) + sizeof(local.sun_family); if (bind(s, (struct sockaddr *)&local, len) == -1) { perror("server: bind error"); exit(EXIT_FAILURE); } if (listen(s, 8) == -1) { perror("server: listen error"); exit(EXIT_FAILURE); } int done, n; unsigned long sum = 0; unsigned long count = 0; printf("server: waiting for a connection...\n"); t = sizeof(remote); // accept and establish a connection if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) { perror("server: accept error"); exit(EXIT_FAILURE); } printf("server: connected.\n"); //TODO: receive the start time n = recv(s2, &time_buff, sizeof(time_buff), 0); if (n <= 0) { if (n < 0) perror("server: recv timer error"); } // reveicing messages done = 0; do { n = recv(s2, &buff, sizeof(buff), 0); // printf("server: received: %d\n", buff); if (n <= 0) { if (n < 0) perror("server: recv error"); done = 1; } else { sum += buff; count++; } } while (!done); double time_diff = get_cur_time() - time_buff; printf("Receiver: sum: %lu\n", sum); printf(">>>Sending starts at: %f s\n", time_buff); printf(">>>Received: %lu messages\n", count); printf(">>>The whole duration: %f s\n", time_diff); printf(">>>Throughput: %.5f msg/s\n", count/time_diff); //TODO: one thread receive, one thread calculate? //TODO: implement batch //TODO: calculate for each batch close(s2); // wait child wait(&status); exit(EXIT_SUCCESS); } return 0; }
C
#include "refcount.h" #include <stdlib.h> #include <string.h> libab_result libab_ref_new(libab_ref* ref, void* data, void (*free_func)(void* data)) { libab_result result = LIBAB_SUCCESS; ref->null = 0; ref->strong = 1; if ((ref->count = malloc(sizeof(*(ref->count))))) { ref->count->data = data; ref->count->strong = ref->count->weak = 1; ref->count->free_func = free_func; ref->count->visit_children = NULL; ref->count->prev = NULL; ref->count->next = NULL; } else { result = LIBAB_MALLOC; } return result; } void libab_ref_null(libab_ref* ref) { ref->null = 1; } void _libab_ref_changed(libab_ref* ref) { if (ref->count->strong == 0) { ref->count->strong--; if (ref->count->free_func) { ref->count->free_func(ref->count->data); } } if (ref->count->weak == 0) { if(ref->count->prev) ref->count->prev->next = ref->count->next; if(ref->count->next) ref->count->next->prev = ref->count->prev; free(ref->count); } } void libab_ref_weaken(libab_ref* ref) { if (!ref->null && ref->strong) { ref->count->strong--; ref->strong = 0; _libab_ref_changed(ref); } } void libab_ref_free(libab_ref* ref) { if (!ref->null) { ref->count->strong -= ref->strong; ref->count->weak--; _libab_ref_changed(ref); } } void libab_ref_copy(const libab_ref* ref, libab_ref* into) { if (!ref->null) { ref->count->strong++; ref->count->weak++; } memcpy(into, ref, sizeof(*ref)); } void libab_ref_swap(libab_ref* left, libab_ref* right) { libab_ref tmp; tmp = *left; *left = *right; *right = tmp; } void libab_ref_data_free(void* data) { free(data); } void* libab_ref_get(const libab_ref* ref) { void* to_return = NULL; if (!ref->null && ref->count->strong > 0) { to_return = ref->count->data; } return to_return; }
C
#include "internal.h" #include "log.h" #include <stdlib.h> #include <string.h> #define VERBOSE 1 UnshieldFileGroup* unshield_file_group_new(Header* header, uint32_t offset)/*{{{*/ { UnshieldFileGroup* self = NEW1(UnshieldFileGroup); uint8_t* p = unshield_header_get_buffer(header, offset); #if VERBOSE unshield_trace("File group descriptor offset: %08x", offset); #endif self->name = unshield_header_get_string(header, READ_UINT32(p)); p += 4; if (header->major_version <= 5) p += 0x48; else p += 0x12; self->first_file = READ_UINT32(p); p += 4; self->last_file = READ_UINT32(p); p += 4; #if VERBOSE unshield_trace("File group %08x first file = %i, last file = %i", offset, self->first_file, self->last_file); #endif return self; }/*}}}*/ void unshield_file_group_destroy(UnshieldFileGroup* self)/*{{{*/ { FREE(self); }/*}}}*/ int unshield_file_group_count(Unshield* unshield)/*{{{*/ { Header* header = unshield->header_list; return header->file_group_count; }/*}}}*/ UnshieldFileGroup* unshield_file_group_get(Unshield* unshield, int index) { Header* header = unshield->header_list; if (index >= 0 && index < header->file_group_count) return header->file_groups[index]; else return NULL; } UnshieldFileGroup* unshield_file_group_find(Unshield* unshield, const char* name) { Header* header = unshield->header_list; int i; for (i = 0; i < header->file_group_count; i++) { if (STREQ(header->file_groups[i]->name, name)) return header->file_groups[i]; } return NULL; } const char* unshield_file_group_name(Unshield* unshield, int index)/*{{{*/ { Header* header = unshield->header_list; if (index >= 0 && index < header->file_group_count) return header->file_groups[index]->name; else return NULL; }/*}}}*/
C
/* * (c) copyright 1995 by the Vrije Universiteit, Amsterdam, The Netherlands. * For full copyright and restrictions on use see the file COPYRIGHT in the * top level of the Panda distribution. */ #include "pan_sys.h" /* Provides a system interface */ #include "pan_global.h" #include "pan_time.h" #include "pan_error.h" #ifdef CMOST #ifndef NODE_TIMER #include <sys/time.h> #endif #elif AMOEBA #include "module/syscall.h" struct timezone { int dummy; }; static int gettimeofday(struct timeval *tp, struct timezone *tzp) { unsigned long msec = sys_milli(); tp->tv_sec = msec / 1000; tp->tv_usec = (msec % 1000) * 1000; return 0; } #endif #include <math.h> #include <limits.h> pan_time_p pan_time_infinity; pan_time_p pan_time_zero; /* Negative times: * invariant holds that time = tv_sec + MICRO * tv_usec., with 0 <= tv_usec < MICRO. * This differs from the conventional notation, for instance: * time = -0.25 is represented as { -1, 750000000 } * * The easiest way to negate a time value is by subtracting it from time_zero. */ #define MICRO 1000000 void pan_sys_time_start(void) { pan_time_infinity = pan_time_create(); pan_time_set(pan_time_infinity, LONG_MAX, MICRO); pan_time_zero = pan_time_create(); pan_time_set(pan_time_zero, 0, 0); #ifdef NODE_TIMER if (CMMD_node_timer_clear(PANDA_TIMER) == -1) { CMMD_error("%3d: pan_time_start: CMMD_node_timer_clear failed\n", CMMD_self_address()); } if (CMMD_node_timer_start(PANDA_TIMER) == -1) { CMMD_error("%3d: pan_time_start: CMMD_node_timer_start failed\n", CMMD_self_address()); } #endif } void pan_sys_time_end(void) { pan_time_clear(pan_time_infinity); pan_time_clear(pan_time_zero); } pan_time_p pan_time_create(void) { pan_time_p time; time = (pan_time_p)pan_malloc(sizeof(struct pan_time)); return time; } void pan_time_clear(pan_time_p time) { pan_free(time); } void pan_time_copy(pan_time_p to, pan_time_p from) { to->time = from->time; } void pan_time_get(pan_time_p now) { #ifdef NODE_TIMER double elapsed; if (CMMD_node_timer_stop(PANDA_TIMER) == -1) { CMMD_error("%3d: pan_time_get: CMMD_node_timer_stop failed\n", CMMD_self_address()); } elapsed = CMMD_node_timer_elapsed(PANDA_TIMER); if (CMMD_node_timer_start(PANDA_TIMER) == -1) { CMMD_error("%3d: pan_time_get: CMMD_node_timer_start failed\n", CMMD_self_address()); } now->time.tv_sec = (int)elapsed; now->time.tv_usec = (int)(MICRO * (elapsed - (int)elapsed)); #else if (gettimeofday(&now->time, 0) == -1){ pan_panic("gettimeofday"); } #endif } void pan_time_set(pan_time_p time, long sec, unsigned long nsec) { time->time.tv_sec = sec; time->time.tv_usec = nsec / 1000; } int pan_time_cmp(pan_time_p t1, pan_time_p t2) { if (t1->time.tv_sec == t2->time.tv_sec) { if (t1->time.tv_usec == t2->time.tv_usec) { return 0; } else if (t1->time.tv_usec > t2->time.tv_usec) { return 1; } else { return -1; } } else if (t1->time.tv_sec > t2->time.tv_sec) { return 1; } else { return -1; } } void pan_time_add(pan_time_p res, pan_time_p delta) { res->time.tv_usec += delta->time.tv_usec; /* max 2e9 = 2^31 */ res->time.tv_sec += delta->time.tv_sec; if (res->time.tv_usec >= MICRO){ res->time.tv_usec -= MICRO; res->time.tv_sec ++; } } void pan_time_sub(pan_time_p res, pan_time_p delta) { res->time.tv_usec -= delta->time.tv_usec; /* max 2e9 = 2^31 */ res->time.tv_sec -= delta->time.tv_sec; if (res->time.tv_usec < 0) { res->time.tv_usec += MICRO; --res->time.tv_sec; } } void pan_time_mul(pan_time_p res, int nr) { unsigned long int u; struct pan_time t1; u = labs(nr); pan_time_set(&t1, 0, 0); /* Accumulate result in t1 */ while (u != 0) { if ((u & 0x1) == 0x1) { pan_time_add(&t1, res); } u >>= 1; pan_time_add(res, res); } if (nr < 0) { pan_time_set(res, 0, 0); pan_time_sub(res, &t1); } else { *res = t1; } } void pan_time_div(pan_time_p res, int nr) { int is_neg; struct pan_time t1; is_neg = (nr < 0); if (is_neg) { nr = -nr; } if (pan_time_cmp(res, pan_time_zero) < 0) { /* % operator ill-defined for negs */ pan_time_set(&t1, 0, 0); pan_time_sub(&t1, res); is_neg = !is_neg; } else { t1 = *res; } res->time.tv_usec = (t1.time.tv_sec % nr) * (MICRO / nr) + t1.time.tv_usec / nr; res->time.tv_sec = t1.time.tv_sec / nr; if (res->time.tv_usec < 0) { assert(res->time.tv_sec == 0); --res->time.tv_sec; res->time.tv_usec = MICRO + res->time.tv_usec; } if (is_neg) { pan_time_set(&t1, 0, 0); pan_time_sub(&t1, res); *res = t1; } } void pan_time_mulf(pan_time_p res, double nr) { struct pan_time t_int; struct pan_time t_frac; double f; double f_sec; double f_usec; int is_neg; struct pan_time t1; is_neg = (nr < 0); if (is_neg) { nr = -nr; } if (pan_time_cmp(res, pan_time_zero) < 0) { /* modf is not OK for negs */ pan_time_set(&t1, 0, 0); pan_time_sub(&t1, res); is_neg = !is_neg; } else { t1 = *res; } f = t1.time.tv_sec * nr; f_usec = modf(f, &f_sec); t_int.time.tv_sec = (int) f_sec; t_int.time.tv_usec = (int) (MICRO * f_usec); f = (t1.time.tv_usec * nr) / MICRO; f_usec = modf(f, &f_sec); t_frac.time.tv_sec = (int) f_sec; t_frac.time.tv_usec = (int) (MICRO * f_usec); *res = t_int; pan_time_add(res, &t_frac); if (is_neg) { pan_time_set(&t1, 0, 0); pan_time_sub(&t1, res); *res = t1; } } void pan_time_d2t(pan_time_p t, double d) { t->time.tv_sec = (long int)d; t->time.tv_usec = (long int)((d - t->time.tv_sec) * MICRO); if (t->time.tv_usec < 0) { t->time.tv_sec -= 1; t->time.tv_usec += MICRO; } } double pan_time_t2d(pan_time_p t) { return t->time.tv_usec / ((double)MICRO) + t->time.tv_sec; } int pan_time_size(void) { return sizeof(struct pan_time); } void pan_time_marshall(pan_time_p p, void *buffer) { pan_time_p t_buffer = buffer; *t_buffer = *p; } void pan_time_unmarshall(pan_time_p p, void *buffer) { pan_time_p t_buffer = buffer; *p = *t_buffer; } void pan_time_t2fix(pan_time_p t, pan_time_fix_p f) { f->t_sec = t->time.tv_sec; f->t_nsec = t->time.tv_usec * 1000; } int pan_time_sub_fix_small(pan_time_p t1, pan_time_p t2, long int *d) { pan_time_t dt; dt = *t1; pan_time_sub(&dt, t2); if (dt.time.tv_sec == 0) { *d = dt.time.tv_usec * 1000; return 1; } return 0; }
C
/** * @file dedup.c * @brief Implements image deduplication feature. * */ #include "dedup.h" int do_name_and_content_dedup(struct pictdb_file* db_file, uint32_t index) { if (db_file == NULL || db_file->metadata[index].is_valid == EMPTY) { return ERR_INVALID_ARGUMENT; } struct pict_metadata* img_index = &db_file->metadata[index]; int found = 0; for (size_t i = 0; i < db_file->header.max_files; ++i) { // For all valid images other than the one at index if (i != index && db_file->metadata[i].is_valid == NON_EMPTY) { // Two distinct images have the same ID! if (strncmp(db_file->metadata[i].pict_id, img_index->pict_id, MAX_PIC_ID) == 0) { return ERR_DUPLICATE_ID; } else if (found == 0 && hashcmp(db_file->metadata[i].SHA, img_index->SHA) == 0) { // Two images with the same hash: deduplication for (size_t res = 0; res < NB_RES; ++res) { img_index->offset[res] = db_file->metadata[i].offset[res]; img_index->size[res] = db_file->metadata[i].size[res]; } found = 1; } } } // No duplicates found if (found == 0) { for (size_t res = 0; res < RES_ORIG; ++res) { img_index->offset[res] = 0; img_index->size[res] = 0; } img_index->offset[RES_ORIG] = 0; } return 0; }
C
// // Stack.h // Stack // // Created by lcf on 2019/12/13. // Copyright © 2019 lcf. All rights reserved. // #ifndef Stack_h #define Stack_h #include <stdio.h> #pragma mark - 栈的指针实现 struct Node; typedef struct Node *PtrToNode; typedef PtrToNode Stack; typedef int Elenment; // 是否为空栈 int IsEmpty(Stack S); // 创建一个栈 Stack CreateStack(void); // 释放栈 void DisposeStack(Stack S); // 清空栈 void MakeEmpty(Stack S); // 入栈 void Push(Elenment X, Stack S); // 出栈 void Pop(Stack S); // 得到栈顶元素 Elenment Top(Stack S); struct Node { Elenment element; PtrToNode Next; }; #pragma mark - 栈的数组实现 struct StackRecord; typedef struct StackRecord *StackK; typedef int ElenmentType; // 是否为空栈 int _IsEmpty(StackK S); // 栈是否满了 int _IsFull(StackK S); // 创建一个栈 StackK _CreateStack(int maxElements); // 销毁栈 void _DisposeStack(StackK S); // 清空栈 void _MakeEmpty(StackK S); // 入栈 void _Push(ElenmentType X,StackK S); // 栈顶元素 ElenmentType _Top(StackK S); // 出栈 void _Pop(StackK S); // 获取栈顶元素并出栈 ElenmentType _TopAndPop(StackK S); #define EmptyTOS (-1) #define MinStackSize (5) struct StackRecord { int Capacity; // 容量 int TopOfStack; ElenmentType *Array; }; #endif /* Stack_h */
C
#ifndef TOOL #define TOOL /**** misc ****/ void line(){ printf("-------------------------------------\n"); } void fline(FILE *f){ fprintf(f,"-------------------------------------\n"); } float mod0(float x, float d){ /* modulus mapped to [-d/2,d/2] */ while(x>+d/2) x-=d; while(x<-d/2) x+=d; return x; } float min0(float a, float b){ /* min of two num */ if(a<b) return a; return b; } float roundsf(float a, int n){ /* round to n sig fig */ return roundf(a*pow(10,n))/pow(10,n); } /********************************************************/ /**** handling ****/ float window(float *a, int n, int m, float func(float*,int)){ /* operate func on a[n] to a[m] */ return func(a+n,m-n+1); } /********************************************************/ /**** statistics ****/ float sum(float *a, int l){ float x=0; for(int i=0; i<l; i++) x+=a[i]; return x; } float mean(float *a, int l){ return sum(a,l)/l; } float wmean(float *a, int l){ /* linearly weighted mean */ float x=0; for(int i=0; i<l; i++) x+=(i+1)*a[i]; return x/(l*(l+1)/2); } float var(float *a, int l){ /* variance */ float x=0; for(int i=0; i<l; i++) x+=a[i]*a[i]; return x/l-pow(mean(a,l),2); } float std(float *a, int l){ /* standard deviation */ return sqrt(var(a,l)); } void normalise(float *a, int l){ /* convert to mean 0, variance 1 */ float m,s; m=mean(a,l); s=std(a,l); for(int i=0; i<l; i++) a[i]=(a[i]-m)/s; } float min(float *a, int l){ float x=a[0]; for(int i=1; i<l; i++) if(a[i]<x) x=a[i]; return x; } float max(float *a, int l){ float x=a[0]; for(int i=1; i<l; i++) if(a[i]>x) x=a[i]; return x; } void print_stat(float *a, int l){ /* summary statistics */ printf("min : %.4f\n" "max : %.4f\n" "mean : %.4f\n" "std : %.4f\n" ,min(a,l),max(a,l),mean(a,l),std(a,l)); } /********************************************************/ /**** tech indicators ****/ float SMA(float *a, int l){ /* simple moving average */ return mean(a,l); } float WMA(float *a, int l){ /* weighted moving average */ return wmean(a,l); } float RSI(float *a, int l){ /* relative strength index */ float x,R=0,D=0; for(int i=1; i<l; i++){ x=a[i]-a[i-1]; if(x>0) R+=x; // rise if(x<0) D-=x; // drop } if(D==0) return 100; return 100*(1-1/(1+R/D)); } /********************************************************/ /**** sampling ****/ float uniform(float a, float b){ float u=(float)rand()/RAND_MAX; return a+(b-a)*u; } float normal(float a, float b){ float u1=uniform(0,1),u2=uniform(0,1), z=sqrt(-2*log(u1))*cos(2*M_PI*u2); return a+b*z; } int poisson(float a){ int k=0; float u,L=exp(-a),p=1; while(p>L){ u=uniform(0,1); p*=u; k++; } return k-1; } #endif
C
#define _CRT_SECURE_NO_WARNINGS 1 //#include<stdio.h> //int main() //{ // printf("%d\n", sizeof(int)); //4 // printf("%d\n", sizeof(char)); //1 // printf("%d\n", sizeof(short)); //2 // printf("%d\n", sizeof(long)); //4/8 // printf("%d\n", sizeof(long long)); //8 // printf("%d\n", sizeof(float)); //4 // printf("%d\n", sizeof(double)); //8 // return 0; //} ////͵ĴСλֽ ////еĵλ ////bit(λ) byte(ֽ) kbyte(kb) mb gb tb pb ////ǰλ֮Ļ㵥λ8ĵλ֮1024 //#include<stdio.h> //int main() //{ // int num = 10; // printf("%d", num); // return 0; // //numֵǿӡ // //ΪnumǾֲprintfҲnumУǿӡġ //} //#include<stdio.h> //int main() //{ // { // int num = 10; // } // printf("%d", num); // return 0; // //ʱnumвprintf䡣 //} //enum Sex //{ // MALE, // FEMALE, // SECRET //}; //#include<stdio.h> //int main() //{ // printf("c:\\test\\test.c\n"); // return 0; //} ////ĽΪ ////c:\test\test.c //#include<stdio.h> //#include<string.h> //int main() //{ // printf("%d\n", 10); // printf("%d\n", strlen("abc")); // printf("%d\n", strlen("c:\test\47\test.c"); // return 0; // //УprintfΪ13Ҫ\47 // //еıʻڿתַ // //\dddҲΪתַdddʾ1-3˽Ƶ֣ͳһĿһַ˵Ϊ1. // //\xddd dddʾ316 //} //#include<stdio.h> //int main() //{ // int a1 = 5 / 2; // float a2 = 5 / 2; // float a3 = 5.0 / 2; // printf("%d\n", a1); // printf("%f\n", a2); // printf("%f\n", a3); // return 0; //} ////ڳ洢ʲôûйϵ ////ҪǿIJʲô͵ģһǸ͵ģõĽͻǸ͵Ľ //#include<stdio.h> //int main() //{ // //int a = 5/2; // //int a = 5/2.0; // //printf("%d\n", a); // //int a = 5%2; // //printf("%d\n", a); // int a = 15; // int b = a << 1; // //a = a<<1; // printf("%d\n", a); // printf("%d\n", b); // //<< λ-ƶǶλ // //ԭ-- // //00000000000000000000000000001111-ԭ--ͬ // //00000000000000000000000000011110 // // // //-1 // //10000000000000000000000000000001-ԭ // //11111111111111111111111111111110- // //11111111111111111111111111111111- // system("pause"); // return 0; //} ////ϸǿʼDZ //#include<stdio.h> //int main() //{ // int a = 10; // int b = 20; // int max = 0; // max = (a > b) ? a : b; // printf("%d", max); // return 0; //} //#include<stdio.h> //void test() //{ // static int n = 1; //nΪֲ // n++; // printf("%d ", n); //} //int main() //{ // int i = 0; // for (i = 0; i < 10; i++) // { // test(); // } // return 0; //} ////ӡĽ2-11staticα˾Ͳˡ //#include<stdio.h> ////Զ //struct Stu //{ // char name[20]; //һַ // int age; // float score; //}; //int main() //{ // struct Stu s = { "",20,60.0f }; // struct Stu* ps = &s; //ṹָ // printf("%s %d %f", ps->name, ps->age, ps->score); // return 0; //} #include<stdio.h> int main() { int count = 0; int j = 0; for (int i = 100; i <= 200; ++i) { for (j = 2; j < i; j++) { if (i % j == 0) break; } if (j == i) { count++; printf("%d ", i); } } printf("\n"); printf("%d", count); return 0; } #include<stdio.h> #include<math.h> int main() { int count = 0; int j = 0; for (int i = 100; i <= 200; ++i) { for (j = 2; j <= sqrt(i); j++) { if (i % j == 0) break; } if (j > sqrt(i)) { count++; printf("%d ", i); } } printf("\n"); printf("%d", count); return 0; } #include<stdio.h> int main() { int a = 0; int b = 0; int c = 1; (void)scanf("%d %d", &a, &b); while (c = a % b) { a = b; b = c; } printf("%d", b); return 0; } #include<stdio.h> void Print(int n) { if (n > 9) Print(n / 10); printf("%d ", n % 10); } int main() { int n = 0; (void)scanf("%d", &n); Print(n); return 0; } #include<stdio.h> #include<string.h> int main() { printf("%d\n", 10); printf("%d\n", strlen("abc")); printf("%d\n", strlen("c:\test\47\test.c")); return 0; //УprintfΪ13Ҫ\47 //еıʻڿתַ //\dddҲΪתַdddʾ1-3˽Ƶ֣ͳһĿһַ˵Ϊ1. //\xddd dddʾ316 } //ƵĻϴӡһ #include<stdio.h> int main() { printf("%c\n", '\''); printf("%s\n", "\""); return 0; } //дһӷĺ #include<stdio.h> int Add(int x, int y) { int z = x + y; return z; } int main() { int a = 0; int b = 0; int c = 0; (void)scanf("%d %d", &a, &b); c = Add(a, b); printf("%d\n", c); return 0; } #include<stdio.h> //Զ struct Stu { char name[20]; //һַ int age; float score; }; int main() { struct Stu s = { "",20,60.0f }; struct Stu* ps = &s; //ṹָ printf("%s %d %f", (*ps).name, (*ps).age, (*ps).score); return 0; } #include<stdio.h> int main() { int day = 0; scanf("%d", &day); switch (day) { case 1: case 2: case 3: case 4: case 5: printf("weekday\n"); break; case 6: case 7: printf("weekend\n"); break; default: printf("ѡ\n"); break; } } #include<stdio.h> int main() { int i = 1; while (i <= 10) { i++; if (i == 5) continue; printf("%d ", i); } return 0; } //ӡΪ23457891011 //continueãcontinueֹεѭcontinue֮䲻ִС //EOFΪend of file #include<stdio.h> int main() { int ch = 0; while ((ch = getchar()) != EOF) putchar(ch); return 0; } //ctrl+zͣ //˷ھ #include<stdio.h> int main() { for (int a = 1; a <= 9; ++a) { for (int b = 1; b <= a; b++) { printf("%d*%d=%2d ", a, b, a * b); } printf("\n"); } return 0; } //ʮеֵ #include<stdio.h> int main() { int arr[10] = { 12,34,675,32,75,24,86,23,88,16 }; int max = arr[0]; int sz = sizeof(arr) / sizeof(arr[0]); int i = 0; for (i = 1; i < sz; i++) { if (arr[i] > max) { max = arr[i]; } } printf("%d", max); return 0; } #include<stdio.h> int main() { int i = 0; int j = 0; for (; i < 10; i++) { for (; j < 10; j++) { printf("hehe\n"); } } return 0; } //δôӡֻ10hehe //10heheǴi=0-- i=9һӡ //i=0ʱjһֱ9ӡ10hehe֮jͲ //һֻӡ10hehe #include<stdio.h> int my_strlen(const char* str) { if (*str == '\0') return 0; else return 1 + my_strlen(str + 1); } int main() { char arr[] = "abc"; int len = my_strlen(arr); printf("%d", len); return 0; } #include<stdio.h> int my_strlen(const char* str) { int count = 0; while (*str != '\0') { str++; count++; } return count; } int main() { char arr[] = "abc"; int len = my_strlen(arr); printf("%d", len); return 0; } #include<stdio.h> int my_strlen( char* str) { char* ret = str; while (*str != '\0') { str ++ ; } return str - ret; } int main() { char arr[] = "abc"; int len = my_strlen(arr); printf("%d", len); return 0; }
C
/******************************************************************************* * * File: kernel_list.h * * Author: Alexy Torres Aurora Dugo * * Date: 17/12/2017 * * Version: 1.5 * * Kernel priority lists used to manage data. ******************************************************************************/ #ifndef __KERNEL_LIST_H_ #define __KERNEL_LIST_H_ #include "../lib/stddef.h" /* OS_RETURN_E */ #include "../lib/stdint.h" /* Generic int types */ /******************************************************************************* * CONSTANTS ******************************************************************************/ /******************************************************************************* * STRUCTURES ******************************************************************************/ /* List node structure */ typedef struct kernel_list_node { struct kernel_list_node* next; /* Next node of the list */ struct kernel_list_node* prev; /* Previous node of the list */ uint16_t priority; /* Priority of the element */ uint16_t enlisted; /* Is the node in a list */ void* data; /* Data contained by the node */ } kernel_list_node_t; /* List structure */ typedef struct kernel_list { struct kernel_list_node* head; /* Head of the list */ struct kernel_list_node* tail; /* Tail of the list */ uint32_t size; /* List size */ } kernel_list_t; /******************************************************************************* * FUNCTIONS ******************************************************************************/ /* Create a node ready to be inserted in a list. The data can be modified later * by accessing the data field of the node structure. * * WARNING A node should be only used in ONE list at most !!! * * @param data The pointer to the data to carry in the node. * @param error A pointer to the variable that contains the function success * state. May be NULL. * @returns The node pointer is returned. */ kernel_list_node_t* kernel_list_create_node(void* data, OS_RETURN_E *error); /* Delete a node from the memory. The node should not be used in any list. If it * is the case, the function will return an error. * * @param node The node pointer of pointer to destroy. * @returns The function returns OS_NO_ERR on success, see system returns type * for further error description. */ OS_RETURN_E kernel_list_delete_node(kernel_list_node_t** node); /* Create an empty list ready to be used. * * @param error A pointer to the variable that contains the function success * state. May be NULL. * @returns The list pointer is returned. */ kernel_list_t* kernel_list_create_list(OS_RETURN_E *error); /* Delete a list from the memory.If the list is not empty, an error is returned. * * @param list The list pointer of pointer to destroy. * @returns The function returns OS_NO_ERR on success, see system returns type * for further error description. */ OS_RETURN_E kernel_list_delete_list(kernel_list_t** list); /* Enlist a node in the list given as parameter. The data will be placed * in the list accordinlgy to the priority defined. * * @param node A now node to add in the list. * @param list The list to manage. * @param priority The priority of the element to place in the list. * @returns The function returns OS_NO_ERR on success, see system returns type * for further error description. */ OS_RETURN_E kernel_list_enlist_data(kernel_list_node_t* node, kernel_list_t* list, const uint16_t priority); /* Remove a node from the list given as parameter. The retreived node that is * returned is the one with the highest priority parameter. * * @param list The list to manage. * @param error A pointer to the variable that contains the function success * state. May be NULL. * @returns The data poitner with the highest priority parameter is returned. */ kernel_list_node_t* kernel_list_delist_data(kernel_list_t* list, OS_RETURN_E* error); /* Find a node containing the data given as paramter. An error is set if not any * node is found. * * @param list The list to manage. * @param data The data contained by the node to find. * @param error A pointer to the variable that contains the function success * state. May be NULL. * @returns The function returns a pointer to the node if found, NULL otherwise. */ kernel_list_node_t* kernel_list_find_node(kernel_list_t* list, void* data, OS_RETURN_E *error); /* Remove a node from a list given as parameter. If the node is not found, * nothing is done and an error is returned. * * @param list The list containing the node. * @param node The node to remove. * @returns The function returns OS_NO_ERR on success, see system returns type * for further error description. */ OS_RETURN_E kernel_list_remove_node_from(kernel_list_t* list, kernel_list_node_t* node); #endif /* __KERNEL_LIST_H_ */
C
/* * * */ #include "../../include/apue.h" #include "../../include/pr_wait.h" #include "sys/wait.h" int main(int argc, char *argv[]) { pid_t pid; int status; printf("now begainning fork\n"); pid = fork(); switch (pid) { case -1://error err_sys("fork error\n"); break; case 0://child sleep(2); break; default://parent; break; } if (pid > 0) { printf("begainning wait\n"); if (wait(&status) != pid) { err_sys("wait error\n"); } pr_wait(status); } exit(EXIT_SUCCESS); }
C
#include "softiic.h" #include "gpio.h" #include "tim.h" #define IIC_SDA(val) {if(val) HAL_GPIO_WritePin(IIC_SDA_GPIO_Port,IIC_SDA_Pin,GPIO_PIN_SET);\ else HAL_GPIO_WritePin(IIC_SDA_GPIO_Port,IIC_SDA_Pin,GPIO_PIN_RESET);} #define IIC_SCL(val) {if(val) HAL_GPIO_WritePin(IIC_SCL_GPIO_Port,IIC_SCL_Pin,GPIO_PIN_SET);\ else HAL_GPIO_WritePin(IIC_SCL_GPIO_Port,IIC_SCL_Pin,GPIO_PIN_RESET);} #define SDA_IN() {GPIOB->CRH&=0XFFFFFF0F;GPIOB->CRH|=(uint32_t)8<<4;} #define SDA_OUT() {GPIOB->CRH&=0XFFFFFF0F;GPIOB->CRH|=(uint32_t)3<<4;} void IIC_Delay(uint16_t times) { for(uint16_t _n=0;_n<times*5;_n++); } void SoftIIC_Port_Init(void) { GPIO_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pins : SDA */ GPIO_InitStruct.Pin = IIC_SDA_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(IIC_SDA_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : SCLK */ GPIO_InitStruct.Pin = IIC_SCL_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(IIC_SCL_GPIO_Port, &GPIO_InitStruct); } void IIC_Start(void) { SDA_OUT(); IIC_SDA(1); IIC_SCL(1); IIC_Delay(1); IIC_SDA(0);//START:when CLK is high,DATA change form high to low IIC_Delay(1); IIC_SCL(0); } void IIC_Stop(void) { SDA_OUT(); IIC_SCL(0); IIC_SDA(0);//STOP:when CLK is high DATA change form low to high IIC_Delay(1); IIC_SCL(1); IIC_SDA(1); IIC_Delay(1); } uint8_t IIC_Wait_Ack(void) { uint8_t ucErrTime=0; SDA_IN(); IIC_SDA(1);IIC_Delay(1); IIC_SCL(1);IIC_Delay(1); while(HAL_GPIO_ReadPin(IIC_SDA_GPIO_Port,IIC_SDA_Pin)) { ucErrTime++; if(ucErrTime>250) { IIC_Stop(); return 1; } } IIC_SCL(0); return 0; } // void IIC_Ack(void) { IIC_SCL(0); SDA_OUT(); IIC_SDA(0); IIC_Delay(1); IIC_SCL(1); IIC_Delay(1); IIC_SCL(0); } void IIC_NAck(void) { IIC_SCL(0); SDA_OUT(); IIC_SDA(1); IIC_Delay(1); IIC_SCL(1); IIC_Delay(1); IIC_SCL(0); } void IIC_Send_Byte(uint8_t txd) { uint8_t t; SDA_OUT(); IIC_SCL(0); for(t=0;t<8;t++) { if((txd&0x80)>>7) { IIC_SDA(1); } else { IIC_SDA(0); } txd<<=1; IIC_Delay(1); IIC_SCL(1); IIC_Delay(1); IIC_SCL(0); IIC_Delay(1); } } uint8_t IIC_Read_Byte(unsigned char ack) { unsigned char i,receive=0; SDA_IN(); for(i=0;i<8;i++ ) { IIC_SCL(0); IIC_Delay(1); IIC_SCL(1); receive<<=1; if(HAL_GPIO_ReadPin(IIC_SDA_GPIO_Port,IIC_SDA_Pin)) receive++; IIC_Delay(1); } if (!ack) IIC_NAck(); else IIC_Ack(); return receive; }
C
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <fcntl.h> #include <string.h> void child_handler(); void child_execute(); void parent_execute(); int count = 0; /* FILE *fp; */ int main() { int num_input,num_real,newpid; struct sigaction ssr; sigset_t blocked; ssr.sa_sigaction = child_handler; ssr.sa_flags = SA_SIGINFO; /* ssr.sa_flags = SA_NODEFER; */ sigemptyset(&blocked); sigaddset(&blocked,SIGCHLD); ssr.sa_mask = blocked; sigaction(SIGCHLD,&ssr,NULL); scanf("%9d",&num_input); num_real = 0; printf("%d\n",num_input); for(int i = 0;i < num_input;i++) { if((newpid = fork()) == -1) perror("fork"); else if(newpid == 0) child_execute(); else num_real++; } sleep(1); printf("%d\n",num_real); while(count != num_real) parent_execute(); printf("all done.\n"); } void child_execute() { printf("child : I am the child %d,waiting for 5 secs\n",getpid()); sleep(5); exit(17); } void child_handler() { waitpid(-1,NULL,WNOHANG); count += 1; } void parent_execute() { sleep(1); printf("parent : already handled %d.\n",count); }
C
/************************************************************************* > File Name: file_server.c > Author: > Mail: > Created Time: 2017年06月15日 星期四 10时20分35秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<arpa/inet.h> #include<sys/socket.h> #define BUF_SIZE 30 void error_handling(char *message); int main(int argc, char *argv[]) { int serv_sd, clnt_sd; FILE *fp; char buf[BUF_SIZE]; int read_cnt; struct sockaddr_in serv_adr, clnt_adr; socklen_t clnt_adr_sz; if(argc!=2){ printf("Usage: %s <port>\n",argv[0]); exit(1); } fp=fopen("op_client.c","rb"); serv_sd=socket(PF_INET,SOCK_STREAM,0); memset(&serv_adr,0,sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); bind(serv_sd,(struct sockaddr*)&serv_adr, sizeof(serv_adr)); listen(serv_sd,5); clnt_adr_sz=sizeof(clnt_adr); clnt_sd=accept(serv_sd,(struct sockaddr*)&clnt_adr, &clnt_adr_sz); while(1) { read_cnt=fread((void *)buf,1,BUF_SIZE,fp); if(read_cnt<BUF_SIZE) { write(clnt_sd,buf,read_cnt); break; } write(clnt_sd,buf,BUF_SIZE); } shutdown(clnt_sd,SHUT_WR); read(clnt_sd,buf,BUF_SIZE); printf("Message from client: %s \n",buf); fclose(fp); close(clnt_sd); close(serv_sd); return 0; } void error_handling(char *message) { fputs(message,stderr); fputc('\n',stderr); exit(1); }
C
//题目:从键盘输入一个字符串,将小写字母全部转换成大写字母, // 然后输出到一个磁盘文件“test”中保存。输入的字符串以!结束。 //1.程序分析: //2.程序源代码: #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; char str[100],filename[10]; int i=0; if((fp=fopen("test","w"))==NULL){ printf("cannot open the file\n"); exit(0); } printf("please input a string:\n"); gets(str); while(str[i]!='!'){ if(str[i]>='a'&&str[i]<='z') str[i]=str[i]-32; fputc(str[i],fp); i++; } fclose(fp); fp=fopen("test","r"); fgets(str,strlen(str)+1,fp); printf("%s\n",str); fclose(fp); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char * argv[]){ int k = atoi(argv[1]); char line[100]; fgets(line, 100, stdin); int i; for(i = 0; i < strlen(line); i++){ if(line[i] > 64 && line[i] < 91){ printf("%c", (((line[i]-64)+k)%26) + 64); }else if(line[i] > 96 && line[i] < 123){ printf("%c", (((line[i]-96)+k)%26) + 96); }else{ printf("%c", line[i]); } } }
C
//Definitions typedef unsigned char uint8 ; //PORT Driver //Type Definitions enum Port_PinDirectionType { PORT_PIN_IN = 0 , PORT_PIN_OUT = 1 }; //Function Definitions void Port_Init( uint8 port_index ) ; void Port_SetPinDirection( uint8 port_index ) ; void Port_SetPinPullUp ( uint8 port_index ) ; void Port_SetPinPullDown ( uint8 port_index ) ; //DIO Driver enum Dio_LevelType { STD_LOW = 0 , STD_HIGH = 1 }; //Function Definitions uint8 DIO_ReadPort ( uint8 port_index ,uint8 pins_mask ) ; uint8 DIO_WritePort ( uint8 port_index ,uint8 pins_mask , enum Dio_LevelType pins_level ) ; uint8 DIO_ReadPort ( uint8 port_index ,uint8 pins_mask ) ; uint8 DIO_FlipPort ( uint8 port_index ,uint8 pins_mask ) ;
C
/* * 得到: * 1. int型取值范围为:-2^31 —— 2^31-1; * 2. 应该注意到边界问题,没有考虑好的话,后期容易造成大的影响; * 3. int to char (n%10 + '0'); * * */ #include <stdio.h> #include <string.h> #include <stdlib.h> // Reverse change start to end void reverse(char s[]) { int c, i, j; for (i = 0, j = strlen(s)-1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } // Itoa 获取int每位上的数存进数组,组成字符串 // @1. 在ASCII中 数字0-9的字符为48-57。 // 所以在n%10 + ‘0’可以将整形变为字符型数字n。 // @2. 判断是否为负数 // @3. 在n = 最大负值时,-n越界了,会报错。 void mitoa(int n, char s[]) { int i, sign; if ((sign = n) < 0) n = -n; // @3 i = 0; do { s[i++] = n % 10 + '0'; // @1 } while ((n /= 10) > 0); if (sign < 0) s[i++] = '-'; // @2 s[i] = '\0'; reverse(s); } void nitoa(int n, char s[]) { int i, sign; sign = n; i = 0; do { s[i++] = abs(n%10) + '0'; // Fix @3 } while((n /= 10) != 0); if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } int main(void) { int n = -2147483648; char s[30]; nitoa(n, s); printf("s = %s\n", s); return 0; }
C
/*--------------------------------------------------------------------- by Kang Woo Jung: 2018.11.28 -----------------------------------------------------------------------*/ #include "bsp.h" #include "clk.h" RTC_DateTypeDef clk_sDate; RTC_TimeTypeDef clk_sTime; const char *clkDAY[DAY_SIZE] = {" ","MON","TUE","WED","THU","FRI","SAT","SUN"}; void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc) { //kprintf(&kpro1,(cu8 *)"RTC Event! ^,.^\n"); } void clk_set_date(uint16_t year, uint16_t month, uint16_t date, day_t day) { clk_sDate.Year = year; clk_sDate.Month = month; clk_sDate.Date = date; clk_sDate.WeekDay = day; HAL_RTC_SetDate(&hrtc, &clk_sDate, RTC_FORMAT_BIN); } void clk_set_time(uint16_t hour, uint16_t min, uint16_t sec) { clk_sTime.Hours = hour; clk_sTime.Minutes = min; clk_sTime.Seconds = sec; clk_sTime.TimeFormat = RTC_HOURFORMAT_24; clk_sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; clk_sTime.StoreOperation = RTC_STOREOPERATION_RESET; HAL_RTC_SetTime(&hrtc, &clk_sTime, RTC_FORMAT_BIN); } void clk_get(clk_t *clk) { HAL_RTC_GetTime(&hrtc, &clk_sTime, RTC_FORMAT_BIN); HAL_RTC_GetDate(&hrtc, &clk_sDate, RTC_FORMAT_BIN); clk->year = clk_sDate.Year; clk->month = clk_sDate.Month; clk->date = clk_sDate.Date; clk->day = clk_sDate.WeekDay; clk->hour = clk_sTime.Hours; clk->min = clk_sTime.Minutes; clk->sec = clk_sTime.Seconds; }
C
/* ID: kiner.s1 LANG: C TASK: milk2 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> typedef struct node { int s,f; }FEED; int comp(const void *a, const void *b) { return ((FEED*)a)->s > ((FEED*)b)->s; } int max(int i, int j) { return i>j?i:j; } int main() { FILE *p1,*p2; int n,i,j,maxfedsofar,maxnotfedsofar=0,start,finish; FEED *ff; p1=fopen("milk2.in","r"); p2=fopen("milk2.out","w"); fscanf(p1,"%d",&n); ff=(FEED *)malloc(n*sizeof(FEED)); for(i=0;i<n;i++) { fscanf(p1,"%d %d",&ff[i].s,&ff[i].f); } qsort(ff,n,sizeof(FEED),comp); start=ff[0].s; finish=ff[0].f; maxfedsofar=ff[0].f-ff[0].s; for(i=1;i<n;i++) { if(ff[i].s <= finish) { if(ff[i].s <= start) start=ff[i].s; if(ff[i].f >= finish) finish=ff[i].f; } else { maxfedsofar=max(maxfedsofar,finish-start); maxnotfedsofar=max(maxnotfedsofar,ff[i].s-finish); start=ff[i].s; finish=ff[i].f; } } fprintf(p2,"%d %d\n",maxfedsofar,maxnotfedsofar); return 0; }
C
#include <stdio.h> #include "vc.h" #pragma region CriarAlterarGuardarImagem //int main(void) //{ // IVC *image; // int i; // // image = vc_read_image("../Images/FLIR/flir-01.pgm"); // if (image == NULL) // { // printf("Erro!!! imagem nao encontrada!!!\n"); // getchar(); // return 0; // } // // for (i = 0; i < image->bytesperline * image->height; i += image->channels) // { // image->data[i] = 255 - image->data[i]; // } // // vc_write_image("../Results/imagem1.pgm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair..."); // // getchar(); // return 0; //} #pragma endregion #pragma region CriarImagemBinaria //int main(void) //{ // IVC *image; // int x, y; // long int pos; // // image = vc_image_new(280, 280, 1, 1); // if (image == NULL) // { // printf("out of memory!!!\n"); // getchar(); // return 0; // } // // for (x = 0; x < image->width; x++) // { // for (y = 0; y < image->height; y++) // { // pos = y * image->bytesperline + x * image->channels; // // if ((x <= image->width / 2) && (y <= image->height / 2)) // image->data[pos] = 1; // else if ((x > image->width / 2) && (y > image->height / 2)) // image->data[pos] = 1; // else // image->data[pos] = 0; // } // } // vc_write_image("../Results/binaria.pbm", image); // vc_image_free(image); // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region InverterBinaria //int main(void) //{ // IVC *image; // int i; // // image = vc_read_image("../Results/binaria.pbm"); // if (image == NULL) // { // printf("File not found"); // getchar(); // return 0; // } // else // { // for (i = 0; i < image->bytesperline * image->height; i += image->channels) // { // if (image->data[i] == 1) // image->data[i] = 0; // else // image->data[i] = 1; // } // // vc_write_image("../Results/binairaInvertida.pbm", image); // vc_image_free(image); // // printf("Press any key to continue\n"); // getchar(); // } //} #pragma endregion #pragma region GradienteEsquerdaDireita //int main(void) //{ // IVC *image; // long int pos; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("out of memory"); // getchar(); // return 0; // } // else // { // GradienteED(image); // vc_write_image("../Results/gradienteED.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region GradienteCimaBaixo //int main(void) //{ // IVC *image; // long int pos; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("out of memory"); // getchar(); // return 0; // } // else // { // GradienteCB(image); // vc_write_image("../Results/gradienteCB.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region GradienteBaixoCima //int main(void) //{ // IVC *image; // long int pos; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("out of memory"); // getchar(); // return 0; // } // else // { // GradienteBC(image); // vc_write_image("../Results/gradienteBC.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region GradienteDireitaEsquerda //int main(void) //{ // IVC *image; // long int pos; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("out of memory"); // getchar(); // return 0; // } // else // { // GradienteDE(image); // vc_write_image("../Results/gradienteDE.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region DiagonalCimaBaixo //int main(void) //{ // IVC *image; // long int pos; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("Out of memory!!!"); // getchar(); // return 0; // } // else // { // DiagonalCB(image); // vc_write_image("../Results/gradienteDiagonalCB.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region DiagonalBaixoCima //int main(void) //{ // IVC *image; // // image = vc_image_new(256, 256, 1, 255); // if (image == NULL) // { // printf("out of memory"); // getchar(); // return 0; // } // else // { // DiagonalBC(image); // // vc_write_image("../Results/gradienteDiagonalBC.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region NegativeGray //int main(void) //{ // IVC *image = vc_read_image("../Images/Other/gray-01.pgm"); // // if (image == NULL || image->channels != 1 || image->height <= 0 || image->width <= 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // // vc_gray_negative(image); // vc_write_image("../Results/grayNegative.pbm", image); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region NegativeRGB //int main(void) //{ // IVC *image = vc_read_image("../Images/Additional/girl.ppm"); // // if (image == NULL || image->channels != 3 || image->height <= 0 || image->width <= 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // // vc_rgb_negative(image); // vc_write_image("../Results/rbgNegative(girl).pbm", image); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region RED_TO_GRAY //int main(void) //{ // IVC *image = vc_read_image("../Images/Classic/baboon.ppm"); // // if (image == NULL || image->channels != 3 || image->height <= 0 || image->width <= 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // // vc_rgb_get_red_gray(image); // vc_write_image("../Results/red_to_gray.pbm", image); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region Green_TO_GRAY //int main(void) //{ // IVC *image = vc_read_image("../Images/Classic/baboon.ppm"); // // if (image == NULL || image->channels != 3 || image->height <= 0 || image->width <= 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // // vc_rgb_get_green_gray(image); // vc_write_image("../Results/green_to_gray.pbm", image); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region Blue_TO_GRAY //int main(void) //{ // IVC *image = vc_read_image("../Images/Classic/baboon.ppm"); // // if (image == NULL || image->channels != 3 || image->height <= 0 || image->width <= 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // // vc_rgb_get_blue_gray(image); // vc_write_image("../Results/blue_to_gray.pbm", image); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; //} #pragma endregion #pragma region RGB_to_Gray //int main(void) //{ // IVC *image = vc_read_image("../Images/Classic/baboon.ppm"); // IVC *result = vc_image_new(image->width, image->height, 1, 255); // // if (vc_rgb_to_gray(image, result) == 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_gray.pbm", result); // // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region RGB_to_HSV //int main(void) //{ // IVC *image = vc_read_image("../HSV_ImagensTeste/HSVTestImage01.ppm"); // // IVC *image = vc_read_image("../HSV_ImagensTeste/HSVTestImage02.ppm"); // // if (vc_rgb_to_hsv(image) == 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // else // { // // vc_write_image("../Results/rgb_to_hsv1.pbm", image); // vc_write_image("../Results/rgb_to_hsv1.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region HSV_Segmentation // int main(void) //{ // IVC *image = vc_read_image("../Images/Additional/fruits.ppm"); // // if (vc_hsv_segmentation(image, 200, 360, 75, 100, 25, 75) == 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // else // { // // vc_write_image("../Results/rgb_to_hsv1.pbm", image); // vc_write_image("../Results/segmentation1.pbm", image); // vc_image_free(image); // // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } //} #pragma endregion #pragma region Scale_Gray_to_RGB // int main(void) // { // IVC *image = vc_read_image("../Images/Special/testpat.pgm"); // IVC *result = vc_image_new(image->width, image->height, 3, 255); // if (vc_scale_gray_to_rgb(image, result) == 0) // { // printf("ERRO!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/GrayToRGB.pbm", result); // vc_image_free(image); // vc_image_free(result); // printf("Carregue numa tecla para sair...\n"); // getchar(); // return 0; // } // } #pragma endregion #pragma region Threshold(Gray_to_Binary) // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/grayscale_chart.pgm"); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // // IVC *image = vc_read_image("../ImagesTestSegmentation/cells.pgm"); // if (vc_gray_to_binary(image, result, 100) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_binary(threshold).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Global_Mean(Gray_to_Binary) // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/grayscale_chart.pgm"); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_global_mean(image, result) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_binary(global_mean).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region MidPoint(Gray_to_Binary) // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/grayscale_chart.pgm"); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_midpoint(image, result, 25) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_binary(midPoint).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Bernsen(Gray_to_Binary) // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/grayscale_chart.pgm"); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_bernsen(image, result, 25, 100) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_binary(bernsen).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Bernsen(Gray_to_Binary) // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/grayscale_chart.pgm"); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_niBlack(image, result, 15, -0.2) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/rgb_to_binary(niblack).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Dilate // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/coins.pgm"); // IVC *threshold = vc_image_new(image->width, image->height, 1, 1); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_global_man(image, threshold) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // if (vc_binary_dilate1(threshold, result, 3) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/binary(dilate).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Erode // int main(void) // { // IVC *image = vc_read_image("../ImagesTestSegmentation/coins.pgm"); // IVC *threshold = vc_image_new(image->width, image->height, 1, 1); // IVC *result = vc_image_new(image->width, image->height, 1, 1); // if (vc_gray_to_binary_global_mean(image, threshold) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // if (vc_binary_erode(threshold, result, 3) == 0) // { // puts("Erro!!!"); // getchar(); // return 0; // } // else // { // vc_write_image("../Results/binary(erode).pbm", result); // vc_image_free(image); // puts("Carregue numa tecla para sair..."); // getchar(); // return 0; // } // } #pragma endregion #pragma region Labelling int main(void) { IVC *image = vc_read_image("../ImagesTestSegmentation/coins.pgm"); IVC *dst = vc_image_new(image->width, image->height, 1, 255); IVC *threshold = vc_image_new(image->width, image->height, 1, 255); IVC *result = vc_image_new(image->width, image->height, 1, 255); vc_gray_to_binary_global_mean(image, threshold); int nlabel = 0; OVC *blobs = vc_binary_blob_labelling(threshold, dst, &nlabel); if (vc_binary_blob_info(image, blobs, nlabel) == 0) { printf("Erro!"); getchar(); return 0; } vc_write_image("../Results/labelling.pgm", dst); printf("press any key to exit.....\n"); getchar(); return 0; } #pragma endregion
C
#include<stdio.h> int main(){ int n, max, number, i; printf("Enter total numbers: "); scanf("%d", &n); printf("\n"); if(n>0){ scanf("%d",&number); max = number; for(int i=1; i< n ; i++){ scanf("%d",&number); if(max < number) max = number; } printf("%d", max); } }
C
#include<stdio.h> int main(){ int n,k,i,j,a[20],dig ; scanf("%d",&n) ; char *one_dig[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; char *two_dig[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; char *tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; char *tens_power[] = {"hundred", "thousand"}; k = n ; i=1;dig=0; while(k){ a[i] = k%10 ; k/=10;i++; dig++; } if(dig==1){ printf("%s",one_dig[a[1]]) ; } else if(dig==2){ if(a[2]==1){printf("%s",two_dig[a[1]+1]);} else{printf("%s ",tens_multiple[a[2]]); printf("%s ",one_dig[a[1]] ); } } else if(dig==3){ printf("%s hundred ",one_dig[a[3]]) ; if(a[2]==0){ printf("%s",one_dig[a[1]]) ;} else{ if(a[2]==1){printf("%s",two_dig[k%10]);} else{printf("%s ",tens_multiple[a[2]]); printf("%s ",one_dig[a[1]] ); } } } else if(dig==4){ printf("%s thousand",one_dig[a[4]]) ; if(a[3]!=0){ printf("%s hundred",one_dig[a[3]]) ;} if(a[2]==0){ printf("%s",one_dig[a[1]]) ;} else{ if(a[2]==1){printf("%s",two_dig[k%10]);} else{printf("%s ",tens_multiple[a[2]]); printf("%s ",one_dig[a[1]] ); } } } return 0 ; }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <quirc.h> #include <jpeglib.h> #include <sys/stat.h> #include </usr/include/setjmp.h> #include <zconf.h> /* * Object that contain image data information * */ struct Image { uint8_t *buffer; int width; int height; unsigned long size; }; typedef struct __jmp_buf_tag jmp_buf[1]; struct my_jpeg_error { struct jpeg_error_mgr base; jmp_buf env; }; static void my_output_message(struct jpeg_common_struct *com) { struct my_jpeg_error *err = (struct my_jpeg_error *) com->err; char buf[JMSG_LENGTH_MAX]; err->base.format_message(com, buf); fprintf(stderr, "JPEG error: %s\n", buf); } static void my_error_exit(struct jpeg_common_struct *com) { struct my_jpeg_error *err = (struct my_jpeg_error *) com->err; my_output_message(com); longjmp(err->env, 0); } /* * Load image file and return image object that contain image data buffer pointer and file size * */ struct Image load_jpeg(const char *filename) { struct Image img; int rc, i; struct stat file_info; unsigned long jpg_size; unsigned char *jpg_buffer; stat(filename, &file_info); jpg_size = file_info.st_size; jpg_buffer = (unsigned char *) malloc(jpg_size + 100); int fd = open(filename, O_RDONLY); i = 0; while (i < jpg_size) { rc = read(fd, jpg_buffer + i, jpg_size - i); printf("Input: Read %d/%lu bytes\n", rc, jpg_size - i); i += rc; } close(fd); img.buffer = jpg_buffer; img.size = jpg_size; return img; } /* * Load image from buffer and return the grayscaled image data in form of a struct image * */ struct Image decompress_image(uint8_t *jpg_buffer, unsigned long jpg_size) { struct Image img; unsigned long output_size; unsigned char *output_buffer; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; int row_stride, width, height, pixel_size; printf("Proc: Create Decompress struct\n"); cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); printf("Proc: Set memory buffer as source\n"); jpeg_mem_src(&cinfo, jpg_buffer, jpg_size); printf("Proc: Read the JPEG header\n"); jpeg_read_header(&cinfo, TRUE); cinfo.output_components = 1; cinfo.out_color_space = JCS_GRAYSCALE; printf("Proc: Initiate JPEG decompression\n"); jpeg_start_decompress(&cinfo); width = cinfo.output_width; height = cinfo.output_height; pixel_size = cinfo.output_components; printf("Proc: Image is %d by %d with %d components\n", width, height, pixel_size); output_size = width * height * pixel_size; output_buffer = (unsigned char *) malloc(output_size); row_stride = width * pixel_size; printf("Proc: Start reading scanlines\n"); while (cinfo.output_scanline < cinfo.output_height) { unsigned char *buffer_array[1]; buffer_array[0] = output_buffer + \ (cinfo.output_scanline) * row_stride; jpeg_read_scanlines(&cinfo, buffer_array, 1); } printf("Proc: Done reading scanlines\n"); jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buffer); printf("End of decompression\n"); img.width = width; img.height = height; img.buffer = output_buffer; return img; } /* * Decode qr-code loaded from buffer array * */ char *decode_qr(uint8_t *buffer, unsigned long size) { /* * To decode images, you'll need to instantiate a ``struct quirc`object, * which is done with the ``quirc_new`` function. * * quirc_begin() must first be called to obtain access to a buffer into * which the input image should be placed. Optionally, the current width and height may be returned. */ struct quirc *q; struct Image decompressedImage; q = quirc_new(); decompressedImage = decompress_image(buffer, size); int decompressedImageWidth; int decompressedImageHeight; uint8_t *decompressedImageBuffer; decompressedImageHeight = decompressedImage.height; decompressedImageWidth = decompressedImage.width; decompressedImageBuffer = decompressedImage.buffer; /* * Load png image file by filename, * convert to grayscale image, * feed grayscale image ke buffer using quirc_end and quirc_begin. * */ printf("img width: %d\n", decompressedImageHeight); printf("img height: %d\n", decompressedImageWidth); printf("img buffer: %p\n", decompressedImageBuffer); /* * Having obtained a decoder object, * you need to set the image size that you'll be working with, * which is done using ``quirc_resize``. */ quirc_resize(q, decompressedImageWidth, decompressedImageHeight); /* * These functions are used to process images for QR-code recognition. * quirc_begin() must first be called to obtain access to a buffer into * which the input image should be placed. Optionally, the current * width and height may be returned. * */ uint8_t *quircBuffer; quircBuffer = quirc_begin(q, &decompressedImageWidth, &decompressedImageHeight); uint8_t *decompressedImageBufferPtr; decompressedImageBufferPtr = decompressedImageBuffer; unsigned int image_area = decompressedImageWidth * decompressedImageHeight; /*check value and copy elements*/ for (int i = 0; i < image_area; ++i) { /*printf("Value of image[%d] = %d\n", i, *p);*/ *quircBuffer = *decompressedImageBufferPtr; decompressedImageBufferPtr++; quircBuffer++; } /* * After filling the buffer, quirc_end() should be called to process * the image for QR-code recognition. The locations and content of each * code may be obtained using accessor functions described below. */ quirc_end(q); /* This structure is used to return information about detected QR codes in the input image. */ struct quirc_code code; /* This structure holds the decoded QR-code data */ struct quirc_data data; /* Extract the QR-code specified by the given index. */ quirc_extract(q, 0, &code); /* Decode a QR-code, returning the payload data. */ quirc_decode(&code, &data); /* Copy data payload from quirc_data to dataPayloadBuffer */ uint8_t *dataPayloadBuffer = malloc(sizeof(uint8_t) * QUIRC_MAX_PAYLOAD); uint8_t *dataPayloadBufferPtr = dataPayloadBuffer; uint8_t *dataPayloadPtr = data.payload; for (int j = 0; j < QUIRC_MAX_PAYLOAD; ++j) { *dataPayloadBufferPtr = *dataPayloadPtr; dataPayloadBufferPtr++; dataPayloadPtr++; } /* * Later, when you no longer need to decode anything, * you should release the allocated memory with ``quirc_destroy`` * */ quirc_destroy(q); /* Return data payload in char pointer form (string in c) */ return (char *) dataPayloadBuffer; } void decoder(char **argv) { /* * Print input filename * */ printf("Filename is %s \n", (const char *) argv[1]); /* * Load png and assign the returned object to Image struct * */ struct Image img = load_jpeg(argv[1]); /* * Print returned data payload from decode_qr function * */ char *dataPayload; dataPayload = decode_qr(img.buffer, img.size); printf("Data payload is %s \n", dataPayload); } int main(int argc, char **argv) { decoder(argv); }
C
#include <stdio.h> #include <cs50.h> typedef struct{ char name[20]; int age; char eyeColor[20]; }person; int main(void){ person *p; FILE *archivo = fopen("bin.cs50","r+"); if(archivo == NULL){ printf("Error\n"); return 1; } //int n = (sizeof(archivo)/sizeof(person)); p = malloc(sizeof(person)); if(p == NULL){ printf("No se pudo reservar memoria\n"); return 1; } fread(p,sizeof(person),1, archivo); printf("Nombre: %s, Edad: %d, Color de ojos %s\n",p->name,p->age,p->eyeColor); fclose(archivo); free(p); return 0; }
C
/************************************************************************* > File Name: 1.c > Author: crooked > Mail:812665244@qq.com > Created Time: Mon 07 Apr 2014 07:55:57 PM CST ************************************************************************/ #include<iostream> int main() { std::cout<<"Enter two numbers:"<< std::endl; int v1, v2; std:: cin>>v1>>v2; std:: cout<<"The sum of "<< v1 <<"and" <<v2 <<"is"<<v1+v2 <<std ::endl; return 0; }
C
#include "msgs.h" #include <stdlib.h> #include <time.h> // Murali Ravivarma // Vivek Narasimha Dondeti void client() { srand(time(NULL)); int r; int count1=1; while(1) { int a[10]; int i=0; r=(rand()%100); a[0]=r; printf("\n\nAt Client, sending msg to Server specifying the replyport as %d\n", r); for(i=1;i<10;i++) { a[i]=count1; printf("%d ", a[i]); } printf("\n"); send(&port[0], a); count1++; sleep(2); receive(&port[r],a); printf("\nAt Client, receiving msg from Server on port: %d\n",r); for(i=1;i<10;i++) { printf("%d ", a[i]); } sleep(2); } } void server() { int count=0; int replyport; while(1){ count++; int a[10]; receive(&port[0],a); printf("\nAt Server, receive success \n"); int i=0; for(i=1;i<10;i++) printf("%d ", a[i]); replyport=a[0]; printf("\nAt Server, sending the msg to Client via reply port: %d\n",replyport); for(i=1;i<10;i++) printf("%d ", a[i]); send(&port[replyport],a); } } void (*c1)(); void (*s1)(); int main() { ReadyQ = newQueue(); initialiseports(); printf("\n********************************************\n"); printf("Message passing system with two clients and a server\n"); printf("Server listens at port 0 and send back the msgs to the port number specified by client in msg_arr[0]\n"); //printf("NOTE: To create second server, pls uncomment line no. 77 \n"); printf("********************************************\n"); c1 = client; printf("\nCreating Client 1\n"); start_thread(c1); printf("Creating Client 2\n"); start_thread(c1); s1 = server; printf("Creating Server 1\n"); start_thread(s1); //printf("Creating Server 2\n"); start_thread(s1); run(); while (1) { sleep(2); } }
C
#include "conv.h" #include "board.h" #define error(a, b) //extern void error(const char a, uint32_t b); uint16_t _strlen (const char *str) { uint32_t i = 0; if (NULL != str) while ('\0' != str[i]) { i++; if (i >= STR_MAX_SIZE) { //error("strlen>", i); return STR_MAX_SIZE; } } return i; } uint8_t bcd2dec (uint8_t val) { return ( (val/16*10) + (val%16) ); } uint8_t dec2bcd (uint8_t val) { return ( (val/10*16) + (val%10) ); } uint32_t _dec2bcd (uint16_t dec) /* Standard iterative function to convert 16-bit integer to BCD */ { uint32_t result = 0; int shift = 0; while (dec) { result += (dec % 10) << shift; dec = dec / 10; shift += 4; } return result; } uint32_t dec2bcd_r(uint16_t dec) /* Recursive one liner because that's fun */ { return (dec) ? ((dec2bcd_r( dec / 10 ) << 4) + (dec % 10)) : 0; } #define MAX_SIZE_STRING 16 /** HEX ASCII **/ const static char harDEC[] = "0123456789"; //const static unsigned char harHEX[] = "0123456789ABCDEF"; uint8_t long2str (char *pstring, uint32_t value) { // @todo uint8_t ms[MAX_SIZE_STRING]; uint8_t size, i; uint32_t temp; i = MAX_SIZE_STRING; while(i--) { ms[i] = 0; // temp = (value % 10); ms[i] = temp; value /= 10; } size = 0; // ? for (i = 0; i < MAX_SIZE_STRING; i++) { //if (0 != ms[i]) { // pstring[size] = harDEC[ms[i]]; size++; } } pstring[size] = '\0'; // return size; } int32_t float2int32 (float number, uint8_t zeros) { uint8_t i; //BOOL sign = FALSE; @todo float fvalue; if (number < 0) /** **/ { //sign = TRUE; number *= -1; } fvalue = number; for (i = 0; i < zeros; i++) { fvalue *= 10; } // 0.5 - return (int32_t)(fvalue + 0.5); } char char2upper (char ch)// @todo { if ((ch >= 'a') && (ch <= 'z')) ch &= 0x5F; else {//conversion Windows-1251 if (((uint8_t)ch >= (uint8_t)('')) && ((uint8_t)(ch) <= (uint8_t)(''))) ch -= ('' - ''); } return ch; } void _memcpy (char *src, uint32_t n, char *dest) { if (NULL == src) // pointer checking return; if (NULL == dest) // pointer checking return; for (; 0 < n; n--) *src++ = *dest++; } char *_strchr (const void *aStr, char Chr) // , @todo { char *str = (char*)aStr; for (;;) { char a = *str++; if(a == Chr) return --str; // if(!a) break; // , } return 0; //NULL; } char *_strncmp (char *strA, char *strB) { msg_t resp = FUNCTION_RETURN_ERROR; uint32_t i, j; uint32_t m, n; char *p_str = (char *)NULL; if (NULL == strA) // pointer checking return (char *)NULL; m = _strlen (strA); // if (m >= STR_MAX_SIZE) return (char *)NULL; if (NULL == strB) return (char *)NULL; m = _strlen (strB); if (m >= STR_MAX_SIZE) return (char *)NULL; n = m; j = 0; while ('\0' != strA[j]) // , { if (strA[j] == strB[0]) { m = n; //_strlen (strB); i = 0; while (('\0' != strB[i]) || ('\0' != strA[j + i])) { if (strA[j + i] == strB[i]) // m--; else break; i++; } if (0 == m) // , return &strA[j]; } j++; } return (char *)NULL; } uint8_t char2hex (char c) { uint8_t v; if(c >= '0' && c <= '9') v = c - '0'; else if(c >= 'a' && c <= 'f') v = c - 'a' + 10; else if(c >= 'A' && c <= 'F') v = c - 'A' + 10; else v = 0xFF; //not a hex return v; }
C
/* * zeroskip is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. * * Copyright (c) 2018 Partha Susarla <mail@spartha.org> * */ #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include "cmds.h" static void usage_and_die(const char *progname) { fprintf(stderr, "Usage: %s %s\n", progname, cmd_batch_usage); exit(EXIT_FAILURE); } int cmd_batch(int argc, char **argv, const char *progname) { static struct option long_options[] = { {"config", required_argument, NULL, 'c'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; int option; int option_index; const char *config_file = NULL; while((option = getopt_long(argc, argv, "c:h?", long_options, &option_index)) != -1) { switch (option) { case 'c': config_file = optarg; break; case 'h': case '?': default: usage_and_die(progname); }; } cmd_parse_config(config_file); exit(EXIT_SUCCESS); }
C
#include <stdio.h> int main() { int i,j,a,b,flag = 0,c=0; scanf("%d%d",&a,&b); for(i=a;i<=b;i++) { flag=0; for(j=2; j<=i/2; ++j) if(i%j==0) { flag=1; break; } if (flag==0) c++; } printf("%d\t",c); return 0; }
C
#include<stdlib.h> /*returns a pointer to a newly allocated space in memory, which contains a copy of the string given as a parameter*/ char *string_dup(char *str) { int len; int i; char *ret; i = 0; len = 0; while (str[len] != '\0') { len++; } ret = malloc(len * sizeof(char)); if (ret == NULL) { return (NULL); } while (len > 0) { ret[i] = str[i]; i++; len--; } ret[i] = 0; return(ret); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* summator.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kwillum <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/15 17:28:23 by kwillum #+# #+# */ /* Updated: 2020/02/16 23:30:56 by kwillum ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_eval.h" int ft_dimnb(long long int nb) { int len; len = 0; while (nb / 10 > 0) { len++; nb = nb / 10; } return (len + 1); } long long int next_nb(char *str, int *pos) { long long int val; int counter; counter = 0; while (str[*pos + counter] == ' ') counter++; if (str[*pos + counter] == '(') { *pos = *pos + counter + 1; val = in_calc(str, 0, pos); counter = 0; *pos = *pos + 1; } else { val = ft_atoi((str + counter + *pos)); counter = counter + ft_dimnb(val); } while (str[*pos + counter] == ' ') counter++; *pos = *pos + counter; return (val); } long long int in_calc(char *st, long long int val, int *pos) { int op_n; if (is_operator(st[*pos]) == 2) return (val); else if (is_operator(st[*pos]) == 4) return (val); else if (is_operator(st[*pos]) == 3) { val = next_nb(st, pos); return (in_calc(st, val, pos)); } else if (is_operator(st[*pos]) == 1) { op_n = num_op(st[*pos]); *pos = *pos + 1; if (op_n <= 2) return (in_calc(st, oper(op_n, val, next_nb(st, pos)), pos)); else if (op_n > 2) return (val + in_calc(st, oper(op_n, 0, next_nb(st, pos)), pos)); } else return (in_calc(st, next_nb(st, pos), pos)); return (0); } int eval_expr(char *str) { int counter; counter = 0; while (str[counter] == ' ') counter++; return (in_calc(str, 0, &counter)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* put_column_str.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mrandou <mrandou@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/13 13:19:20 by mrandou #+# #+# */ /* Updated: 2019/04/15 13:17:52 by mrandou ### ########.fr */ /* */ /* ************************************************************************** */ #include "../incs/diff.h" void first_column(struct s_dlist *file1, int mid) { int size; size = ft_strlen(file1->content); ft_putnbr(file1->number); ft_putstr(" > "); print_spaces(mid * 10 / 100 - ft_nblen(file1->number)); print_nstr(file1->content, mid * 80 / 100); if (size > mid * 80 / 100 - 6) size = mid * 80 / 100; print_spaces(mid * 90 / 100 - size); } void put_column_str(struct s_dlist *file1, struct s_dlist *file2) { struct winsize window; int mid; int ret; int nb_print; ret = 0; if (ioctl(0, TIOCGWINSZ, &window) == -1) return ; mid = window.ws_col / 2; nb_print = mid; if (file1->content) first_column(file1, mid); else print_spaces(mid); ft_putchar('|'); if (file2->content) { print_spaces(mid * 10 / 100); nb_print += mid * 10 / 100; ret = print_nstr(file2->content, mid * 80 / 100); if (ret) nb_print += mid * 80 / 100; else nb_print += ft_strlen(file2->content); print_spaces((window.ws_col - nb_print) - 3); } }
C
/* * CS3600, Spring 2013 * Project 4 Starter Code * (c) 2013 Alan Mislove * */ #include <math.h> #include <ctype.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <sys/time.h> #include <sys/types.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "3600sendrecv.h" unsigned int sequence = 0; window win; int data_byte_at_start_of_window = 0; int main() { /** * I've included some basic code for opening a UDP socket in C, * binding to a empheral port, printing out the port number. * * I've also included a very simple transport protocol that simply * acknowledges every received packet. It has a header, but does * not do any error handling (i.e., it does not have sequence * numbers, timeouts, retries, a "window"). You will * need to fill in many of the details, but this should be enough to * get you started. */ // first, open a UDP socket int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // next, construct the local port struct sockaddr_in out; out.sin_family = AF_INET; out.sin_port = htons(0); out.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (struct sockaddr *) &out, sizeof(out))) { perror("bind"); exit(1); } struct sockaddr_in tmp; int len = sizeof(tmp); if (getsockname(sock, (struct sockaddr *) &tmp, (socklen_t *) &len)) { perror("getsockname"); exit(1); } mylog("[bound] %d\n", ntohs(tmp.sin_port)); // wait for incoming packets struct sockaddr_in in; socklen_t in_len = sizeof(in); // construct the socket set fd_set socks; // construct the timeout struct timeval t; t.tv_sec = RECV_TIMEOUT; t.tv_usec = 0; initialize_window(&win); int last_acked = 0; int number_of_times_acked = 0; // wait to receive, or for a timeout while (1) { // our receive buffer int buf_len = 1500; void* buf = malloc(buf_len); FD_ZERO(&socks); FD_SET(sock, &socks); if (select(sock + 1, &socks, NULL, NULL, &t)) { int received; if ((received = recvfrom(sock, buf, buf_len, 0, (struct sockaddr *) &in, (socklen_t *) &in_len)) < 0) { perror("recvfrom"); exit(1); } header *myheader = get_header(buf); int window_pos = (myheader->sequence - win.data_offset_at_start_of_window) / 1460; if (myheader->magic != MAGIC){ mylog("[recv corrupted packet]\n"); continue; } if ( myheader->sequence < win.data_offset_at_start_of_window) mylog("[recv duplicate packet: %d]\n", myheader->sequence); else if ( window_pos >= win.size) mylog("[recv error - packet beyond window size]\n"); else if (window_pos == 0) mylog("[recv data] %d (%d) %s\n", myheader->sequence, myheader->length, "ACCEPTED (in-order)"); else if (window_pos < win.size) mylog("[recv data] %d (%d) %s\n", myheader->sequence, myheader->length, "ACCEPTED (out-of-order)"); // store the data in case there are gaps in transmission if (window_pos >= 0 && window_pos < win.size && win.frames[window_pos].is_free) add_frame_at_index(&win, *myheader, buf, window_pos); else free(buf); // otherwise it is freed when window shifts // print all completed stored data at the front of the window int eof = 0; int i = 0; while(i < win.size && !win.frames[i].is_free){ header *head = &(win.frames[i].head); char *data = get_data(win.frames[i].data); write(1, data, head->length); if(head->eof) eof = 1; i++; } int frames_printed = i; // Build ACK int ack_num; if (frames_printed > 0){ header *last_header = &win.frames[frames_printed - 1].head; ack_num = last_header->sequence + last_header->length; } else{ ack_num = win.data_offset_at_start_of_window; } header *responseheader = make_header(ack_num, 0, eof, 1); if (last_acked == ack_num) number_of_times_acked++; else{ last_acked = ack_num; number_of_times_acked = 0; } // If multiple frames were completed, packets are probably // being dropped, so send multiple acks. But don't send more than three, // or it might trigger the sender to retransmit window in a feedback loop int n = frames_printed; if (frames_printed > 2) n = 2; int j = 0; // Send Acks do{ j++; // if this squence number has been acked less than 7 times, send it // again, otherwise harsh backoff number_of_times_acked++; if(number_of_times_acked > 7 && number_of_times_acked % 3 != 0){ continue; } mylog("[send ack] %d\n", ack_num); if (sendto(sock, responseheader, sizeof(header), 0, (struct sockaddr *) &in, (socklen_t) sizeof(in)) < 0) { perror("sendto"); exit(1); } } while (j < n); free(responseheader); // Shift the window the number of frames fully received and printed shift_window(&win, frames_printed); if (eof) { mylog("[recv eof]\n"); mylog("[completed]\n"); exit(0); } } else { mylog("[error] timeout occurred\n"); exit(1); } } return 0; }
C
#include "FloatLoopType.h" float getMinDifference_FLOAT(LoopFloatType type, float valueA, float ValueB) { float width = type.maxValue - type.minValue; float difference = valueA > ValueB ? valueA - ValueB : ValueB - valueA; if (width / 2 > difference) { if (valueA > ValueB) { if (type.antiTurning) { return difference; } return -difference; } else { if (type.antiTurning) { return difference; } return difference; } } else { if (valueA < ValueB) { if (type.antiTurning) { return difference; } return -difference; } else { if (type.antiTurning) { return difference; } return difference; } } } void LOOP_FLOAT_ADD(LoopFloatType type, float *value, float addValue) { *value += addValue; while (*value > type.maxValue) { *value = *value - type.maxValue + type.minValue; } } void LOOP_FLOAT_SUB(LoopFloatType type, float *value, float subValue) { *value -= subValue; while (*value < type.minValue) { *value = type.maxValue - type.minValue + *value; } }
C
#include<iostream> using namespace std; int main() { int t,n,x,y,count; cin>>t; while(t--) { x=0; y=0; count=0; cin>>n; x=x+3*(n/5); y=y-2*(n/5); count=(n/5)*5; if(count!=n) { x=x+1; count++; } if(count!=n) { y=y+2; count++; } if(count!=n) { x=x-3; count++; } if(count!=n) { y=y-4; count++; } if(count!=n) { x=x+5; count++; } cout<<x<<" "<<y<<endl; } }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include "DynamicArr.h" #include "SeqQueue.h" VdSeqQue SeqQueueInit() { //queue init struct DyArrStru *seqQue = DyArrInit(3); return seqQue; } void Enqueue(VdSeqQue vdSeqQue, void *pushData) { if (vdSeqQue==NULL || pushData==NULL) { return; } struct DyArrStru* seqQue = vdSeqQue; if (seqQue->arrCount==queueMax) { return; } InsertArr(seqQue, seqQue->arrCount, pushData); } void Dequeue(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return; } struct DyArrStru *seqQue = vdSeqQue; if (seqQue->arrCount == 0) { return; } //first in first out,head remove RemoveDyArrByPos(seqQue,0); } void *GetHeadQueue(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return; } struct DyArrStru *seqQue = vdSeqQue; return seqQue->dyptAddr[0]; } void *GetTailQueue(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return; } struct DyArrStru *seqQue = vdSeqQue; return seqQue->dyptAddr[seqQue->arrCount-1]; } int GetQueueCount(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return; } struct DyArrStru *seqQue = vdSeqQue; return seqQue->arrCount; } int GetQueIsNULL(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return -1; } struct DyArrStru *seqQue = vdSeqQue; if (seqQue->arrCount==0) { return 1; //NULL,return 1 } return 0; //not null,return 0 } void DestoryQueue(VdSeqQue vdSeqQue) { if (vdSeqQue == NULL) { return; } ClearDyArr(vdSeqQue); }
C
// Ficheros de cabecera y librerias #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <sys/stat.h> #include <time.h> #include <fcntl.h> #include <stdlib.h> //netbd.h es necesitada por la estructura hostent usando la funcion stat de C POXIS. int main(int argc, char *argv[]) { //hacemos la declaracion de variables para nuestro programa struct stat datos; struct tm *fecha; char tipofich; char *fichero2; if(argc > 2) { //Primer paso, definir variables char *ip; int fd, numbytes,puerto; char buf[100]; puerto=atoi(argv[2]); ip=argv[1]; struct hostent *he; /*==Lee y valida argumentos==*/ /* estructura que recibira informacion sobre el nodo remoto */ struct sockaddr_in server; /* informacion sobre la direccion del servidor */ if ((he=gethostbyname(ip))==NULL){ /* llamada a gethostbyname() */ printf("gethostbyname() error\n"); exit(-1); } //Paso 2, Definicion de socket y creacion de la conexion con el servidor if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){ /* llamada a socket() */ printf("socket() error\n"); exit(-1); } //Datos del servidor server.sin_family = AF_INET; server.sin_port = htons(puerto); server.sin_addr = *((struct in_addr *)he->h_addr); /*he->h_addr pasa la información de ``*he'' a "h_addr" */ bzero(&(server.sin_zero),8); //Paso 3, conectarnos al servidor if(connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr))==-1){ /* llamada a connect() */ printf("connect() error\n"); exit(-1); } if ((numbytes=recv(fd,buf,100,0)) == -1){ /* llamada a recv() */ printf("Error en recv() \n"); exit(-1); } buf[numbytes]='\0'; //Se envia el nombre del archivo asi como el host y direccion. printf("Nombre de este host cliente: %s\n",argv[1]); printf("Direccion de internet de este host cliente: %s\n",argv[1]); printf("El puerto del servidor es: %s\n",argv[2]); printf("Nombre de este host servidor: %s\n",argv[1]); printf("Direccion de internet de este host servidor: %s\n",argv[1]); /*Recibe la conexion y la imprime*/ printf("Se ha iniciado el Servidor: %s\n",buf); /* muestra el mensaje de bienvenida del servidor =) */ printf("================================================================\n"); printf("================================================================\n"); if (argc != 4) { /*si no se han ingresado parametros nos lanzara un error*/ perror("Necesario fichero o directorio como parámetro\n"); exit (-1); } if (stat(argv[3],&datos) != 0) { perror("Error en el stat"); exit (-1); } //nos muestra el nombre del archivo o fichero. printf("Nombre del fichero: %s\n",argv[3]); //nos muestra la informacion del fichero pedida. printf("Recide en el dispositivo = %ld \n", (long) datos.st_dev); printf("Numero de inode = %ld \n", (long) datos.st_ino); printf("Tamaño(longitud) en bytes: %d\n",datos.st_size); switch(datos.st_mode & S_IFMT) { case S_IFREG: tipofich='R'; printf("Tipo de fichero: Parametro (%c)\n",tipofich); break; case S_IFLNK: tipofich='L'; printf("Tipo de fichero: Fichero: (%c)\n",tipofich); break; case S_IFDIR: tipofich='D'; printf("Tipo de fichero: Directorio: (%c)\n",tipofich); break; } //printf("Tipo de fichero: %c\n",tipofich); printf("Permisos: \t"); printf( (S_ISDIR(datos.st_mode)) ? "d" : "-"); printf( (datos.st_mode & S_IRUSR) ? "r" : "-"); printf( (datos.st_mode & S_IWUSR) ? "w" : "-"); printf( (datos.st_mode & S_IXUSR) ? "x" : "-"); printf( (datos.st_mode & S_IRGRP) ? "r" : "-"); printf( (datos.st_mode & S_IWGRP) ? "w" : "-"); printf( (datos.st_mode & S_IXGRP) ? "x" : "-"); printf( (datos.st_mode & S_IROTH) ? "r" : "-"); printf( (datos.st_mode & S_IWOTH) ? "w" : "-"); printf( (datos.st_mode & S_IXOTH) ? "x" : "-"); printf("\n"); printf("Número de enlaces: %d\n",datos.st_nlink); printf("User ID= %ld (alexis)\n", (long) datos.st_uid); printf("Group ID= %ld (alexis) \n", (long) datos.st_gid); printf("Fecha Último acceso: "); printf("%s \n",ctime(&datos.st_atime)); printf("Fecha Última modificación: "); printf("%s \n",asctime(localtime(&datos.st_mtime))); close(fd); } else{ printf("No se ingreso el ip y puerto por parametro\n"); } }
C
#include <stdio.h> #include <math.h> ranf(r) double *r; {int ir; ir=rand(); ir=ir & 0xfffffff; *r=(double)ir/268435455.0; return(0); } rannor(a,b) double *a,*b; {double t,r,r1,r2,r3,r4,aa,bb; ranf(&r1); t=6.283185*r1; ranf(&r2); r3=1.0/r2; r4=2.0*log(r3); r=sqrt(r4); aa=r*cos(t); bb=r*sin(t); /* printf("r=%f t=%f r1=%f r2=%f r3=%f r4=%f\n",r,t,r1,r2,r3,r4); */ *a=aa; *b=bb; /* printf("rannor a=%f b=%f\n",aa,bb); */ return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { int len_a, len_b; printf("Length of string a = "); scanf("%d", &len_a); getc(stdin); char* a = malloc(len_a * sizeof(char)); printf("String a = "); scanf("%s", a); getc(stdin); printf("Length of string b = "); scanf("%d", &len_b); getc(stdin); char* b = malloc(len_b * sizeof(char)); printf("String b = "); scanf("%s", b); getc(stdin); printf("1. a + b = %s\n", strcat(a, b)); printf("3. Compare a to b: %d\n", strcmp(a, b)); printf("5. Copy b to a: %s\n", strcpy(a, b)); free(a); free(b); printf("Length of string a = "); scanf("%d", &len_a); getc(stdin); a = malloc(len_a * sizeof(char)); printf("String a = "); scanf("%s", a); getc(stdin); printf("Length of string b = "); scanf("%d", &len_b); getc(stdin); b = malloc(len_b * sizeof(char)); printf("String b = "); scanf("%s", b); getc(stdin); printf("Searching for elements of b in a\n"); for (int i = 0; i < len_b; i++) { if (strchr(a, b[i]) != NULL) { printf("Element %c is in a\n", *strchr(a, b[i])); } } printf("Len of the part of a that doen't contain b: %d\n", strcspn(a, b)); free(a); free(b); return 0; }
C
#include <stdio.h> int main(void) { float x, y, z, sum, avg; printf("실수를 입력하시오.\n"); scanf_s("%f", &x); printf("실수를 입력하시오.\n"); scanf_s("%f", &y); printf("실수를 입력하시오.\n"); scanf_s("%f", &z); sum = x + y + z; avg = sum / 3; printf("합계는 %f이고, 평균값은 %f입니다.\n", sum, avg); }
C
#include <stdio.h> #define MAX 5 void sort(int arr[], int); int main(void) { int arr[5] = {12, 11, 13, 5, 6}; sort(arr, MAX); printf("Sorted array: \n"); for(int i = 0;i < MAX;i++) printf("%d ", arr[i]); printf("\n"); } //12, 11, 13, 5, 6 void sort(int arr[], int num) { int temp, i, j; for(i = 1; i < num; i++) { j = i-1; temp = arr[i]; while(j >=0 && arr[j] > temp) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = temp; } }
C
#include<stdio.h> void bubble(int data[15],int no); void selection(int data[15],int no); void insertion(int data[15],int no); int main() { int no,data[15],i,ch; //no=total no of elements printf("\n\n\tenter total no of students:"); scanf("%d",&no); for(i=0;i<no;i++) { printf("\n\n\tenter the roll nos:"); scanf("%d",&data[i]); } do { printf("\n\n\t***SORTING***"); printf("\n\n\t1.Bubble sort\n\n\t2.selection sort\n\n\t3.insertion sort"); printf("\n\n\tEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("\n\n\t***BUBBLE SORT***"); bubble(data,no); break; case 2: printf("\n\n\t***SELECTION SORT***"); selection(data,no); break; case 3: printf("\n\n\t***INSERTION SORT***"); insertion(data,no); break; } }while(ch!=10); return 0; } void bubble(int a[15],int no) { int i,j,temp,k,no1; no1=no-1; for(i=0;i<no;i++) { for(j=0;j<no1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("\n\n\n After sorting\t\n\n\n"); for(i=0;i<no;i++) { printf("\t%d",a[i]); } } void selection(int a[15],int no) { int i,j,temp,k; for(i=0;i<no;i++) { for(j=i+1;j<no;j++) { if(a[i]>a[j]) { temp=a[j]; a[j]=a[i]; a[i]=temp; } } } //print the sorted elements printf("\n\n\t after sorting\t\n\n"); for(i=0;i<no;i++) { printf("\t%d",a[i]); } } void insertion(int a[15],int no) { int i,j,temp,k; for(i=1;i<no;i++) { temp=a[i]; j=i; while(j>0 && (a[j-1]>temp)) { a[j]=a[j-1]; j=j-1; } a[j]=temp; } printf("\n\n\n After sorting\t\n\n\n"); for(i=0;i<no;i++) { printf("\t%d",a[i]); } }
C
#include <stdio.h> int main() { //Solicitar o n ao usuário int n; printf("Digite o valor de n: "); scanf("%d",&n); //Calcular o primeiro ímpar int primeiro; primeiro = (n*n)-n+1; int soma = primeiro; int proximo = primeiro + 2; int i = 1; printf("%d\n",primeiro); for (i=1; i<=(n-1);i++) { soma = soma + proximo; printf("%d\n",proximo); proximo = proximo + 2; } printf("Soma: %d\n",soma); return 0; }
C
/* Write a program for error detecting code using CRC-CCITT (16bit) */ #include <stdio.h> char msg[50], gen[50], rem[50], quo[50], temp[50]; void caltrans(int); void crc(int); void calrem(); void shiftl(); int main() { int n, i = 0; char ch, flag = 0; printf("Enter the Polynomial: "); while ((ch = getc(stdin)) != '\n') msg[i++] = ch; n = i; for (i = 0; i < 16; i++) msg[n++] = '0'; msg[n] = '\0'; printf("Modified Polynomial: %s", msg); for (i = 0; i <= 16; i++) gen[i] = '0'; gen[0] = gen[4] = gen[11] = gen[16] = '1'; gen[17] = '\0'; printf("\nGenerator: %s", gen); crc(n); printf("\nQuotient: %s", quo); printf("\nChecksum: %s", rem); caltrans(n); printf("\nFinal Codeword: %s", msg); printf("\nEnter transmitted Frame: "); scanf("\n%s", msg); crc(n); for (i = 0; i < 16; i++) if (rem[i] != '0') flag = 1; else continue; if (flag == 1) printf("\nError Detected"); else printf("\nNo Error Detected, Received Frame is correct."); } void crc(int n) { int i, j; for (i = 0; i < n; i++) temp[i] = msg[i]; for (i = 0; i < 16; i++) rem[i] = msg[i]; for (i = 0; i < n - 16; i++) { if (rem[0] == '1') { quo[i] = '1'; calrem(); } else { quo[i] = '0'; shiftl(); } rem[16] = msg[17 + i]; rem[17] = '\0'; for (j = 0; j <= 17; j++) temp[j] = rem[j]; } quo[n - 16] = '\0'; } void calrem() { int i, j; for (i = 1; i <= 16; i++) rem[i - 1] = ((int)temp[i] - 48) ^ ((int)gen[i] - 48) + 48; } void shiftl() { int i; for (i = 1; i <= 16; i++) rem[i - 1] = rem[i]; } void caltrans(int n) { int i, k = 0; for (i = n - 16; i < n; i++) msg[i] = ((int)msg[i] - 48) ^ ((int)rem[k++] - 48) + 48; msg[i] = '\0'; }
C
/* * FICHERO: funciones.h * AUTORES: Jorge Hunter Iaki Echevarra Jos Miguel Hervs * * El fichero contiene algunas funciones que se utilizan en el programa. */ #ifndef FUNCIONES_H #define FUNCIONES_H #include "main.h" // La funcin mezcla las posiciones de los ndices de una tabla utilizando // el algoritmo de Fisher-Yates. // // Inputs: puntero struct lista que apunta al comienzo de la tabla y int que // contiene el nmero de elementos en la tabla. // // Outputs: la funcin opera sobre la tabla y la mezcla. // // En cada iteracin se elige al azar un nmero entre 1 y el nmero de elementos // que queden sin ordenar y se coloca en la nueva tabla aleatoria. void mezclar(struct lista *, long); // La funcin crea la tabla que indica el usuario. // // Inputs: puntero struct lista que apunta al comienzo de la tabla, long con el // tipo de ordenacin de la tabla y long con el tamao de la tabla. // // Outputs: la tabla de tamao y ordenacin indicados. void crearTabla(struct lista *, long, long); // La funcin ordena una tabla utilizando el mtodo indicado. // // Inputs: puntero struct lista que apunta al comienzo de la tabla, long con el // tamao de la tabla y long con el algoritmo a usar para ordenarla. // // Outputs: la funcin opera sobre la tabla y la ordena. void ordenarTabla(struct lista *, long, long,long*, long*); #endif
C
#include <curses.h> #include <stdio.h> /* Compile with: gcc -Wall -pedantic -lcurses curses_test.c */ /* The window pointer. */ WINDOW *mywindow; int main() { int r; mywindow = initscr(); nodelay(mywindow, 1); /* makes getch() a non blocking function. */ mvprintw(10, 10, "####################"); mvprintw(11, 10, "ROWS: %d", LINES); while ((r = getch()) == ERR) ; endwin(); printf("Getch() returnerade: %d\n", r); return 0; }
C
#include <stdio.h> int isOE(int number) { if((number%2)==0) return -1; else return 1; } int main() { int r; scanf("%d",&r); printf("%d \n",isOE(r)); return 0; }
C
/* * 1BPP BMP to XBM converter. * Public domain. */ #include <stdio.h> #include <string.h> #include <endian.h> #include <stdint.h> #include <malloc.h> char *img; uint16_t width, height, offset, bpp, byte_width; void show_usage(const char *name) { fprintf(stdout, "Usage:\t%s INPUT-FILE [OUTPUT-FILE]\n", name); } int load_bitmap(const char *filename) { #define BMP_HEADER_SIZE 54 FILE *f; char header[BMP_HEADER_SIZE]; char buffer[1024]; int n; int x, y, pad; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Can't open '%s'\n", filename); return 1; } n = fread(header, sizeof(char), BMP_HEADER_SIZE, f); if (n < BMP_HEADER_SIZE || /* First 2 bytes are 0x424d */ header[0] != 'B' || header[1] != 'M') { fprintf(stderr, "Invalid header in '%s'\n", filename); fclose(f); return 2; /* Invalid bitmap */ } width = ((header[18+0] << 0) & 0xFF) | ((header[18+1] << 8) & 0xFF) ; height =((header[22+0] << 0) & 0xFF) | ((header[22+1] << 8) & 0xFF) ; offset =((header[10+0] << 0) & 0xFF) | ((header[10+1] << 8) & 0xFF) ; bpp = ((header[28+0] << 0) & 0xFF) | ((header[28+1] << 8) & 0xFF) ; width = le16toh(width); height = le16toh(height); offset = le16toh(offset); bpp = le16toh(bpp); byte_width = (width + 8 - 1) / 8; pad = (4 - (byte_width) % 4) % 4; if (bpp != 1) { fprintf(stderr, "Not a monochrome bitmap '%s'\n", filename); fclose(f); return 3; /* Wrong kind of bitmap */ } fseek(f, offset, SEEK_SET); img = malloc(sizeof(char) * width * height); if (!img) { fprintf(stderr, "Out of memory, can't allocate %dx%d bytes\n", width, height); fclose(f); return 4; /* Out of memory */ } x = 0; y = 0; while ((n = fread(buffer, sizeof(char), 1024, f))) { int i; for (i = 0; i < n; i++) { int j; for (j = 0; j < 8; j++) { char nibble = ( buffer[i] & (0x80 >> j) ); img[(height - 1 - y) * width + (x)] = nibble; if (++x >= width) break; } if (x >= width) { i += pad; x = 0; if (++y >= height) break; } } } fclose(f); return 0; } int save_xbm(const char *filename) { const char name[] = "inline_font"; int n, bit, x, y; unsigned int t; FILE *f; f = fopen(filename, "wb"); if (!f) { fprintf(stderr, "Can't open '%s'\n", filename); return 1; } fprintf(f, "#define %s_width %d\n", name, width); fprintf(f, "#define %s_height %d\n", name, height); fprintf(f, "static unsigned char %s_bits[] = {\n", name); t = 0; bit = 0; n = 0; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { if (!img[y * width + x]) t |= (0x80 >> (7-bit)); bit++; if (bit > 7) { fprintf(f, "0x%02x, ", t); bit = 0; t = 0; n++; if (n > 12) { fprintf(f, "\n"); n = 0; } } } } if (bit) { fprintf(f, "0x%02x, ", t); } fseek(f, -2, SEEK_CUR); fprintf(f, " };\n"); fclose(f); return 0; } int main(int argc, char *argv[]) { const char *output; if (argc < 2) { show_usage(argv[0]); return 1; } if (argc > 2) { output = argv[2]; } else { output = "inline_font.h"; } if (load_bitmap(argv[1])) { fprintf(stderr, "Unable to read file %s\n", argv[1]); return -1; } if (save_xbm(output)) { fprintf(stderr, "Unable to write file %s\n", output); free(img); return -2; } free(img); return 0; }
C
#include<stdio.h> #include<stdlib.h> /* Name: Questo 05 - lista 2.1 Copyright: Author: Mayara Rysia Date: 11/10/17 14:12 Description: Os valores numricos de 0 9 na tabela ASCII vo de 48 57. */ main(){ char placa[8]; int mes, tam; printf("Insira a placa do carro: "); scanf("%s", &placa); tam = strlen(placa); if(tam>2){ mes = placa[tam-1]; if(mes>=48 && mes<=57){ printf("\n\n\tPLACA DO CARRO INSERIDA: %s\n", placa); mes = mes-48; if(mes == 0){ printf("\n\tMes 0 inexistente! Digite novamente."); } else{ if(mes == 1) printf("\n\tO Emplacamento de ser renovado em JANEIRO!"); if(mes == 2) printf("\n\tO Emplacamento de ser renovado em FEVEREIRO!"); if(mes == 3) printf("\n\tO Emplacamento de ser renovado em MARCO!"); if(mes == 4) printf("\n\tO Emplacamento de ser renovado em ABRIL!"); if(mes == 5) printf("\n\tO Emplacamento de ser renovado em MAIO!"); if(mes == 6) printf("\n\tO Emplacamento de ser renovado em JUNHO!"); if(mes == 7) printf("\n\tO Emplacamento de ser renovado em JULHO!"); if(mes == 8) printf("\n\tO Emplacamento de ser renovado em AGOSTO!"); if(mes == 9) printf("\n\tO Emplacamento de ser renovado em SETEMBRO!"); } } else printf("\n\tPlaca Invalida!"); } else printf("\n\tPlaca Invalida!"); }
C
#include <stdlib.h> #include <GL/glut.h> void Inicializa(void) { glClearColor(1,1,1,0); } void Desenha(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1,0,0); glBegin(GL_TRIANGLES); glVertex2f(-0.5,-0.5); glVertex2f( 0.0, 0.5); glVertex2f( 0.5,-0.5); glEnd(); glutSwapBuffers(); } void funcao_ociosa(void){ glRotatef(1,0,0,1); glutPostRedisplay(); /* Manda o redesenhar a tela em cada frame, sempre que o sistema ficar ocioso */ } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(400,400); glutInitWindowPosition(50, 50); glutCreateWindow("Primeiro Programa"); glutDisplayFunc(Desenha); glutIdleFunc(funcao_ociosa);//registramos a fun��o idle/ociosa Inicializa(); glutMainLoop(); return 0; }
C
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> char s[200]; char c = '\0'; int ex = 2; int k, PID = 0; int pointer = 1; void zero() { printf("Okay, received 0\n"); if (k == 8) { s[pointer] = c; printf("OK. I write c = %d as s[%d]\n", c, pointer); if (c =='\0') { ex = 0; } k = 1; pointer++; c = 0; } else { k++; } printf("%d\n", c); if (ex != 0) { kill(PID, 10); } } void one() { printf("Okay, received 1\n"); int i = 0; int st = 1; if (k == 8) { s[pointer] = c; printf("OK. I write c = %d as s[%d]\n", c, pointer); k = 1; pointer++; c = 1; } else { st = 1; if (k == 0) { st = 1; } else { for (i = 0; i < k; i++) { st = 2*st; } } c = c + st; k++; } kill(PID, 10); printf("%d\n", c); } int main() { //receiver int MyPID = getpid(); int code; printf("First print PID and string in sender\n"); printf("My PID = %d\n",MyPID); printf("Enter sender PID: "); scanf("%d", &PID); signal(10, zero); signal(12, one); kill(PID, 12); while (ex != 0) { } printf("Execution code\n\n\n"); code = 1; while (s[code] != '\0') { printf("%c", s[code]); code++; } printf("\n\n"); return(0); }
C
//Faça um programa que peça um número e então mostre a mensagem: "O número informado foi {numero}. #include <stdio.h> int main() { int numero; printf("Digite um numero:\n"); scanf("%d", &numero ); printf("O numero digitado foi: %d\n", numero); return 0; }
C
#include <stdio.h> long long int f[100050]; long long int x[100050]; int main(void){ int n,q,i,a,b,l,r; scanf("%d%d",&n,&q); scanf("%I64d%I64d",&f[1],&f[2]); scanf("%d%d",&a,&b); for(i=3;i<=n;i++){ f[i] = (a * f[i-2] + b*f[i-1]) % 1000000007; } for(i=1;i<=n;i++){ scanf("%I64d",&x[i]); } while(q--){ scanf("%d%d",&l,&r); for(i=l;i<=r;i++){ x[i] = (f[i-l+1] + x[i] ) % 1000000007; } } for(i=1;i<=n;i++){ printf("%I64d ",x[i]); } return 0; }
C
/* * 基于顺序存储结构的线性表实现 * ---- by U201610136 朱晓光 校际交流1601班 */ #include <stdio.h> #include <stdlib.h> // #define DEBUG /* Page 10 */ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASABLE -1 #define OVERFLOW -2 /* 数据元素类型定义 */ typedef int status; typedef int ElemType; /* Page 22 */ #define LIST_INIT_SIZE 2 #define LIST_INC_SIZE 1 #define LIST_POOL_SIZE 20 /* 基于顺序存储结构的线性表数据结构定义 */ typedef struct _SqList { ElemType *elem; // 指向线性存储区 int length; // 表长 int list_size; // 表容量 } SqList; /* Page 19 */ status SqList_init(SqList *l); status SqList_destroy(SqList *l); status SqList_clear(SqList *l); status SqList_empty(SqList l); int SqList_length(SqList l); status SqList_getElem(SqList l, int i, ElemType *e); status Sqlist_locateElem(SqList l, ElemType e); status SqList_priorElem(SqList l, ElemType cur, ElemType *pre_e); status SqList_nextElem(SqList l, ElemType cur, ElemType *next_e); status SqList_insert(SqList *l, int i, ElemType e); status SqList_delete(SqList *l, int i, ElemType *e); status SqList_traverse(SqList l); /* 文件操作 */ status SqList_writeToFile(SqList l, const char *filename); status SqList_readFromFile(SqList *l, const char *path); /* 多表操作 */ status SqList_selectList(SqList *l, SqList pool[], int *cur, int idx); /* Main */ int main(int argc, const char *argv[]) { // 初始化表池 SqList list_pool[LIST_POOL_SIZE]; // 表池 int current_list = 0; // 保存 L 在 list_pool 中的位置 int i = 0; // HACK: 重用下面的 `op` 来节省内存空间(不过也就 4 个字节。。 for (; i < LIST_POOL_SIZE; i++) { list_pool[i].elem = NULL; list_pool[i].length = 0; list_pool[i].list_size = 0; } SqList L; L.elem = NULL; L.length = 0; L.list_size = 0; // 初始化 int op=1; // 操作表示符 while (op) { system("clear"); // *nix printf("\n\n"); /* 操作选择提示 */ printf(" Menu for Linear Table On Sequence Structure\n"); printf("-------------------------------------------------\n"); printf(" 1. InitList 7. LocateElem\n"); printf(" 2. DestroyList 8. PriorElem\n"); printf(" 3. ClearList 9. NextElem\n"); printf(" 4. ListEmpty 10. ListInsert\n"); printf(" 5. ListLength 11. ListDelete\n"); printf(" 6. GetElem 12. ListTraverse\n"); printf("\n"); printf("--------------------- EXTRA ---------------------\n"); printf(" 13. WriteToFile 14. ReadFromFile\n"); printf(" 15. SelectList\n"); printf("\n"); printf(" 0. Exit\n"); printf("-------------------------------------------------\n"); printf(" 请选择你的操作[0~12]:"); scanf("%d", &op); /* 执行操作 */ switch (op) { case 1: { if (SqList_init(&L) == OK) { printf("线性表创建成功!\n"); } else { printf("线性表创建失败!\n"); } getchar(); getchar(); break; } case 2: { if (SqList_destroy(&L) == OK) { printf("线性表销毁成功!\n"); } else { printf("线性表销毁失败!\n"); } getchar(); getchar(); break; } case 3: { if (SqList_clear(&L) == OK) { printf("线性表置空成功!\n"); } else { printf("线性表置空失败!\n"); } getchar(); getchar(); break; } case 4: { int result = SqList_empty(L); if (result == TRUE) { printf("线性表为空表!\n"); } // NOTE: 由于 FALSE 和 ERROR 值均为 0 ,故当线性表还没有创建时,使用 // 该功能将同时输出“线性表还没有被创建!”和“线性表不为空表!” else if (result == FALSE) { printf("线性表不为空表!\n"); } else { printf("操作失败!\n"); } getchar(); getchar(); break; } case 5: { int ret = SqList_length(L); if (ret != ERROR) { printf("线性表表长为 %d 。\n", ret); } else { printf("获取线性表表长失败!\n"); } getchar(); getchar(); break; } case 6: { int index; ElemType result; // 函数参数 printf("请输入元素位序: "); scanf("%d", &index); int ret = SqList_getElem(L, index, &result); // 存取返回状态码 if (ret == OK) { printf("该元素值为 %d 。\n", result); } else { printf("获取元素值失败!\n"); } getchar(); getchar(); break; } case 7: { int target; printf("请输入要查找的元素的值: "); scanf("%d", &target); int ret = Sqlist_locateElem(L, target); if (ret == 0) { printf("该元素不在线性表中!\n"); } else { printf("该元素在线性表中的位序为 %d 。\n", ret); } getchar(); getchar(); break; } case 8: { ElemType current, previous; printf("请输入要目标元素的直接后继的元素值: "); scanf("%d", &current); int ret = SqList_priorElem(L, current, &previous); if (ret == OK) { printf("目标元素值为 %d 。\n", previous); } else { printf("获取目标元素失败!\n"); } getchar(); getchar(); break; } case 9: { ElemType current, next; printf("请输入要目标元素的直接前驱的元素值: "); scanf("%d", &current); int ret = SqList_nextElem(L, current, &next); if (ret == OK) { printf("目标元素值为 %d 。\n", next); } else { printf("获取目标元素失败!\n"); } getchar(); getchar(); break; } case 10: { int key; ElemType value; printf("请输入要插入元素的位置: "); scanf("%d", &key); printf("请输入要插入元素的值: "); scanf("%d", &value); if (SqList_insert(&L, key, value) == OK) { printf("成功插入元素!\n"); } else { printf("插入元素失败!\n"); } getchar(); getchar(); break; } case 11: { int key; ElemType value; printf("请输入要删除元素的位序: "); scanf("%d", &key); int ret = SqList_delete(&L, key, &value); if (ret == OK) { printf("成功删除元素,其值为 %d 。\n", value); } else { printf("删除元素失败!\n"); } getchar(); getchar(); break; } case 12: { if (!SqList_traverse(L)) { printf("线性表是空表!\n"); } getchar(); getchar(); break; } case 13: { char filename[100]; printf("请输入文件名: "); scanf("%s", filename); if (SqList_writeToFile(L, filename) == OK) { printf("成功写入文件!\n"); } else { printf("写入文件失败!\n"); } getchar(); getchar(); break; } case 14: { char filename[100]; printf("请输入文件名: "); scanf("%s", filename); int ret = SqList_readFromFile(&L, filename); if (ret == OK) { printf("成功从文件读取!\n"); } else { printf("从文件读取失败!\n"); } getchar(); getchar(); break; } case 15: { int index; printf("请输入要操作的表的位序: "); scanf("%d", &index); if (SqList_selectList(&L, list_pool, &current_list, index) == OK) { printf("切换操作表成功!\n"); } else { printf("切换操作表失败!\n"); } getchar(); getchar(); break; } case 0: { break; } // 无效操作 } // switch } // while printf("欢迎下次再使用本系统!\n"); return 0; // 这里就不返回 OK 了,不然 shell 会判异常退出的 } /*** 函数具体实现 ***/ /* * 函数名称:SqList_init * 函数参数:线性表 L 的指针 * 函数功能:构造一个空的线性表 * 返回值: 成功构造返回 OK ,否则返回 ERROR */ status SqList_init(SqList *L) { if (L->elem) { printf("该线程下已有挂载的线性表!\n"); return ERROR; } L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if (!L->elem) { return ERROR; } L->length = 0; L->list_size = LIST_INIT_SIZE; #ifdef DEBUG L->length = 10; // 直接存入随机值(初始值)用作测试数据 L->elem[2] = 1; L->elem[3] = 2; L->elem[4] = 5; #endif return OK; } /* * 函数名称:SqList_traverse * 函数参数:线性表 L * 函数功能:依次访问并显示线性表中的每个元素 * 返回值: 成功遍历返回 OK ,否则返回ERROR */ status SqList_traverse(SqList L) { if (!L.elem) { printf("线性表还没有被创建!\n"); return ERROR; } int i; printf("\n-----------all elements -----------------------\n"); for (i = 0; i < L.length; i++) { printf("%d ", L.elem[i]); } printf("\n------------------ end ------------------------\n"); return L.length; } /* * 函数名称:SqList_destroy * 函数参数:线性表 L 的指针 * 函数功能:销毁线性表 * 返回值: 成功销毁返回 OK ,否则返回 ERROR */ status SqList_destroy(SqList *l) { // 合法性检测 if (!l->elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 释放空间 free(l->elem); l->elem = NULL; l->length = 0; l->list_size = 0; return OK; } /* * 函数名称:SqList_clear * 函数参数:线性表 L 的指针 * 函数功能:重置线性表 * 返回值: 成功置空返回 OK ,否则返回 ERROR */ status SqList_clear(SqList *l) { // 合法性检测 if (!l->elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 直接将表大小置 0 l->length = 0; // 减少空间占用 if (l->list_size > LIST_INIT_SIZE) { free(l->elem); l->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if (!l->elem) { return ERROR; } } return OK; } /* * 函数名称:SqList_empty * 函数参数:线性表 L * 函数功能:判断线性表是否为空 * 返回值: 若 L 为空表则返回 TRUE ,否则返回 FALSE * 判断失败返回 ERROR */ status SqList_empty(SqList l) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } if (l.length) { return FALSE; } return TRUE; } /* * 函数名称:SqList_length * 函数参数:线性表 L * 函数功能:计算线性表 L 中数据元素的个数 * 返回值: 计算成功则返回 L 中数据元素的个数,计算失败返回 ERROR */ int SqList_length(SqList l) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 直接返回结构体中定义的表长 return l.length; // NOTE: 表长为零时返回 0 ,正好是 ERROR 的值,主函数无法区分! } /* * 函数名称:SqList_getElem * 函数参数:线性表 L ,用 e 带回第 i 个数据元素的值 * 函数功能:查找并用 e 带回第 i 个元素的值 * 返回值: 查找成功则返回 OK ,否则返回 ERROR */ status SqList_getElem(SqList l, int idx, ElemType *e) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } if (idx > l.length || idx < 1) { printf("输入地址格式不合法!\n"); return ERROR; } // 取出并赋值 *e = l.elem[idx - 1]; return OK; } /* * 函数名称:SqList_locateElem * 函数参数:线性表 L ,相比对的元素值 * 函数功能:查找 L 中数据值与 e 相同的元素所在的位序 * 返回值: 成功则返回第一个与 e 相同的元素所在的位序,不存在则返回 0, * 否则返回 ERROR */ status Sqlist_locateElem(SqList l, ElemType e) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 遍历查找元素 int idx = 1; // 直接从 1 开始加,省得后面序列转位序还要加一 for (; l.elem[idx - 1] != e; idx++) { if (idx > l.length) { return 0; } } // 找到了!返回! return idx; } /* * 函数名称:SqList_priorElem * 函数参数:线性表 L ,查找的数据 cur_e ,其前驱值用 pre_e 带回 * 函数功能:查找 L 中与 cur_e 相同的第一个数据,并用 pre_e 带回其前驱的值 * 返回值: 操作成功则返回 OK ,否则返回 ERROR */ status SqList_priorElem(SqList l, ElemType cur_e, ElemType *pre_e) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 获取 `cur_e` 位序 int idx = Sqlist_locateElem(l, cur_e); // NOTE: 重复了合法性检测 idx -= 2; // 获取 `pre_e` 对基地址的偏移量 // 第一个 -1 : 前一个元素 // 第二个 -1 : 位序转偏移量 // 检查 `cur_e` 合法性 if (idx == ERROR - 2) { printf("未找到元素值值为输入值的元素!\n"); return ERROR; } if (idx == -1) { printf("元素值为输入值的元素为表中第一个元素!\n"); return ERROR; } else { // 正常 // 给 `pre_e` 赋值 *pre_e = l.elem[idx]; return OK; } } /* * 函数名称:SqList_nextElem * 函数参数:线性表 L ,查找的数据 cur_e ,其后继值用 next_e 带回 * 函数功能:查找 L 中与 cur_e 相同的第一个数据,并用 next_e 带回其后继的值 * 返回值: 操作成功则返回 OK ,否则返回 ERROR */ status SqList_nextElem(SqList l, ElemType cur_e, ElemType *next_e) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 获取 `cur_e` 位序 int idx = Sqlist_locateElem(l, cur_e); // idx = idx + 1 - 1; // 类似于 SqList_priorElem 中的操作,但恰好不改变元素值 // 检查 `cur_e` 合法性 if (idx == ERROR) { printf("未找到元素值值为输入值的元素!\n"); return ERROR; } if (idx == l.length) { printf("元素值为输入值的元素为表中最后一个元素!\n"); return ERROR; } else { // 正常 // 给 `next_e` 赋值 *next_e = l.elem[idx]; return OK; } } /* * 函数名称:SqList_insert * 函数参数:线性表 L 的地址,插入的位置 i ,插入的数据元素 e * 函数功能:在 L 的第 i 个位置之前插入新的数据元素 e * 若已插满,则按照分配增量,分配更大的空间,再插入 * 返回值: 成功插入返回 OK ,否则返回 ERROR */ status SqList_insert(SqList *l, int i, ElemType e) { // 合法性检测 if (!l->elem) { printf("线性表还没有被创建!\n"); return ERROR; } // - `i` 范围限制 if ((l->length == 0 && i != 1) // 空表 || (l->length > 0 && (i < 1 || i > l->length))) { // 非空表,`i`应有范围 printf("输入地址格式不合法!\n"); return ERROR; } // 空间是否已满? if (l->length == l->list_size) { // 扩充空间 l->list_size += LIST_INC_SIZE; // 将数据移动到空间更宽裕的地方 l->elem = (ElemType *)realloc(l->elem, l->list_size); if (!l->elem) { return OVERFLOW; } // 检查 } // 移动插入位置之后的所有元素 i--; // 转化为偏移量 int bak_ptr = l->length - 1; for (; bak_ptr >= i; bak_ptr--) { l->elem[bak_ptr + 1] = l->elem[bak_ptr]; } // 给目标位置赋值 l->elem[i] = e; // 扩充可见表长 l->length += 1; return OK; } /* * 函数名称:SqList_delete * 函数参数:线性表 L 的地址,删除的位序 i ,带回数据的指针 e * 函数功能:删除 L 的第 i 个数据元素,用 e 返回其值 * 若可以缩小分配增量所指明的空间,则重新分配更小的空间 * 返回值: 成功删除返回 OK ,否则返回 ERROR */ status SqList_delete(SqList *l, int i, ElemType *e) { // 合法性检测 if (!l->elem) { printf("线性表还没有被创建!\n"); return ERROR; } if (i < 1 || i > l->length) { printf("输入地址格式不合法!\n"); return ERROR; } // 删除元素值带出 i--; l->length -= 1; *e = l->elem[i]; // 删除位置后元素依次前移 for (; i < l->length; i++) { l->elem[i] = l->elem[i + 1]; } // 检查是否可以减小容量 // HACK: 与上一步进行合并可以减小时间消耗 if (l->list_size - l->length > LIST_INC_SIZE) { l->elem = (ElemType *)realloc(l->elem, (l->list_size - LIST_INC_SIZE) * sizeof(ElemType)); if (!l->elem) { return ERROR; } } return OK; } /* * 函数名称:SqList_saveList * 函数参数:文件指针 fp ,线性表 L * 函数功能:将 L 中的数据保存到 fp 指向的文件中 * 返回值: 成功保存返回 OK ,否则返回 ERROR */ status SqList_saveList(FILE *fp, SqList l) { /* * 配合 API 用的 wrapper */ if (!fp) { return ERROR; } // NOTE: **假设** 传进来的 fp 是已打开的文件 if (!l.elem) { return ERROR; } fwrite(l.elem, sizeof(ElemType), l.length, fp); return OK; } status SqList_writeToFile(SqList l, const char *filename) { // 合法性检测 if (!l.elem) { printf("线性表还没有被创建!\n"); return ERROR; } // 创建文件 FILE *fp; if ((fp = fopen(filename, "w")) == NULL) { printf("不能够创建文件!\n"); return ERROR; } // 写入 if (SqList_saveList(fp, l) != OK) { /* pass */ return ERROR; } fclose(fp); return OK; // 释放句柄并返回 } /* * 函数名称:SqList_loadList * 函数参数:文件指针 fp ,线性表 L 的地址 * 函数功能:将 fp 指向文件中的数据,加载到线性表 L 中 * 返回值: 加载成功返回 OK ,加载失败返回 ERROR */ status SqList_loadList(FILE *fp, SqList *l) { /* * 配合 API 用的 wrapper */ if (!fp) { return ERROR; } if (l->elem) { return ERROR; } // 不允许覆盖正挂载的表 // 初始化挂载结构体 // - 获取文件大小 fseek(fp, 0, SEEK_END); size_t filesize = ftell(fp) / sizeof(ElemType); fseek(fp, 0, SEEK_SET); // - 必要时创建空间 if ((!l->elem) || l->length < filesize) { // 没有空间 或 空间太小 if (l->elem) { free(l->elem); } // NOTE: 这个分支不会执行! // 已禁止覆盖挂载表的操作! l->elem = (ElemType *)malloc(filesize * sizeof(ElemType)); if (!l->elem) { return ERROR; } } // 一次性读取文件内容 l->length = filesize; l->list_size = filesize; fread(l->elem, sizeof(ElemType), filesize, fp); return OK; } status SqList_readFromFile(SqList *l, const char *path) { // 检查是否已有表挂载 if (l->elem) { printf("已有挂载的线性表!\n"); return ERROR; } // 打开文件 FILE *fp; if ((fp = fopen(path, "r")) == NULL) { printf("不能够读取文件!\n"); return ERROR; } // 读取 if (SqList_loadList(fp, l) != OK) { /* pass */ return ERROR; } return OK; } /* * 函数名称:SqList_selectList * 函数参数:线性表 L 的地址,多表数组 pool , * 存放 L 在 pool 中位置的 current_list (0-下标)的地址, * 要切换到的线性表在 pool 中的位序 idx (1-下标) * 函数功能:切换工作表到 pool 中第 idx 个线性表 * 返回值: 成功切换返回 OK ,否则返回 ERROR */ status SqList_selectList(SqList *l, SqList pool[], int *current_list, int idx) { // 合法性检测 if (idx < 1 || idx > LIST_POOL_SIZE) { printf("输入地址格式不合法!\n"); return ERROR; } idx--; // 位序转偏移量 // 向池中存储表数据 pool[*current_list] = *l; // 加载目标表数据 // NOTE: 由于 `L` 不是 malloc 出来的,不能直接改变其指向 l->elem = pool[idx].elem; l->length = pool[idx].length; l->list_size = pool[idx].list_size; // 改动表指针 *current_list = idx; return OK; }
C
#include "lists.h" /** * list_len - lists # of links in linked lists * @h: pointer to the head of the list * * Return: the number of nodes */ size_t list_len(const list_t *h) { int ret = 0; const list_t *temp; temp = h; while (temp != NULL) { temp = temp->next; ret++; } return (ret); }
C
#include <stdio.h> #include <stdlib.h> int GenerateLotteryNumbers(int array[]); int DisplayLotteryNumbers(int array[]); int main() { int numArray[6]; GenerateLotteryNumbers(numArray); DisplayLotteryNumbers(numArray); return 0; } int GenerateLotteryNumbers(int array[]){ srand(time(NULL)); for(int i=0; i<=5; i++){ array[i] = (rand() % S49 )+ 1; printf("%d\n", array[i]); } } int DisplayLotteryNumbers(int array[]){ for(int i=0; i<=5; i++){ printf("%d\n", array[i]); } }
C
#include <stdio.h> //#define scanf scanf_s borlandȂKv void main(void) { int age; printf("N͂ĂF"); scanf("%d", &age); if (age >= 10 && age < 20){ printf("Ȃ 10 łˁI\n"); } else { printf("Ȃ 10 ł͂܂ˁB\n"); } }
C
#include <stdio.h> int main() { int a, b, c; scanf("%d %d %d", &a, &b, &c); if (a > b) { if (b < c) { if (a > c) printf("%d", c); else printf("%d", a); } else printf("%d", b); } else { //a < b, a==b if (b > c) { if (a > c) printf("%d", a); else printf("%d", c); } else printf("%d", b); } return 0; }
C
#include "delay.h" void delay_for_1000_nops_x (uint16_t n) { while (n --) { int i; for (i = 0; i < 1000; i++) asm volatile ("nop"); } } void delay_for_1000_nops () { delay_for_1000_nops_x (1); } // The following function is adopted from // Digital Design and Computer Architecture // by David Harris & Sarah Harris void delay_micros (uint16_t n) { const uint16_t function_overhead = 6; while (n > 1000) // To avoid timer overflow { delay_micros (1000); n -= 1000; } if (n > function_overhead) { T2CONCLR = 0xFFFFFFFF; IFS0CLR = 0x00000200; TMR2 = 0; PR2 = (n - function_overhead) * (PBCLK_FREQUENCY / 1000) / 1000; T2CONSET = 0x00008000; while (!IFS0bits.T2IF) // Wait until overflow flag is set ; } } void delay_millis (uint16_t n) { while (n --) delay_micros (1000); } void delay_seconds (uint16_t n) { while (n --) delay_millis (1000); }
C
#include <stdio.h> #include <pthread.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> pthread_t t1,t2; sigset_t sigs; pthread_cond_t cond; pthread_mutex_t m; void handle(int s) { } void *r1(void *d) { int s; while(1) { pthread_cond_wait(&cond,&m); // sigwait(&sigs,&s); printf("active!\n"); // pause(); } } void *r2(void *d) { while(1) { sleep(1); pthread_cond_signal(&cond); // pthread_kill(t1,34); } } int main() { pthread_mutex_init(&m,0); pthread_cond_init(&cond,0); // sigemptyset(&sigs); // sigaddset(&sigs,34); signal(34,handle); pthread_create(&t1,0,r1,0); pthread_create(&t2,0,r2,0); pthread_join(t1,(void**)0); pthread_join(t2,(void**)0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&m); }
C
#pragma once #include "Basic.h" #include <stdbool.h> //ջ typedef struct { bool present; //Ƿ bool connected; //Ƿ bool available; //Ƿ TIME last_update_time; //ϴθʱ float update_time; //ʱ float raw_data[16]; //ԭʼ float data[8]; //У׼ }Receiver; #define Receivers_Count 3 typedef enum { RC_Type_Sbus = 0 , RC_Type_PPM = 1 , }RC_Type; //ȡָĽջ const Receiver* get_Receiver( RC_Type rc ); //ȡǰʹõĽջ const Receiver* get_current_Receiver(); //ȡǰʹõĽջ RC_Type get_current_Receiver_Type();
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <mqtt.h> #ifdef WIN32 #include <ws2tcpip.h> #endif #ifdef LINUX #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <fcntl.h> #endif struct mqtt_client client; void publish_callback(void **unused, struct mqtt_response_publish *published); void print_help(char *name) { printf("Usage: %s flags\n", name); printf("-h print help\n"); printf ("-a address specify IP address of the server (test.mosquitto.org)\n"); printf("-p port specify port of the server (1883)\n"); printf("-t topic specify topic (datetime)\n"); printf("-m message message to send (hello)\n"); printf("-d delay specify delay in seconds between messages (0)\n"); printf("-l continuous loop\n"); fflush(stdout); exit(1); } int main(int argc, const char *argv[]) { char *message = "hello"; char *topic = "datetime"; int loopit = 0; int delay = 0; int i = 1; int port = 1883; char *address = "test.mosquitto.org"; setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); while (i < argc) { if (strcmp(argv[i], "-h") == 0) { print_help(argv[0]); } else if (strcmp(argv[i], "-l") == 0) { loopit = 1; } else if (strcmp(argv[i], "-m") == 0) { if (++i < argc) message = argv[i]; else print_help(argv[0]); } else if (strcmp(argv[i], "-d") == 0) { if (++i < argc) delay = atoi(argv[i]); else print_help(argv[0]); } else if (strcmp(argv[i], "-a") == 0) { if (++i < argc) address = argv[i]; else print_help(argv[0]); } else if (strcmp(argv[i], "-t") == 0) { if (++i < argc) topic = argv[i]; else print_help(argv[0]); } else { print_help(argv[0]); } i++; } printf ("Will connect to MQTT broker at addr %s at port %d on topic %s\n", address, port, topic); #ifdef WIN32 WSADATA wsaData; int res = WSAStartup(MAKEWORD(2, 2), &wsaData); if (res != NO_ERROR) { printf("WSAStartup failed\n"); exit(1); } #endif int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("Failed to open socket: "); exit(1); } struct hostent *host; struct sockaddr_in sin; host = gethostbyname(address); if (!host) { perror("error: can't gethostbyname"); exit(1); } sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = *(long *)(host->h_addr_list[0]); printf("%s\n", inet_ntoa(sin.sin_addr)); if (connect(sockfd, (struct sockaddr *)&sin, sizeof(sin)) != 0) { close(sockfd); perror("error: can't connect"); exit(1); } #ifdef WIN32 int on = 1; ioctlsocket(sockfd, FIONBIO, &on); #endif #ifdef LINUX fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL) | O_NONBLOCK); #endif uint8_t sendbuf[2048]; uint8_t recvbuf[1024]; mqtt_init(&client, sockfd, sendbuf, sizeof(sendbuf), recvbuf, sizeof(recvbuf), publish_callback); const char *client_id = NULL; uint8_t connect_flags = MQTT_CONNECT_CLEAN_SESSION; mqtt_connect(&client, client_id, NULL, NULL, 0, NULL, NULL, connect_flags, 400); if (client.error != MQTT_OK) { fprintf(stderr, "error: %s\n", mqtt_error_str(client.error)); exit(1); } char hostname[200]; gethostname(hostname, sizeof(hostname)); mqtt_subscribe(&client, topic, 0); printf("subscribed to the topic %s\n", topic); do { if (strcmp(message, "none") != 0) { mqtt_publish(&client, topic, message, strlen(message) + 1, MQTT_PUBLISH_QOS_0); if (client.error != MQTT_OK) { fprintf(stderr, "error: %s\n", mqtt_error_str(client.error)); exit(1); } } mqtt_sync(&client); sleep(delay); } while (loopit); mqtt_sync(&client); printf("\n%s disconnecting from %s\n", argv[0], address); sleep(1); exit(0); } void publish_callback(void **unused, struct mqtt_response_publish *published) { /* note that published->topic_name is NOT null-terminated */ char *topic_name = (char *)malloc(published->topic_name_size + 1); memcpy(topic_name, published->topic_name, published->topic_name_size); topic_name[published->topic_name_size] = '\0'; printf("\nReceived publish('%s'): %s\n", topic_name, (const char *)published->application_message); free(topic_name); }
C
#ifndef DE #define DE #include <stdio.h> #include <stdlib.h> #endif struct { unsigned int is_keyword:1; unsigned int is_extern:1; unsigned int is_static:1; unsigned int is_static1:1; unsigned int is_static2:1; unsigned int is_static3:1; unsigned int is_static4:1; unsigned int is_static5:1; unsigned int is_static6:1; unsigned int is_static7:1; unsigned int is_static8:1; unsigned int is_static9:1; unsigned int is_static10:1; unsigned int is_static11:1; unsigned int is_static12:1; unsigned int is_static13:1; unsigned int is_static14:1; unsigned int is_static15:1; unsigned int is_static16:1; unsigned int is_static17:1; unsigned int is_static18:1; unsigned int is_static19:1; unsigned int is_static20:1; unsigned int is_static21:1; unsigned int is_static22:1; unsigned int is_static23:1; unsigned int is_static24:1; unsigned int is_static25:1; unsigned int is_static26:1; unsigned int is_static27:1; unsigned int is_static28:1; unsigned int is_static29:1; }flag; int main(void) { flag.is_keyword = 1; flag.is_extern = 1; flag.is_static = 0; printf("flag.is_keyword = %d\n",flag.is_keyword); printf("flag.is_extern = %d\n",flag.is_extern); printf("flag.is_static = %d\n",flag.is_static); printf("sizeof flag is = %d\n",sizeof flag); return 0; }
C
Node *new_node(PyObject *key, PyObject *data) { /* Initializes a new Node. Inputs: key - The key to assign to the node. data - An optional dictionary (or None) of attributes to associate with the node. Outputs: A pointer to the newly created node object, or NULL if an error occurred. */ Node *node; if ((node = PyObject_New(Node, &NodeType)) == NULL) return NULL; PyErr_Clear(); PyObject_Init((PyObject *)node, &NodeType); if (PyErr_Occurred() != NULL) { PyObject_Del(node); return NULL; } node->key = key; node->data = data; node->parent = NULL; SET_LEFT(node, NULL); SET_RIGHT(node, NULL); Py_INCREF(key); Py_XINCREF(data); return node; } void _node_set_child(Node *self, Node *child, unsigned char side) { /* Sets a child of the given node. This function should not be used directly. Instead, use one of the macros: SET_LEFT(node, left), SET_RIGHT(node, right), SET_CHILD(node, child, side). Inputs: self - The node to set the child of. child - The node to set as the child. side - A boolean indicating which side the child should be set on. See bst.h for defines */ if (child != NULL) child->parent = self; if (self != NULL) { if (side == LEFT) { self->left = child; } else { self->right = child; } } } void _node_single_rotation(Node *self, unsigned char dir) { /* Rotates a node to the left or right. This function should not be used directly. Instead use the macros: ROTATE_LEFT(node), ROTATE_RIGHT(node), ROTATE(node, direction). Inputs: self - The first pivot node to rotate. Note that neither this, nor the other pivot can be NULL. dir - A boolean indicating which direction the node will be rotated. See bst.h for defines */ Node *pivot = GET_OTHER_CHILD(self, dir), *parent = GET_PARENT(self); unsigned char parentSide = CHILD_TYPE(self); if (dir == LEFT) { SET_RIGHT(self, GET_LEFT(pivot)); SET_LEFT(pivot, self); } else { SET_LEFT(self, GET_RIGHT(pivot)); SET_RIGHT(pivot, self); } SET_CHILD(parent, pivot, parentSide); }
C
#ifndef MAZE_LIST_H #define MAZE_LIST_H #include "point.h" typedef struct { int size; Node *first; Node *last; } List; List *createList(); int insertStart(List *l, Point point); int insertEnd(List *l, Point point); int contains(List *l, Point point); int getItem(List *l, int position, Point *point); int isEmptyList(List *l); int getListSize(List *l); void destroyList(List *l); void clearList(List *l); const Point *peekList(List *l); #endif //MAZE_LIST_H
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/sysinfo.h> #include <mpi.h> #include <omp.h> int m1[SIZE][SIZE],m2[SIZE][SIZE],mres[SIZE][SIZE]; int l1, c1, l2, c2, lres, cres; void initializeMatrices() { int i, j, k; l1 = c1 = SIZE; l2 = c2 = SIZE; lres = l1; cres = c2; k=1; for (i=0 ; i<SIZE; i++) { for (j=0 ; j<SIZE; j++) { if (k%2==0) m1[i][j] = -k; else m1[i][j] = k; } k++; } k=1; for (j=0 ; j<SIZE; j++) { for (i=0 ; i<SIZE; i++) { if (k%2==0) m2[i][j] = -k; else m2[i][j] = k; } k++; } } int validateMatrix(){ int i, j, k; for (i=0 ; i<SIZE; i++) { k = SIZE*(i+1); for (j=0 ; j<SIZE; j++) { int k_col = k*(j+1); if (i % 2 ==0) { if (j % 2 == 0) { if (mres[i][j]!=k_col){ printf("\nF1"); MPI_Finalize(); return 0; } } else { if (mres[i][j]!=-k_col){ printf("\nF2"); MPI_Finalize(); return 0; } } } else { if (j % 2 == 0) { if (mres[i][j]!=-k_col){ printf("\nF3"); MPI_Finalize(); return 0; } } else { if (mres[i][j]!=k_col){ printf("\nF4"); MPI_Finalize(); return 0; } } } } } return 1; } int main(int argc, char *argv[]) { int i, j, k, n, f, rank, nprocs, name_len, offset, rows_per_proccess, cores; double elapsed_time; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Get_processor_name(processor_name, &name_len); // PREPARA PARA MEDIR TEMPO elapsed_time = - MPI_Wtime (); if(rank == 0){ // INICIALIZA OS ARRAYS A SEREM MULTIPLICADOS initializeMatrices(); //printf("\n rank: %d", rank); offset = 0; for(n=1; n < nprocs; n++){ //Send name MPI_Send(&processor_name, MPI_MAX_PROCESSOR_NAME, MPI_UNSIGNED_CHAR, n, 1, MPI_COMM_WORLD); //Receive number of cores MPI_Recv(&cores, 1, MPI_INT, n, 8, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Send second matrix MPI_Send(&m2, SIZE*SIZE, MPI_INT, n, 2, MPI_COMM_WORLD); //Send offset MPI_Send(&offset, 1, MPI_INT, n, 3, MPI_COMM_WORLD); //Send rows per proccess rows_per_proccess = SIZE / (nprocs-1); if(n == (nprocs-1) && (rows_per_proccess * (nprocs-1)) < SIZE ){ rows_per_proccess = SIZE-offset; } int rows[cores][SIZE]; MPI_Send(&rows_per_proccess, 1, MPI_INT, n, 4, MPI_COMM_WORLD); int r = 0; int o = 0; int k = 0; //printf("\n rows_per_proccess: %d", rows_per_proccess); //printf("\n cores: %d", cores); while(r < rows_per_proccess){ //printf("\n r: %d, o: %d, k:%d", r,o,k); k = 0; for(i=o; i < (o+cores); i++){ for(j=0; j<SIZE; j++) { rows[k][j] = m1[i][j]; } k++; } MPI_Send(&rows, cores*SIZE, MPI_INT, n, 5, MPI_COMM_WORLD); int res[cores][SIZE]; //MPI_Recv(&res, rows_per_proccess*SIZE, MPI_INT, n, 6, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Insert results into mres matrix for(i=o; i < cores; i++){ for(j=0; j<SIZE; j++) mres[offset+i][j] = res[i][j]; } r = r + cores; o = o + cores; } /* for (i=0 ; i<SIZE; i++) { for (j=0 ; j<SIZE; j++) { printf(" %d ", mres[i][j]); if (j == SIZE-1) printf("\n"); } } */ //Send first matrix rows /* k = 0; for(i=offset; i < (offset+rows_per_proccess); i++){ for(j=0; j<SIZE; j++) { rows[k][j] = m1[i][j]; } k++; } */ /* for (i=0 ; i<SIZE; i++) { for (j=0 ; j<SIZE; j++) { printf(" %d ", rows[i][j]); if (j == SIZE-1) printf("\n"); } } */ //MPI_Send(&rows, rows_per_proccess*SIZE, MPI_INT, n, 5, MPI_COMM_WORLD); offset = offset+rows_per_proccess; } /* int slave_offset; for(n=1; n < nprocs; n++){ //Receive offset MPI_Recv(&slave_offset, 1, MPI_INT, n, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Receive rows per process MPI_Recv(&rows_per_proccess, 1, MPI_INT, n, 9, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("\n n: %d, offset: %d, rows per process: %d", n, slave_offset, rows_per_proccess); //Receive result int res[rows_per_proccess][SIZE]; MPI_Recv(&res, rows_per_proccess*SIZE, MPI_INT, n, 6, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Insert results into mres matrix for(i=0; i < rows_per_proccess; i++){ for(j=0; j<SIZE; j++) mres[slave_offset+i][j] = res[i][j]; } } */ /* for (i=0 ; i<SIZE; i++) { for (j=0 ; j<SIZE; j++) { printf(" %d ", mres[i][j]); if (j == SIZE-1) printf("\n"); } } */ // VERIFICA SE O RESULTADO DA MULTIPLICACAO ESTA CORRETO /* if(!validateMatrix()){ MPI_Finalize(); return 1; } */ // OBTEM O TEMPO elapsed_time += MPI_Wtime (); // MOSTRA O TEMPO DE EXECUCAO printf("\nelapsed_time: %lf",elapsed_time); }else{ int cores; char slave_processor_name[MPI_MAX_PROCESSOR_NAME]; //Receive name MPI_Recv(&processor_name, MPI_MAX_PROCESSOR_NAME, MPI_UNSIGNED_CHAR, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Send cores to use MPI_Get_processor_name(slave_processor_name, &name_len); cores = get_nprocs(); if (strcmp(processor_name, slave_processor_name) == 0) cores = get_nprocs()-1; MPI_Send(&cores, 1, MPI_INT, 0, 8, MPI_COMM_WORLD); //Receive sencond matrix MPI_Recv(&m2, SIZE*SIZE, MPI_INT, 0, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Receive offset MPI_Recv(&offset, 1, MPI_INT, 0, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //Receive rows per proccess MPI_Recv(&rows_per_proccess, 1, MPI_INT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //printf("\n rank: %d, offset: %d, rows: %d", rank, offset, rows_per_proccess); int r = 0; int o = 0; int k = 0; int x = 0; int rows[cores][SIZE]; int rows_to_multiply[cores][SIZE]; int msres[cores][SIZE]; omp_set_num_threads(cores); while(r < rows_per_proccess){ MPI_Recv(&rows, cores*SIZE, MPI_INT, 0, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for(i=0; i < cores; i++){ for(j=0; j<SIZE; j++) rows_to_multiply[k][j] = rows[i][j]; k++; } // REALIZA A MULTIPLICACAO i = 0; j = 0; # pragma omp parallel for private (i,j) for (i=0 ; i<rows_per_proccess; i++) { for (j=0 ; j<SIZE; j++) { # pragma omp critical { msres[i][j] = 0; for (x=0 ; x<SIZE; x++) msres[i][j] += rows_to_multiply[i][x] * m2[x][j]; } } } for (i=0 ; i<cores; i++) { for (j=0 ; j<SIZE; j++) { printf(" %d ", msres[i][j]); if (j == SIZE-1) printf("\n"); } } printf("\n---\n"); //MPI_Send(&msres, cores*SIZE, MPI_INT, 0, 6, MPI_COMM_WORLD); r = r + cores; o = o + cores; } /* printf("\n"); for (i=0 ; i<SIZE; i++) { for (j=0 ; j<SIZE; j++) { printf(" %d ", rows_to_multiply[i][j]); if (j == SIZE-1) printf("\n"); } } */ //Receive first matrix rows /* int rows[rows_per_proccess][SIZE]; int msres[rows_per_proccess][SIZE]; MPI_Recv(&rows, rows_per_proccess*SIZE, MPI_INT, 0, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* omp_set_num_threads(cores); // REALIZA A MULTIPLICACAO # pragma omp parallel for private (i,j) for (i=0 ; i<rows_per_proccess; i++) { for (j=0 ; j<SIZE; j++) { # pragma omp critical { msres[i][j] = 0; for (k=0 ; k<SIZE; k++) { msres[i][j] += rows[i][k] * m2[k][j]; } } } } //Send offset to master MPI_Send(&offset, 1, MPI_INT, 0, 3, MPI_COMM_WORLD); //Send rows per process MPI_Send(&rows_per_proccess, 1, MPI_INT, 0, 9, MPI_COMM_WORLD); //Send msres to master MPI_Send(&msres, rows_per_proccess*SIZE, MPI_INT, 0, 6, MPI_COMM_WORLD); */ } //printf("\n >> Rank %d finalizing", rank); MPI_Finalize(); return 0; }
C
#include <stdio.h> int main(void) { int i = 0; float height[5] = {0}; float average = 0.0; float sum = 0.0; for(i = 0;i < 5;i ++) { printf("pls input the height of student%d:\n",i+1); scanf("%f",&height[i]); } for(i = 0;i < 5;i ++) { printf("student%d:%.2f\n",i+1,height[i]); } for(i = 0;i < 5;i ++) { sum = sum + height[i]; //sum += height[i]; } average = sum/5; printf("average = %.2f.\n",average); return 0; }
C
#include "video.h" #include <SDL2/SDL.h> #include <stdio.h> static SDL_Window *window = NULL; static SDL_Renderer * renderer = NULL; int video_init(bool fullscreen, int w, int h) { fprintf(stderr, "Initializing video subsystem ...\n"); // Set up video window int flags = fullscreen ? SDL_WINDOW_FULLSCREEN : 0; window = SDL_CreateWindow( "Utuclient v2.0", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags); if(!window) { fprintf(stderr, "Unable to set up video window: %s\n", SDL_GetError()); goto exit_0; } // Set up a renderer renderer = SDL_CreateRenderer( window, -1, // Dev indec (any) SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); if(!renderer) { fprintf(stderr, "Unable to set up a renderer: %s\n", SDL_GetError()); goto exit_1; } // Print out renderer information SDL_RendererInfo info; SDL_GetRendererInfo(renderer, &info); fprintf(stderr, " * Renderer: %s\n", info.name); // Check flags if(info.flags & SDL_RENDERER_SOFTWARE) fprintf(stderr, " * Using SDL_RENDERER_SOFTWARE\n"); if(info.flags & SDL_RENDERER_ACCELERATED) fprintf(stderr, " * Using SDL_RENDERER_ACCELERATED\n"); if(info.flags & SDL_RENDERER_PRESENTVSYNC) fprintf(stderr, " * Using SDL_RENDERER_PRESENTVSYNC\n"); if(info.flags & SDL_RENDERER_TARGETTEXTURE) fprintf(stderr, " * Using SDL_RENDERER_TARGETTEXTURE\n"); // Texture limits fprintf(stderr, " * Texture size limit: %d x %d\n", info.max_texture_width, info.max_texture_height); // All done. return 0; exit_1: SDL_DestroyWindow(window); exit_0: return 1; } void video_close() { fprintf(stderr, "Closing video subsystem.\n"); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); renderer = NULL; window = NULL; } int video_init_surface(video_surface *surface, int w, int h) { SDL_Texture *tex = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, w, h); if(!tex) { fprintf(stderr, "video: Unable to allocate a new texture\n"); return 1; } surface->sfc = tex; surface->w = w; surface->h = h; fprintf(stderr, "video: Initialized %dx%d texture.\n", w, h); return 0; } int video_copy_to_surface(video_surface *surface, const unsigned char* data) { SDL_Texture *tex = (SDL_Texture*)surface->sfc; unsigned char* pixels; int pitch; // Lock texture, copy data over, unlock. if(SDL_LockTexture(tex, NULL, (void**)&pixels, &pitch) == 0) { memcpy(pixels, data, pitch * surface->h); SDL_UnlockTexture(tex); } else { fprintf(stderr, "video: Unable to lock texture for streaming access.\n"); return 1; } return 0; } void video_free_surface(video_surface *surface) { fprintf(stderr, "video: Texture freed.\n"); SDL_DestroyTexture((SDL_Texture*)surface->sfc); surface->w = 0; surface->h = 0; } void video_render_surface(video_surface *surface) { SDL_RenderCopy(renderer, (SDL_Texture*)surface->sfc, NULL, NULL); } void video_present_start() { SDL_RenderClear(renderer); } void video_present_finish() { SDL_RenderPresent(renderer); }
C
/*------------------------------------------------------------------------- * * zlib_wrapper.c * Wrapper functions for zlib to provide better integration with GPDB * * Greenplum Database * Copyright (c) 2016-Present Pivotal Software, Inc. * * * IDENTIFICATION * src/backend/utils/misc/zlib_wrapper.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "utils/palloc.h" #include "utils/zlib_wrapper.h" /* * Wrapper for palloc to be passed into zlib. */ static voidpf gp_zpalloc (voidpf opaque, unsigned items, unsigned size) { return (voidpf) palloc(items * size); } /* * Wrapper for pfree to be passed into zlib. */ static void gp_zpfree (voidpf opaque, voidpf ptr) { pfree(ptr); } /* =========================================================================== Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int gp_uncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) { return Z_BUF_ERROR; } stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) { return Z_BUF_ERROR; } stream.zalloc = (alloc_func)gp_zpalloc; stream.zfree = (free_func)gp_zpfree; err = inflateInit(&stream); if (err != Z_OK) { return err; } err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) { return Z_DATA_ERROR; } return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } /* * compressBound doesn't exist in older zlibs, so let's use our own */ unsigned long gp_compressBound(unsigned long sourceLen) { return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; } /* =========================================================================== Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ int gp_compress2(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level) { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; #ifdef MAXSEG_64K /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) { return Z_BUF_ERROR; } #endif stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) { return Z_BUF_ERROR; } stream.zalloc = (alloc_func)gp_zpalloc; stream.zfree = (free_func)gp_zpfree; stream.opaque = (voidpf)0; err = deflateInit(&stream, level); if (err != Z_OK) { return err; } err = deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { deflateEnd(&stream); return err == Z_OK ? Z_BUF_ERROR : err; } *destLen = stream.total_out; err = deflateEnd(&stream); return err; } /* =========================================================================== */ int gp_compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { return gp_compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); } /* EOF */
C
#define MAX 20 void sort(int[],int); void main(void) { int list[MAX]; int size=0; int dex; do { printf("Enter Number"); scanf("%d",&list[size]); } while(list[size++]!=0); sort(list,--size); for(dex=0;dex<size;dex++) printf("%d\n",list[dex]); } void sort(int list[],int size) { int out,in,temp; for(out=0;out<size-1;out++) for(in=out+1;in<size;in++) if(list[out]>list[in]) { temp=list[in]; list[in]=list[out]; list[out]=temp; } }
C
#include<stdio.h> int main(){ int leanth, breath; printf("Enter the value of leanth\n"); scanf("%d", &leanth); printf("Enter the value of breath\n"); scanf("%d", &breath); printf("Area of the rectange is %d \n", leanth*breath); return 0; }
C
#include "systime.h" void time_Init(void) { time.ms = 0; time.callback = NULL; TCCR3A = TCCR3B = 0; TIMSK3 = 0; // Configure timer 3 to overflow each ms TCCR3B |= (1 << WGM32); // CTC mode OCR3A = 249; // 250 counts to overflow TCCR3B |= (1 << CS31) | (1 << CS30); // prescaler = 64 TIMSK3 |= (1 << OCIE3A); // enable timer overflow interrupt } void time_RegisterCallback(void (*callback)(void)) { time.callback = callback; } uint32_t time_Getms(void) { TIMSK2 &= ~(1 << OCIE2A);// block timer interrupt to avoid data corruption uint32_t ret = time.ms; TIMSK2 |= (1 << OCIE2A); return ret; } void time_Waitms(uint16_t ms) { uint32_t start = time_Getms(); while (time_Getms() < start + ms) ; } ISR(TIMER3_COMPA_vect) { // timer 3 overflowed -> 1 ms has passed time.ms++; if (time.beep) { PORTB ^= (1 << PB3); } else { PORTB &= ~(1 << PB3); } static uint8_t cnt = 0; cnt++; if (cnt >= 10) { if (time.callback) time.callback(); } }
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #include "aid.h" #define MAXLINE 1000 #define MAXVARS 26 struct { char infix[MAXLINE]; char postfix[MAXLINE]; char vnum[MAXVARS]; // stores on which place stands i-th var (if stands >=0) char letter[MAXVARS]; // stores which letter stands in i-th place in table sets char nvars; } typedef Expression; #define ORDER_ALPHA 0 // alphabetic order #define ORDER_EXPR 1 // vars go as they appear in expression #define ORDER_RAND 2 // random order void initExpression(Expression *expr); int infixToPostfix(Expression *expr); void setOrder(Expression *expr, int order_type); void makeTableTXT(Expression expr); char eval(Expression expr, char *set); // vars for stack #define MAXSTACK 200 char stk[MAXSTACK]; char *sp = stk; // methods for stack char pop(); void push(char c); void printStk(); // has been used for debug int stackEmpty(); int topOp(); void resetStack(); int fgetline(FILE *f, char *dest, int lim); // all for operations #define EMPTY ' ' #define NEG '!' #define NEG2 '~' #define AND '*' #define OR '+' #define XOR '^' #define THEN '>' #define EQ '=' int priority(char c); // returns relative priority of an operation // some things for list struct node { char val; struct node *next; } typedef Node; // list made to be with first fictive element, for simplicity Node* initList(); void addNode(Node *head, char c); char extractNode(Node *head, int n); void printList(Node *head); // has been used for debug //======================================// // DEFINITION // //======================================// int main(int argc, char const *argv[]) { Expression e; initExpression(&e); //setOrder(&e,ORDER_RAND); makeTableTXT(e); return 0; } void initExpression(Expression *expr) { // read line from file FILE *f; f = fopen("input.txt","r"); if (f==NULL){ fprintf(stderr, "No input file! Expression must be in input.txt\nDefault expression used\n"); *(expr->infix)=NEG; *(expr->infix+1)='A'; *(expr->infix+2)='\0'; } else{ fgetline(f,expr->infix,MAXLINE); fclose(f); } *(expr->postfix)='\0'; // impossimble numbers for each var for(int i=0; i<MAXVARS; i++){ expr->vnum[i]=-1; expr->letter[i]=-1; } expr->nvars=0; setOrder(expr,ORDER_ALPHA); // alphabetic order by default, can be reset later infixToPostfix(expr); } int fgetline(FILE *f, char *dest, int lim) { int i; char *tp = dest; char c; for(i=0; i<lim-1 && (c=fgetc(f))!='\n' && c!=EOF; i++){ *tp=c; tp++; } *tp='\0'; return i; } int infixToPostfix(Expression *expr) { char *tp = expr->infix; char *mp = expr->postfix; char op1; char op2 = EMPTY; // HACK: EMPTY has the highest priority, so it will not be pushed in the beginning // Implementation of the Shunting-yard algotithm while((op1=*tp)!='\0'){ if(isalpha(op1)){ *mp=toupper(op1); mp++; } else switch(op1){ case NEG: case NEG2:{ push(op1); break; } case AND:{ while( topOp() && priority(op2=pop())>=priority(AND) ){ *mp = op2; mp++; } if(priority(op2)<priority(op1)) push(op2); push(AND); break; } case OR:{ while( topOp() && priority(op2=pop())>=priority(OR) ){ *mp = op2; mp++; } if(priority(op2)<priority(op1)) push(op2); push(OR); break; } case XOR:{ while( topOp() && priority(op2=pop())>=priority(XOR) ){ *mp = op2; mp++; } if(priority(op2)<priority(op1)) push(op2); push(XOR); break; } case THEN:{ while( topOp() && priority(op2=pop())>=priority(THEN) ){ *mp = op2; mp++; } if(priority(op2)<priority(op1)) push(op2); push(THEN); break; } case EQ:{ while( topOp() && priority(op2=pop())>=priority(EQ) ){ *mp = op2; mp++; } if(priority(op2)<priority(op1)) push(op2); push(EQ); break; } case '(':{ push('('); break; } case ')':{ while( !stackEmpty() && (op2=pop())!='(' ){ *mp = op2; mp++; } if(stackEmpty() && op2!='('){ fprintf(stderr,"Incorrect sequence: some brackets missing!\n"); return -1; } if(op2=='('); op2=EMPTY; // Reset of op2, otherwise it will be pushed back break; } default:{ break; } } tp++; } // pop all remaining from stack while(!stackEmpty()){ if (topOp()){ *mp = pop(); mp++; } else{ fprintf(stderr,"Incorrect sequence: brackets not closed!\n"); return -1; break; } } // place line ending for prefix form *mp='\0'; return 0; } void setOrder(Expression *expr, int order_type) { for(int i=0; i<MAXVARS; i++){ expr->vnum[i]=-1; expr->letter[i]=-1; } char *p = expr->infix; char var; char *vnum = expr->vnum; char *letter = expr->letter; switch(order_type){ case ORDER_ALPHA:{ while(*p!='\0'){ if (isalpha(*p)){ var = toupper(*p)-'A'; if(vnum[var]<0) vnum[var]=0; } p++; } int n=0; for(int i=0; i<MAXVARS; i++) if(vnum[i]==0){ vnum[i]=n; letter[n]=i; n++; } expr->nvars=n; break; } case ORDER_EXPR:{ int n=0; while(*p!='\0'){ if(isalpha(*p)){ var = toupper(*p)-'A'; if(vnum[var]<0){ vnum[var]=n; n++; } } p++; } for(int i=0; i<MAXVARS; i++) if(vnum[i]>=0) letter[vnum[i]]=i; expr->nvars=n; break; } case ORDER_RAND:{ int n=0; while(*p!='\0'){ if(isalpha(*p)){ var = toupper(*p)-'A'; if(vnum[var]<0){ vnum[var]=0; n++; } } p++; } expr->nvars=n; Node *numlist = initList(); for(int i=0; i<n; i++) addNode(numlist,i); srand(time(NULL)); for(int i=0; i<MAXVARS; i++) if(vnum[i]==0){ vnum[i]=extractNode(numlist,rand()%n); letter[vnum[i]]=i; n--; } break; } default:{ // alphabetic order by default setOrder(expr,ORDER_ALPHA); return; } } } void makeTableTXT(Expression expr) { FILE *f; f = fopen("table.txt","w"); for(int i=0; i<expr.nvars; i++) fprintf(f,"%c",expr.letter[i]+'A'); fprintf(f," %s\n",expr.infix); for(int i=0; i<expr.nvars +1 +10; i++) fprintf(f, "-"); fprintf(f, "\n"); int nlines = ipow(2,expr.nvars); int ntrue = 0; char set[MAXVARS]; int t; char val; for(int i=0; i<nlines; i++){ t=i; for(int j=expr.nvars-1; j>=0; j--){ set[j]=t%2; t>>=1; } for(int j=0; j<expr.nvars; j++) fprintf(f,"%c",set[j]+'0'); if((val=eval(expr,set))!=0) ntrue++; fprintf(f," %c\n",val+'0'); } fprintf(f, "\nTRUE: %d\nFALSE: %d\n", ntrue, nlines-ntrue); fclose(f); } char eval(Expression expr, char *set) { resetStack(); char *line = expr.postfix; char *vnum = expr.vnum; char op2; while(line-(expr.postfix)+1<MAXLINE && *line!='\0'){ switch(*line){ case NEG: case NEG2:{ if(pop()==1) push(0); else push(1); break; } case AND:{ op2=pop(); if(pop()==1 && op2==1) push(1); else push(0); break; } case OR:{ op2=pop(); if(pop()==0 && op2==0) push(0); else push(1); break; } case XOR:{ op2=pop(); if(pop()==op2) push(0); else push(1); break; } case THEN:{ op2=pop(); if(pop()==1 && op2==0) push(0); else push(1); break; } case EQ:{ op2=pop(); if(pop()==op2) push(1); else push(0); break; } default:{ if(isalpha(*line)) push(set[vnum[*line-'A']]); break; } } line++; } if (!stackEmpty()) return pop(); else return -1; } char pop() { if(sp!=stk){ sp--; return *(sp); } else{ fprintf(stderr, "Stack is empty! Can't pop!\n" ); return 0; } } void push(char c){ if(sp-stk+1<MAXSTACK){ *sp=c; sp++; } else fprintf(stderr, "Stack is full! Can't push!\n" ); } void printStk() { char *tp = sp; printf("\nSTACK: "); while(tp>stk){ tp--; printf("%c",*tp); } } int stackEmpty() { return !(sp>stk); } int priority(char c) { switch(c){ case EMPTY:{return 999; break;} case NEG: case NEG2:{return 5; break;} case AND:{return 4; break;} case OR:{return 3; break;} case XOR:{return 3; break;} case THEN:{return 2; break;} case EQ:{return 1; break;} case '(':{return 0; break;} default: {return -1; break;} } } int topOp() { if(stackEmpty()) return 0; if(*(sp-1)=='(') return 0; else return 1; } void resetStack() { sp = stk; } Node* initList() { Node *p; p = (Node*)malloc(sizeof(Node)); p->next=NULL; p->val=-1; } void addNode(Node *head, char c) { Node *p = head; while(p->next!=NULL) p=p->next; p->next= (Node*)malloc(sizeof(Node)); p=p->next; p->next=NULL; p->val=c; } char extractNode(Node *head, int n) { Node *p = head; int i; for(i=n; i>0 && p->next!=NULL; i--) p=p->next; if(i!=0 || head->next==NULL){ // list ended fprintf(stderr,"\nElement #%d not found in list!\n",n); return -1; // possible char with value = -1 here? } Node *nxt = p->next->next; char val=p->next->val; free(p->next); p->next = nxt; return val; } void printList(Node *head) { Node *p = head->next; while(p!=NULL){ printf("%d ",p->val); p=p->next; } printf("\n"); }
C
#define __LM75_C__ #include "LM75.h" #include "IIC.h" #include <stdio.h> #include <stdlib.h> void write_1byte(unsigned char data1){ IIC_Start(); IIC_Write(I2C_ADDRESS|Write); IIC_Write(data1); IIC_Stop(); } void write_2byte(unsigned char data1, unsigned char data2){ IIC_Start(); IIC_Write(I2C_ADDRESS|Write); IIC_Write(data1); IIC_Write(data2); IIC_Stop(); } void write_3byte(unsigned char data1, unsigned char data2, unsigned char data3){ IIC_Start(); IIC_Write(I2C_ADDRESS|Write); IIC_Write(data1); IIC_Write(data2); IIC_Write(data3); IIC_Stop(); } unsigned char *get_1byte(void){ static unsigned char data[1]; IIC_Start(); IIC_Write(I2C_ADDRESS|Read); data[0]= IIC_Read(); IIC_Stop(); return data; } unsigned char *get_2byte(void){ static unsigned char data[2]; IIC_Start(); IIC_Write(I2C_ADDRESS|Read); data[0] = IIC_Read(); data[1] = IIC_Read(); IIC_Stop(); return data; } void Get_Temperature(void){ unsigned char *t_data; write_1byte(Temp); t_data = malloc( 2 * sizeof(unsigned char) ); t_data = get_2byte(); printf("Temp = %03.3fC\n", (float)(((t_data[0] << 8) | t_data[1]) >> 5)*0.125 ); } void Get_Configuration(void){ unsigned char *t_data; write_1byte(Conf); t_data = malloc( 1 * sizeof(unsigned char) ); t_data = get_1byte(); printf("Configuration = 0x%02X\n", t_data[0]); } void Get_Hysteresis(void){ unsigned char *t_data; write_1byte(Thyst); t_data = malloc( 2 * sizeof(unsigned char) ); t_data = get_2byte(); printf("Hysteresis = %03.1fC\n", (float)(((t_data[0] << 8) | t_data[1]) >> 7)*0.5 ); } void Get_Overtemperature_Shutdown_Threshold(void){ unsigned char *t_data; write_1byte(Tos); t_data = malloc( 2 * sizeof(unsigned char) ); t_data = get_2byte(); printf("Overtemperature Shutdown Threshold = %03.1fC\n", (float)(((t_data[0] << 8) | t_data[1]) >> 7)*0.5 ); } void Get_All_Information(void){ Get_Temperature(); Get_Configuration(); Get_Overtemperature_Shutdown_Threshold(); Get_Hysteresis(); } void Set_Configuration(unsigned char data){ data = data & 0x1F; //B[7:5] reserved, reserved for manufacturer’s use; should be kept as zeroes for normal operation write_2byte(Conf, data); } void Set_Hysteresis(float f_input){ unsigned char MSB, LSB; f_input = f_input/0.5; MSB = (((unsigned short)f_input & 0x1ff) >> 1); LSB = (((unsigned short)f_input & 0x001)); write_3byte(Thyst, MSB, LSB); } void Set_Overtemperature_Shutdown_Threshold(float f_input){ unsigned char MSB, LSB; f_input = f_input/0.5; MSB = (((unsigned short)f_input & 0x1ff) >> 1); LSB = (((unsigned short)f_input & 0x001)); write_3byte(Tos, MSB, LSB); } void Set_All_Pointer_Register(unsigned char h_conf, float f_tos, float f_thyst){ //Configuration, Overtemperature, Hysteresis Set_Configuration(h_conf); Set_Overtemperature_Shutdown_Threshold(f_tos); Set_Hysteresis(f_thyst); }
C
#ifndef __GRAPHICS_H #define __GRAPHICS_H #ifdef __WIN32 #include <SDL.h> #else #include <SDL2/SDL.h> #endif #include "globals.h" #define GAME_NAME "Dumb Ways to Memorize" #define SCREEN_STRING "Screen Dimensions" #define SCREEN_RES_W 1280 #define SCREEN_RES_H 720 #define MAX_SPRITES 500 #define MAX_ANIMATIONS 20 /** Defines Frame , which is an alias for Position of the start of the sprite */ typedef struct { vec2_t Position; }Frame; typedef struct sprite_s sprite_t; /** * The structure of our sprites. * * @author Anthony Rios * @date 3/30/2016 */ struct sprite_s { Frame mAnimations[MAX_ANIMATIONS]; /**< The animation positions of the given sprite*/ SDL_Texture *mTexture; /**< The texture of the sprite */ vec2_t mSize; /**< The size of the sprite frames */ vec2_t mRawSize; /**< The size of the image */ int mFrames; /**< The number of frames in this sprite */ int mRefCount; /**< Number of references, in the engine */ int mMillisecondsPerFrame; /**< The frames per second of this sprite */ char *name; /**< The name of the sprite's location */ }; /** * Init graphics system. * Calls SDL_Init and allocates memory for the sprites. * * @return 0 if good, -1 if failure. * * @author Anthony Rios * @date 3/16/2016 */ int InitGraphics(); /** * Shutdown graphics system, which frees all sprite data. * * @author Anthony Rios * @date 3/30/2016 */ void ShutdownGraphics(); /** * Loads an animation based on frame_width & frame_height. * * @param frame_width Width of the frame. * @param frame_height Height of the frame. * @param width The width. * @param height The height. * * @return null if it fails, else the animation. * * @author Anthony Rios * @date 3/16/2016 */ Frame *LoadAnimation(int frame_width, int frame_height, int width, int height); /** * Searches for the first sprite. * * @param name The name of the sprite file. * @param [in,out] position If non-null, the position. * * @return null if it fails, else the found sprite. * * @author Anthony Rios * @date 3/16/2016 */ sprite_t *FindSprite(const char *name, int *position); /** * Searches for the first free sprite in sprite system memory. * * @param [in,out] position If non-null, the position. * * @return null if it fails, else the found free sprite. * * @author Anthony Rios * @date 3/16/2016 */ sprite_t *FindFreeSprite(int *position); /** * Loads a sprite. * * @param name The file name of the image to load. * @param flags The flags. * * @return null if it fails, else the sprite. * * @author Anthony Rios * @date 3/16/2016 */ sprite_t *LoadSprite(const char *name, int flags); /** * Draw the sprite. If mCurrentFrame not set, draws the first frame (0,0). * If no position given, will draw as if was background. * * @param [in,out] sprite If non-null, the sprite. * @param [in,out] frame If non-null, the frame number to draw. * @param [in,out] position If non-null, the position. * @param [in,out] renderer If non-null, the renderer. * * @return 0 if good, -1 if failure * * @author Anthony Rios * @date 3/16/2016 */ int DrawSprite(sprite_t *sprite, int frame, vec2_t * position, SDL_Renderer * renderer, int flags); /** * Free the sprite memory, if recfcount - 1 > 0 nothing happens. * * @param [in,out] sprite If non-null, the sprite. * * @author Anthony Rios * @date 3/16/2016 */ void FreeSprite(sprite_t *sprite); void UpdateSprite(sprite_t *sprite); /** * Sdl set rectangle dimensions. * * @param [in,out] rect If non-null, the rectangle to set. * @param x The x coordinate. * @param y The y coordinate. * @param w The width. * @param h The height. * * @author Anthony Rios * @date 3/29/2016 */ void SDL_SetRect(SDL_Rect *rect, int x, int y, int w, int h); extern sprite_t *gSprites; extern int gLastSprite; extern SDL_Window *gWindow; extern SDL_Renderer *gRenderer; extern SDL_Surface *gRedSurface; extern SDL_Texture *gRedTexture; extern SDL_Renderer *gRedRenderer; #endif
C
/** * @file PlatformSensors.c * Sensors implementation source file. * @author Nezametdinov I.E. */ #include "../../PIL/Sensors/Sensors.h" #include "../../DRIVERS/SHT11/SHT11.h" #include "../../PIL/Guard.h" #define SENSOR_IS_SYSTEM_SENSOR(Sensor) ((SensorsDefs.SensorsOwners)&(1<<Sensor)) #define SENSOR_SET_SYS_ACCESS_RIGHTS(Sensor) {SensorsDefs.SensorsOwners |= (1<<Sensor);} #define SENSOR_SET_APP_ACCESS_RIGHTS(Sensor) {SensorsDefs.SensorsOwners &= ~(1<<Sensor);} /// structure defines sensor typedef struct { EVENT (*MeasurementDone[NUM_SENSORS])(uint32_t Value,RESULT Result); uint8_t SensorsOwners; }SensorsDefsStruct; static volatile SensorsDefsStruct SensorsDefs; /*******************************************************************************//** * @implements SHT11_MeasurementDone **********************************************************************************/ EVENT SHT11_MeasurementDone(SHT11_QUANTITY Quantity,uint16_t Value,RESULT Result) { // save current guard state SAVE_GUARD_STATE if(Quantity==SHT11_TEMPERATURE) { // if sensor is not active then no need to signal "measurement done" event if(SensorsDefs.MeasurementDone[TEMPERATURE_SENSOR]==NULL) { // restore previous guard state RESTORE_GUARD_STATE return; } // if current sensor is a not a system sensor, then // guard should watch for it if(!SENSOR_IS_SYSTEM_SENSOR(TEMPERATURE_SENSOR)) Guard_Watch(); else Guard_Idle(); // signal "measurement done" event SensorsDefs.MeasurementDone[TEMPERATURE_SENSOR]((uint32_t)Value,Result); } else { // if sensor is not active then no need to signal "measurement done" event if(SensorsDefs.MeasurementDone[HUMIDITY_SENSOR]==NULL) { // restore previous guard state RESTORE_GUARD_STATE return; } // if current sensor is a not a system sensor, then // guard should watch for it if(!SENSOR_IS_SYSTEM_SENSOR(HUMIDITY_SENSOR)) Guard_Watch(); else Guard_Idle(); // signal "measurement done" event SensorsDefs.MeasurementDone[HUMIDITY_SENSOR]((uint32_t)Value,Result); } // restore previous guard state RESTORE_GUARD_STATE } /*******************************************************************************//** * @implements Sensors_Init **********************************************************************************/ RESULT Sensors_Init(void) { uint8_t i; // init sensors for(i=0;i<NUM_SENSORS;++i) { SensorsDefs.MeasurementDone[i] = NULL; } // init SHT11 return SHT11_Init(); } #ifdef USE_PWR /*******************************************************************************//** * @implements Sensors_PowerSave **********************************************************************************/ void Sensors_PowerSave(void) { // empty } /*******************************************************************************//** * @implements Sensors_Restore **********************************************************************************/ void Sensors_Restore(void) { // empty } #endif /*******************************************************************************//** * @implements Sensor_Open **********************************************************************************/ HSensor Sensor_Open(uint8_t Sensor,EVENT (*MeasurementDone) (uint32_t Value,RESULT Result)) { // check sensor if(Sensor!=TEMPERATURE_SENSOR&&Sensor!=HUMIDITY_SENSOR) return INVALID_HANDLE; // check "measurement done" event handler if(MeasurementDone==NULL) return INVALID_HANDLE; // check sensor to be not active if(SensorsDefs.MeasurementDone[Sensor]!=NULL) return INVALID_HANDLE; // activate sensor SensorsDefs.MeasurementDone[Sensor] = MeasurementDone; // set sensor access rights if(!Guard_IsWatching()) SENSOR_SET_SYS_ACCESS_RIGHTS(Sensor) else SENSOR_SET_APP_ACCESS_RIGHTS(Sensor) // return sensor handle return Sensor; } /*******************************************************************************//** * @implements Sensor_Close **********************************************************************************/ RESULT Sensor_Close(HSensor Sensor) { // check sensor if(Sensor!=TEMPERATURE_SENSOR&&Sensor!=HUMIDITY_SENSOR) return FAIL; // if sensor is a system sensor and guard is watching for a threat // then return failure if(SENSOR_IS_SYSTEM_SENSOR(Sensor)&&Guard_IsWatching()) return FAIL; // stop sensor SensorsDefs.MeasurementDone[Sensor] = NULL; // return success return SUCCESS; } /*******************************************************************************//** * @implements Sensor_RequestMeasurement **********************************************************************************/ RESULT Sensor_RequestMeasurement(HSensor Sensor) { // check sensor if(Sensor!=TEMPERATURE_SENSOR&&Sensor!=HUMIDITY_SENSOR) return FAIL; // if sensor is not active then return failure if(SensorsDefs.MeasurementDone[Sensor]==NULL) return FAIL; // if sensor is a system sensor and guard is watching for a threat // then return failure if(SENSOR_IS_SYSTEM_SENSOR(Sensor)&&Guard_IsWatching()) return FAIL; // request measurement if(Sensor==TEMPERATURE_SENSOR) return SHT11_RequestMeasurement(SHT11_TEMPERATURE); return SHT11_RequestMeasurement(SHT11_HUMIDITY); }
C
#include<stdio.h> #define N 100 void init(int w[],int v[],int* len,int* t,int dp[][N]){ int i=0; scanf("%d",len); while(scanf("%d%d",w+i,v+i),++i<*len); scanf("%d",t); for(i=0;i<*len;++i){ dp[0][i]=0; dp[i][0]=0; } } int max(int a,int b){ return a<b?b:a; } int solve(int *w,int* v,int t,int n,int dp[][N]){ /* if(i==n){ dp[i][j]=0; }else if(w[i]>j){ dp[i+1][j]=dp[i][j]; }else{ dp[i+1][j]=max(dp[i][j],dp[i+1][j-w[i]]+v[i]); } */ int i,j; for(i=0;i<n;++i){ for(j=0;j<=t;++j){ if(j<w[i]){ dp[i+1][j]=dp[i][j]; }else{ dp[i+1][j]=max(dp[i][j],dp[i][j-w[i]]+v[i]); } } } return dp[n][t]; } int main(){ int w[N],v[N],len,t,dp[N][N],res; init(w,v,&len,&t,dp); res=solve(w,v,t,len,dp); printf("\n%d\n",res); return 0; }
C
/* gcc -o ../057_fib 057_fib.c */ #include <stdio.h> int fib(n) { if (n < 2) { return n; } else { return fib(n-1) + fib(n-2); } } int main() { printf("%d", fib(5)); }
C
#include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<sys/wait.h> #include<string.h> #include<strings.h> #include<unistd.h> #include<errno.h> #include<signal.h> #include<sys/socket.h> #include<sys/epoll.h> #include<arpa/inet.h> #include<pthread.h> #define SERV_PORT 8000 #define MAXLINE 8192 #define OPEN_MAX 5000 void sys_err(const char *str) { perror(str); exit(1); } int main(int argc,char *argv[]) { int i,lfd,cfd,sockfd; int n,num=0; ssize_t nready,efd,res; char buf[MAXLINE],str[INET_ADDRSTRLEN]; socklen_t clilen; struct sockaddr_in cliaddr,servaddr; struct epoll_event tep,ep[OPEN_MAX]; lfd=socket(AF_INET,SOCK_STREAM,0); if (lfd==-1) sys_err("socket error"); int opt=1; setsockopt(lfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(SERV_PORT); servaddr.sin_addr.s_addr=htonl(INADDR_ANY); bind(lfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); listen(lfd,128); efd=epoll_create(OPEN_MAX); if (efd==-1) sys_err("epoll_create error"); tep.events=EPOLLIN; tep.data.fd=lfd; res=epoll_ctl(efd,EPOLL_CTL_ADD,lfd,&tep); if (res==-1) sys_err("epoll_ctl error"); for(;;) { nready=epoll_wait(efd,ep,OPEN_MAX,-1); if (nready==-1) sys_err("epoll_wait error"); for (i=0;i<nready;i++) { if (!(ep[i].events & EPOLLIN)) continue; if (ep[i].data.fd==lfd) { clilen=sizeof(cliaddr); cfd=accept(lfd,(struct sockaddr*)&cliaddr,&clilen); printf("received from %s at port %d\n", inet_ntop(AF_INET,&cliaddr.sin_addr,str,sizeof(str)), ntohs(cliaddr.sin_port)); printf("cfd %d---client %d\n",cfd,++num); tep.events=EPOLLIN; tep.data.fd=cfd; res=epoll_ctl(efd,EPOLL_CTL_ADD,cfd,&tep); if (res==-1) sys_err("eopll_ctl error"); } else { sockfd=ep[i].data.fd; n=read(sockfd,buf,MAXLINE); if (n==0) { res=epoll_ctl(efd,EPOLL_CTL_DEL,sockfd,NULL); if (res==-1) sys_err("eopll_ctl error"); close(sockfd); printf("client[%d] closed connection\n",sockfd); } else if (n<0) { perror("read n<0 error:"); res=epoll_ctl(efd,EPOLL_CTL_DEL,sockfd,NULL); close(sockfd); } else { for (i=0;i<n;i++) buf[i]=toupper(buf[i]); write(sockfd,buf,n); write(STDOUT_FILENO,buf,n); } } } } close(lfd); close(efd); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> int main(int argc, char **argv) { char buf[1024]; int num; while(fgets(buf, 1024, stdin) != NULL){ num = 1+(int) (10.0*rand()/(RAND_MAX+1.0)); fprintf(stdout, "%d\n", num); fflush(stdout); } exit(0); }
C
#include <stdio.h> #define MAX 100000 int main() { int num, speed[MAX], ans = 1; scanf("%d", &num); for (int i = 0; i < num; i++) { scanf("%d", &speed[i]); } for (int i = num - 1; i > 0 ; i--) { if (speed[i] < speed[i - 1]) { speed[i - 1] = speed[i]; } } for (int i = 0; i < num - 1; i++) { if (speed[i] != speed[i + 1]) { ans++; } } printf("%d\n", ans); for (int i = 0; i < num; i++) { if (speed[i] != speed[i + 1]) { printf("%d ", speed[i]); } } }
C
/* Name : Terence Tang * Course : CS344 - Operating Systems * Date : Apr 12, 2021 * Assignment #1: Movies * Description: Header file for defining the movie_processing and file_processing library of functions * used for this assignment. */ /* struct for movie information */ struct movie; /* Parse the current line which is space delimited and create a * movie struct with the data in this line */ struct movie *createMovie(char *currLine); /* * Return a linked list of movies by parsing data from * each line of the specified file. */ struct movie *processFile(char *filePath); /* * Cleans up memory used for creation of movie link list * Call once you've finished with list */ void free_movie_memory(struct movie *list); /* * Print data for the given movie */ void printMovie(struct movie* aMovie); /* * Print the linked list of movie */ void printMovieList(struct movie *list); /* * Print the list of movies for a given year */ void printMovieListByYear(int year, struct movie *list); /* * Print the list of movies for a given language */ void printMovieListByLanguage(char *language, struct movie *list); /* * Print the highest rating movie for each year */ void printHighestRatedMovieByYear(struct movie *list); /* * Print the instructions for what details the program can provide */ void printInstructions(int *programChoice); /* * Print the instructions for what type of file processing the program can provide */ void printFileProcessingInstructions(int *fileChoice); /* * Parses user input on which type of file they would like to process */ int getFileName(int *choice, char *fileName, int lengthFileName); /* * Scans current active directory for the largest file (by byte size) given * specific criteria for file prefix and extension suffixes */ int getLargestMovieCSV(char *fileName, int lengthFileName); /* * Scans current active directory for the smallest file (by byte size) given * specific criteria for file prefix and extension suffixes */ int getSmallestMovieCSV(char *fileName, int lengthFileName); /* * Prompts user for a file name and checks if the file exists in the current active directory */ int getUserInputFile(char *fileName, int lengthFileName); /* * Generates a new directory name with a randomly generated int */ void setDirectoryName(char *directoryName, char *onid); /* * Takes a given directory path and movie list and writes a new file for each year a * movie was released from the movie list. Then it prints all movies in the movie list * to their respective release year files. * File naming format = YYYY.txt */ void writeMoviesToDirectory(struct movie *list, char *directoryName);
C
#include "holberton.h" /** *jack_bauer - prints every minute of the day *Return: 0 */ void jack_bauer(void) { int m; int n; int o; int p; for (m = 48; m <= 50; m++) { for (n = 48; n <= 57; n++) { for (o = 48; o <= 53; o++) { for (p = 48; p <= 57; p++) { if (!(m == 50 && n > 51)) { _putchar(m); _putchar(n); _putchar(58); _putchar(o); _putchar(p); _putchar('\n'); } } } } } }
C
/*------------------------------------------------------------------ * * LED32x16.c * *Description: * 32x16ledģʾ *Author: * hulinkang *Date: * 2015-4-22 *------------------------------------------------------------------*/ #include "LED32x16.h" #include "fft.h" /*FFT.cеȫֱ*/ extern xdata volatile uint8 result[FREQ_TAB]; //ɫ״32 extern xdata volatile uint8 topPoint[FREQ_TAB];//ɫ㣬32 /*------------------------------------------------------------------- *32x16LEDʾ *˵ * SHCPλһ * *룺 * ---------------------------------------------------------------------*/ void sendData(uint8 line) { uint8 i; for(i = 0; i < 32; i++) { SHCP = 0; GREEN = 1; RED = 1; //һƵ if(result[i] > line) { GREEN = 0;//green RED = 1; } //һƯ if(topPoint[i] == line) { GREEN = 1; //RED point RED = 0; } SHCP = 1; } } /*ѡ*/ void scan(uint8 value) { switch(value){ case 0: line0;break; case 1: line1;break; case 2: line2;break; case 3: line3;break; case 4: line4;break; case 5: line5;break; case 6: line6;break; case 7: line7;break; case 8: line8;break; case 9: line9;break; case 10:line10;break; case 11:line11;break; case 12:line12;break; case 13:line13;break; case 14:line14;break; case 15:line15;break; default:break; } }
C
/* * Copyright (c) 2013 Joe Kopena <tjkopena@gmail.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __tj_buffer_h__ #define __tj_buffer_h__ #include <stdio.h> #include <stdarg.h> //---------------------------------------------------------------------- //---------------------------------------------------------------------- typedef unsigned char tj_buffer_byte; typedef struct tj_buffer tj_buffer; /** * Create a tj_buffer. Data can be added to a tj_buffer and it will * grow, if possible, to accommodate. The buffer can then be reset * and the memory reused. Note that none of the tj_buffer operations * check if the passed tj_buffer * is null. Operation on buffers * created statically are also undefined. All operations assume the * structure has been created using tj_buffer_create. * * \param n The initial buffer size; can be 0. If you write directly * into the buffer rather than use tj_buffer_append, it must be the * total length. */ tj_buffer * tj_buffer_create(size_t initial); /** * Destroys a buffer and frees its memory. Behavior of any future * calls on the buffer are undefined, but will probably segfault. * * \param x The buffer to deallocate. */ void tj_buffer_finalize(tj_buffer *x); /** * Set whether or not the buffer owns its data and should free it when * the tj_buffer is finalized. * * \param b The buffer to operate on. * \param own 0 for the buffer no longer owns and should not free its * data, 1 otherwise. */ void tj_buffer_setOwnership(tj_buffer *b, char own); /** * Reset the buffer but do not release the memory. Future calls to * tj_buffer_append() overwrite previous contents but reuse the * current memory allocation. * * \param b The buffer to operate on. */ void tj_buffer_reset(tj_buffer *b); /** * Get the currently used extent of the buffer. * * \param b The buffer to operate on. * * \return The number of bytes consumed by data since creation or the * last reset. */ size_t tj_buffer_getUsed(tj_buffer *b); /** * Get how much memory is currently allocated for the buffer. * * \param b The buffer to operate on. * * \return The current total internal memory allocation for the * buffer. */ size_t tj_buffer_getAllocated(tj_buffer *b); /** * Get a pointer to the internal byte array. * * \param b The buffer to operate on. * * \return */ tj_buffer_byte * tj_buffer_getBytes(tj_buffer *b); /** * Get a pointer to the internal byte array as a string. Same as * (char *) tj_buffer_getBytes(b). This does not ensure a null * terminator is present. * * \param b The buffer to operate on. * * \return */ char * tj_buffer_getAsString(tj_buffer *b); /** * Get a pointer to the internal byte array from a given position. * This is no different from tj_buffer_getBytes(b)+i. * * \param b The buffer to operate on. * * \return */ tj_buffer_byte * tj_buffer_getBytesAtIndex(tj_buffer *b, size_t i); /** * Write data into a buffer, growing its memory allocation if * necessary. The new data is pushed onto the end of the buffer. If * the internal memory allocation cannot be grown to encompass all of * the data, none of it is written and the previous buffer contents * and size are maintained. * * \param b The buffer to operate on. * \param data A byte array of at least length n. * \param n The number of bytes from data to add to b. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_append(tj_buffer *b, const tj_buffer_byte *data, size_t n); /** * Appends the used extent of s into b. Follows the same memory rules * as tj_buffer_append(). * * \param b The buffer to operate on. * \param s The buffer providing data to append. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_appendBuffer(tj_buffer *b, const tj_buffer *s); /** * Add a string to the end of the buffer, including the null * terminator, growing the buffer allocation if necessary. If the * internal memory allocation cannot be grown to encompass all of the * data, none of it is written and the previous buffer contents and * size are maintained. Nothing is done to the existing contents of * the buffer. In particular, this means that if the existing buffer * already has a null terminator, functions like strcmp() will only * see the portion up to that terminator. tj_buffer_appendAsString is * intended to be used for iterated string construction. * * \param b The buffer to operate on. * \param str Null terminated string. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_appendString(tj_buffer *b, const char *str); int tj_buffer_appendAsStringN(tj_buffer *b, const char *str, size_t n); /** * Add a string to the end of the buffer, including the null * terminator, growing the buffer allocation if necessary. If the * internal memory allocation cannot be grown to encompass all of the * data, none of it is written and the previous buffer contents and * size are maintained. The last byte of the previous buffer is * assumed to be a null terminator and is overwritten. This function * can therefore be called iteratively to construct a string. * * \param b The buffer to operate on. * \param str Null terminated string. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_appendAsString(tj_buffer *b, const char *str); int tj_buffer_appendAsStringBackslashEscaped(tj_buffer *b, const char *str, const char *escape); /** * Add a formatted string to the end of the buffer, including the null * terminator, growing the buffer allocation if necessary. If the * internal memory allocation cannot be grown to encompass all of the * data, none of it is written and the previous buffer contents and * size are maintained. The last byte of the previous buffer is * assumed to be a null terminator and is overwritten. This function * can therefore be called iteratively to construct a string. * * \param b The buffer to operate on. * \param str Null terminated string. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_printf(tj_buffer *b, const char *fmt, ...); int tj_buffer_vaprintf(tj_buffer *b, const char *fmt, va_list ap); /** * Read a file or file stream into the buffer. The given file handle * can be a stream such as stdin, but the entire contents will be read * before the function returns. Internally, the function reads bytes * in TJ_PAGE_SIZE sized chunks, which may be redefined at compile * time. Note that no null terminator is included. I.e., to read a * text file from f and interpret as a string, read the file using * tj_buffer_appendFileStream(b, f), and then call * tj_buffer_appendString(b, "") to append a null terminator. * * \param b The buffer to operate on. * \param fh An open file descriptor to read from. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_appendFileStream(tj_buffer *b, FILE *fh); /** * Read a file into the buffer. The given filename is opened in * binary mode and read in using tj_buffer_appendFileStream(). The * same notes about null terminators apply. * * \param b The buffer to operate on. * \param fh Filename to open. * * \return 0 on failure, 1 otherwise. */ int tj_buffer_appendFile(tj_buffer *b, const char *filename); /** * Removes the first n bytes from the front of the buffer. * * \param b The buffer to operate on. * \param n The number of bytes to remove. */ void tj_buffer_popFront(tj_buffer *b, size_t n); /** * Removes the first n bytes from the back of the buffer. * * \param b The buffer to operate on. * \param n The number of bytes to remove. */ void tj_buffer_popBack(tj_buffer *b, size_t n); /** * Removes leading and trailing characters matching a comparison function. * * Comparison function has the same signature as functions such as isblank() * or isspace(). * * \param b The buffer to operate on. * \param func A comparison function. */ void tj_buffer_strip(tj_buffer *b, int (*func)(int c)); #endif // __tj_buffer_h__
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> struct arguments { int num1, num2; }; void *add(void *arg) { struct arguments *args = (struct arguments *) arg; printf("Addition : %d\n", ((*args).num1 + (*args).num2)); return NULL; } void *subtract(void *arg) { struct arguments *args = (struct arguments *) arg; printf("Subtraction : %d\n", ((*args).num1 - (*args).num2)); return NULL; } void *multiply(void *arg) { struct arguments *args = (struct arguments *) arg; printf("Multiplication : %d\n", ((*args).num1 * (*args).num2)); return NULL; } void *divide(void *arg) { struct arguments *args = (struct arguments *) arg; printf("Division : %d\n", ((*args).num1 / (*args).num2)); return NULL; } int main(int argc, char *argv[]) { pthread_t mThread[4]; int i; struct arguments args; if (argc == 3) { args.num1 = atoi(argv[1]); args.num2 = atoi(argv[2]); } else { printf("Enter Two Numbers\n"); scanf("%d%d", &args.num1, &args.num2); } pthread_create(&mThread[0], NULL, add, (void *) &args); pthread_create(&mThread[1], NULL, subtract, (void *) &args); pthread_create(&mThread[2], NULL, multiply, (void *) &args); pthread_create(&mThread[3], NULL, divide, (void *) &args); for (i = 0;i < 4;i++) { pthread_join(mThread[i], NULL); } return 0; }