language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int main() { int a,b,sub; printf("Please input two values for subtract:"); scanf("%d %d",&a,&b); sub=a-b; printf("%d - %d = %d\n",a,b,sub); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int ssize_t ; /* Variables and functions */ int /*<<< orphan*/ EBADOP ; int /*<<< orphan*/ LOG_ERR ; int /*<<< orphan*/ exit (int) ; int /*<<< orphan*/ send_error (int,int /*<<< orphan*/ ) ; int /*<<< orphan*/ tftp_log (int /*<<< orphan*/ ,char*) ; ssize_t get_field(int peer, char *buffer, ssize_t size) { char *cp = buffer; while (cp < buffer + size) { if (*cp == '\0') break; cp++; } if (*cp != '\0') { tftp_log(LOG_ERR, "Bad option - no trailing \\0 found"); send_error(peer, EBADOP); exit(1); } return (cp - buffer + 1); }
C
#include <stdio.h> /** *main - print 00 - 99 with comma * *Return: 0 */ int main(void) { int i; int j; i = 48; while (i < 58) { j = 48; while (j < 58) { putchar(i); putchar(j); if (i == 57 && j == 57) break; j++; putchar(','); putchar(' '); } i++; } putchar('\n'); return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* creat_display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aderragu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/12/25 16:49:44 by aderragu #+# #+# */ /* Updated: 2016/01/05 20:46:10 by tvisenti ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/fillit.h" int ft_sharp_check(char *buf, int line, int *cnts) { int cur; int shrp_cnt; int dot_cnt; cur = 0; shrp_cnt = 0; dot_cnt = 0; while (buf[cur] != '\n') { shrp_cnt = buf[line * 5 + cur] == '#' ? shrp_cnt + 1 : shrp_cnt; dot_cnt = buf[line * 5 + cur] == '.' ? dot_cnt + 1 : dot_cnt; cur++; } if (shrp_cnt + dot_cnt != 4) return (0); if (line < 3 && cnts[1] > 0 && cnts[1] < 4 && !(buf[cnts[4]] == '#' || buf[cnts[4] + 1] == '#' || buf[cnts[4] + 2] == '#' || buf[cnts[4] + 3] == '#')) return (0); return (1); } static char *ft_strsetnew(char c, int size) { char *str; int i; str = (char*)malloc((size + 1) * sizeof(char)); if (!str) return (NULL); i = 0; while (size--) { str[i] = c; i++; } str[i] = '\0'; return (str); } char **ft_createmap(int bsq) { char **map_y; char *map_x; int i; map_y = (char**)malloc((bsq + 1) * sizeof(char*)); if (!map_y) return (NULL); i = bsq; map_y[i] = NULL; while (--i >= 0) { map_x = ft_strsetnew('.', bsq); map_y[i] = map_x; } return (map_y); } void ft_display_map(char **map, int sze_sqr, int bonus) { int cnti; int cntj; cnti = 0; cntj = 0; if (map == NULL) return ; if (bonus >= 2) ft_putstr(PUR); while (cnti < sze_sqr) { while (cntj < sze_sqr) { write(1, &(map[cnti][cntj]), 1); if (bonus == 1 || bonus == 3) write(1, " ", 1); cntj++; } write(1, "\n", 1); cnti++; cntj = 0; } if (bonus == 1 || bonus == 3) ft_putstr(EOC); } int ft_bonus_init(int ac, char **av) { int bonus; int cnt; bonus = 0; ac -= 2; cnt = 0; while (cnt < ac) { if (av[cnt + 2][0] == 's') bonus++; if (av[cnt + 2][0] == 'c') bonus += 2; cnt++; } return (bonus); }
C
/* ============================================================================ Name : problem1.c Author : Version : Copyright : Your copyright notice Description : Newton Root ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <math.h> double f(double x); double f_prime(double x); double NewtonRoot (double x0, double tol, int maxniter); #define NUM_ITERATIONS 100 #define TOLERANCE 0.0001 void main(void) { double x0 = 6.1; printf("\nx_zero=%f",NewtonRoot (x0, TOLERANCE, NUM_ITERATIONS)); } // declare NewtonRoot function double NewtonRoot (double x0, double tol, int maxniter) { int iter =1; double x = x0; // I think I should be able to remove this step double x_prev, delta_x; while(iter <= maxniter) { x_prev = x; // defensive coding block... if(f_prime(x)==0) { printf("f_prime(x)==0: undefined output"); break; // probably should break to some useful spot... in real life abort would kill the patient anyway!!! } // end defensive coding block; else // what would happen if I didn't have the else here? { delta_x = -f(x)/f_prime(x); // might want to create a variable double f_prime so I dont call the function out twice? x = x+delta_x; } if(abs(x-x_prev)<tol) break; // otherwise it will keep iterating the loop else iter++; } printf("\nnumber of iterations= %d",iter); return x; } // input declare functions; double f(double x) { return -0.09375*x*x*x + 1.125*x*x - 3.375*x + 6; } double f_prime (double x) { return -3*0.09375*x*x + 2.25*x - 3.375; }
C
#include <stdio.h> #include "common/types.h" #include "common/debug.h" #include "packet.h" void debug_print_packet(struct packet * pkt) { int i; unsigned char * skb = packet_data(pkt); for(i = 0; i < 64; i++) { printf("%d ",skb[i]); } printf("********\n"); for(i = 0; i < 64; i++) { printf("%x ",skb[i]); } printf("\n\n"); }
C
//circular queue typedef struct{ char name[5]; int CBT; }Job; typedef struct{ Job *job; int front, rear, capacity,size; }Queue; int isEmpty(Queue q){ if(q.size==0) return 1; else return 0; } int isFull(Queue q){ if(q.size == q.capacity) return 1; else return 0; } void init(Queue *q){ printf("\nEnter capacity of the queue:"); scanf("%d",&q->capacity); q->front = q->rear = -1; q->size = 0; q->job = (Job *)malloc(sizeof(Job)*q->capacity); } void enqueue(Queue *q, Job job){ if(isFull(*q)){ printf("\nQueue is full!"); } else{ q->rear = (q->rear+1)%q->capacity; *(q->job+q->rear) = job; q->size++; } } void dequeue(Queue *q){ if(isEmpty(*q)){ printf("\nQueue is empty!"); } else{ q->front = (q->front+1)%q->capacity; q->size--; } } void display(Queue q){ int i; if(isEmpty(q)){ printf("\nQueue is empty!"); } else{ for(i=q.front+1;i!=q.rear;i = (i+1)%q.capacity){ printf("%c %d\t",q.job[i].name,q.job[i].CBT); } printf("%c %d ",q.job[i].name,q.job[i].CBT); } } int calcCBT(Queue q){ int CBT=0,i; for(i=0;i<q.size;i++){ CBT += q.job[i].CBT; } return CBT; }
C
#include "config.h" #include "assembler.h" #include "labels.h" #include "def_op.h" #include "check_line.h" /********************************************************************************************** This function execute the second pass on the given file and search for syntax error. Moreover, this function extracting labels data from the symbol tabel and inserting it to the machine code * @param fp- a pointer to the file * @return 0 if the function finish the second pass in succes or 1 otherwise ********************************************************************************************/ int second_pass(FILE *fp) { char line[MAX_LINE_LEN], label[MAX_ARGS_LEN]; int error = 0, definition; IC = 100; extern_counter= 0; line_idx = 0; while (fgets(line, MAX_LINE_LEN, fp)) { line_idx++; data_idx = 0; data_len = check_line(line); /*getting the line arguments after parsing */ if (data_len == 0) /*if the line is empty, we continue to the next line */ continue; if (extract_insert_label(label, 0)) { /*if the label exist we get the label. If the label is invalid, there's an error */ error = -1; continue; } definition = get_def(); /*checks if there's any definition identified */ if (definition != -1) { if (definition != ENTRY) /* if the defintion is not entry- continue */ continue; data_idx++; /*Incrementing data index to get the entry label */ if (extract_insert_label(label, 1)) { /*gets the label in the entry definition. If the label is invalid, there's an error */ error = -1; continue; } if (add_entry_to_symbol(label)) { /*If there isn't a symbol with the given name, there's an error */ error = -1; } } else { if (add_address_to_symblos()) { /*add the address of each symbol*/ error = -1; } } } return error; /*returns a flag regarding an error in the file */ }
C
#include <stdio.h> #include <string.h> int main() { int i, j = 0; char w[1000]; gets (w); for(i = strlen(w) - 1; i >= (int)strlen(w)/2 ; i--) { char x = w[i]; w[i] = w[j]; w[j] = x; j++; } printf("%s", w); return 0; }
C
//---------------------------------------------------------------- // Statically-allocated memory manager // // by Eli Bendersky ([email protected]) // // This code is in the public domain. //---------------------------------------------------------------- #include <stdio.h> #include <string.h> #include <stdlib.h> #include "memmgr.h" int memmgr_init(MemMgr* memMgr, size_t heapSize) { if (memMgr->Pool != NULL) { return 1; } memMgr->Base.s.next = 0; memMgr->Base.s.size = 0; memMgr->FreePtr = 0; memMgr->PoolFreePos = 0; memMgr->BaseVirtualAddress = 0; memMgr->PoolSizeInBytes = heapSize; memMgr->Pool = calloc(heapSize, 1); if (memMgr->Pool == NULL) { return 2; } return 0; } int memmgr_destroy(MemMgr* memMgr) { if (memMgr->Pool == NULL) { return 0; } free(memMgr->Pool); memMgr->Pool = NULL; memMgr->PoolSizeInBytes = 0; memMgr->BaseVirtualAddress = 0; return 0; } int memmgr_is_initialized(MemMgr* memMgr) { return memMgr->Pool != NULL; } size_t memmgr_get_base_virtual_address(MemMgr* memMgr) { return memMgr->BaseVirtualAddress; } void memmgr_set_base_virtual_address(MemMgr* memMgr, size_t baseVirtualAddress) { memMgr->BaseVirtualAddress = baseVirtualAddress; } size_t memmgr_get_virtual_address(MemMgr* memMgr, size_t realAddress) { if (realAddress == 0) { return 0; } size_t dataAddress = memmgr_get_data_address(memMgr); return memMgr->BaseVirtualAddress + (realAddress - dataAddress); } void* memmgr_get_real_address(MemMgr* memMgr, size_t virtualAddress) { if (virtualAddress == 0) { return 0; } size_t dataAddress = memmgr_get_data_address(memMgr); return (void*)(dataAddress + (virtualAddress - memMgr->BaseVirtualAddress)); } size_t memmgr_get_size(MemMgr* memMgr) { return memMgr->PoolSizeInBytes; } size_t memmgr_get_free_size(MemMgr* memMgr) { return memMgr->PoolSizeInBytes - memMgr->PoolFreePos; } int memmgr_is_first_pointer(MemMgr* memMgr, void* ptr) { mem_header_t* block = ((mem_header_t*)ptr) - 1; return (void*)block == (void*)memMgr->Pool; } size_t memmgr_get_data_address(MemMgr* memMgr) { return (size_t)(((mem_header_t*)memMgr->Pool) + 1); } void* memmgr_calloc(MemMgr* memMgr, size_t num, size_t size) { size_t totalSize = num * size; void* ptr = memmgr_alloc(memMgr, totalSize); if (ptr != NULL) { memset(ptr, 0, totalSize); } return ptr; } void* memmgr_realloc(MemMgr* memMgr, void* ptr, size_t size) { if (ptr == NULL) { return memmgr_alloc(memMgr, size); } // acquire pointer to block header mem_header_t* block = ((mem_header_t*)ptr) - 1; // the block is already big enough, no change required size_t currentSize = (block->s.size - 1) * sizeof(mem_header_t); if (currentSize >= size) { return ptr; } //memmgr_alloc a new address, copy the data, and then memmgr_free the old block void* newPtr = memmgr_alloc(memMgr, size); if (newPtr == NULL) { return NULL; } memcpy(newPtr, ptr, currentSize); memmgr_free(memMgr, ptr); return newPtr; } void memmgr_print_stats(MemMgr* memMgr) { #ifdef DEBUG_MEMMGR_SUPPORT_STATS mem_header_t* p; printf("------ Memory manager stats ------\n\n"); printf("Pool: free_pos = %lu (%lu bytes left)\n\n", memMgr->PoolFreePos, memMgr->PoolSizeInBytes - memMgr->PoolFreePos); p = (mem_header_t*)memMgr->Pool; while (p < (mem_header_t*)(memMgr->Pool + memMgr->PoolFreePos)) { printf(" * Addr: %p; Size: %8lu\n", p, p->s.size); p += p->s.size; } printf("\nFree list:\n\n"); if (memMgr->FreePtr) { p = memMgr->FreePtr; while (1) { printf(" * Addr: %p; Size: %8lu; Next: %p\n", p, p->s.size, p->s.next); p = p->s.next; if (p == memMgr->FreePtr) break; } } else { printf("Empty\n"); } printf("\n"); #endif // DEBUG_MEMMGR_SUPPORT_STATS } static mem_header_t* get_mem_from_pool(MemMgr* memMgr, ulong nquantas) { ulong total_req_size; mem_header_t* h; if (nquantas < MIN_POOL_ALLOC_QUANTAS) nquantas = MIN_POOL_ALLOC_QUANTAS; total_req_size = nquantas * sizeof(mem_header_t); if (memMgr->PoolFreePos + total_req_size <= memMgr->PoolSizeInBytes) { h = (mem_header_t*)(memMgr->Pool + memMgr->PoolFreePos); h->s.size = nquantas; memmgr_free(memMgr, (void*)(h + 1)); memMgr->PoolFreePos += total_req_size; } else { return 0; } return memMgr->FreePtr; } // Allocations are done in 'quantas' of header size. // The search for a free block of adequate size begins at the point 'freep' // where the last block was found. // If a too-big block is found, it is split and the tail is returned (this // way the header of the original needs only to have its size adjusted). // The pointer returned to the user points to the free space within the block, // which begins one quanta after the header. // void* memmgr_alloc(MemMgr* memMgr, size_t nbytes) { mem_header_t* p; mem_header_t* prevp; // Calculate how many quantas are required: we need enough to house all // the requested bytes, plus the header. The -1 and +1 are there to make sure // that if nbytes is a multiple of nquantas, we don't allocate too much // ulong nquantas = ((ulong)nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; // First alloc call, and no free list yet ? Use 'base' for an initial // denegerate block of size 0, which points to itself // if ((prevp = memMgr->FreePtr) == 0) { memMgr->Base.s.next = memMgr->FreePtr = prevp = &memMgr->Base; memMgr->Base.s.size = 0; } for (p = prevp->s.next; ; prevp = p, p = p->s.next) { // big enough ? if (p->s.size >= nquantas) { // exactly ? if (p->s.size == nquantas) { // just eliminate this block from the free list by pointing // its prev's next to its next // prevp->s.next = p->s.next; } else // too big { p->s.size -= nquantas; p += p->s.size; p->s.size = nquantas; } memMgr->FreePtr = prevp; return (void*)(p + 1); } // Reached end of free list ? // Try to allocate the block from the pool. If that succeeds, // get_mem_from_pool adds the new block to the free list and // it will be found in the following iterations. If the call // to get_mem_from_pool doesn't succeed, we've run out of // memory // else if (p == memMgr->FreePtr) { if ((p = get_mem_from_pool(memMgr, nquantas)) == 0) { #ifdef DEBUG_MEMMGR_FATAL printf("!! Memory allocation failed !!\n"); #endif return 0; } } } } // Scans the free list, starting at freep, looking the the place to insert the // free block. This is either between two existing blocks or at the end of the // list. In any case, if the block being freed is adjacent to either neighbor, // the adjacent blocks are combined. // void memmgr_free(MemMgr* memMgr, void* ap) { if (!ap) { return; } mem_header_t* block; mem_header_t* p; // acquire pointer to block header block = ((mem_header_t*)ap) - 1; // Find the correct place to place the block in (the free list is sorted by // address, increasing order) // for (p = memMgr->FreePtr; !(block > p && block < p->s.next); p = p->s.next) { // Since the free list is circular, there is one link where a // higher-addressed block points to a lower-addressed block. // This condition checks if the block should be actually // inserted between them // if (p >= p->s.next && (block > p || block < p->s.next)) break; } // Try to combine with the higher neighbor // if (block + block->s.size == p->s.next) { block->s.size += p->s.next->s.size; block->s.next = p->s.next->s.next; } else { block->s.next = p->s.next; } // Try to combine with the lower neighbor // if (p + p->s.size == block) { p->s.size += block->s.size; p->s.next = block->s.next; } else { p->s.next = block; } memMgr->FreePtr = p; }
C
#include <stdio.h> #include <stdlib.h> int a(int*n,int x) { int i; for(i=1;(i*2)<=x;i++) { (*n)++; a(n,i); } return 0; } int main() { int x,n=1; scanf("%d",&x); a(&n,x); printf("%d",n); return 0; }
C
#include "factory.h" int insert_login(user p) { //插入信息 MYSQL *conn; //从配置文件中读取连接信息 FILE *config; config=fopen("../conf/mysql.conf","r"); char server[50]={0}; char user[50]={0}; char password[50]={0}; char database[50]={0};//要访问的数据库名称 fscanf(config,"%s %s %s %s",server,user,password,database); char query[300]="insert into User(user,salt,ciphertext) values('"; sprintf(query,"%s%s%s%s%s%s%s%s%s%s%s%s",query,p.username,"'",",","'",p.salt,"'",",","'",p.ciphertext,"'",")"); printf("执行的数据库插入命令为:\n%s\n",query); int t; conn=mysql_init(NULL); if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0)) { printf("Error connecting to database:%s\n",mysql_error(conn)); return -3; }else{ printf("Connected...\n"); } t=mysql_query(conn,query); if(t)//不成功返回非0 { printf("Error making query:%s\n",mysql_error(conn)); return -3; }else{ printf("用户%s信息插入成功\n",p.username); } mysql_close(conn); return 0; }
C
#include <stdio.h> int main () { int Bills_of_20 ,Bills_of_10 ,Bills_of_5 ,Bills_of_1 ,amount; printf ("Enter the amount of money = "); scanf("%d" ,&amount); Bills_of_20 = amount / 20; amount %= 20; Bills_of_10 = amount / 10; amount %= 10; Bills_of_5 = amount / 5; amount %= 5; Bills_of_1 = amount; printf("20_L.E Bills = %d\n10_L.E Bills = %d\n 5_L.E Bills = %d\n 1_L.E Bills = %d\n" ,Bills_of_20 ,Bills_of_10 ,Bills_of_5 ,Bills_of_1); return 0; }
C
#include <pthread.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <png.h> #include <stdint.h> #include <errno.h> #include <sys/stat.h> /* These Values are used to control the recursive fractal funtion. DEPTH: The maximum number of steps used for testing ESCAPE: The square of the largest absolute value allowed before ending testing MIN_R: This is the square of the smallest absolute value the function will check to prevent errors with the log function */ #define DEPTH 2000 #define ESCAPE 100.0 #define MIN_R 1E-12 /* Use the EIGHT_BIT and BRANCH constants as flags. First clear all flags that have been set inadvertently. The default is for both to not be set. EIGHT_BIT: If set, the PNG file will be encoded using a 8 bit encoding for pixel color, otherwise the default is 16 bit BRANCH: If set, the branch cut for the arctangent function will be from (theta-pi,theta+pi) where theta is the original argument of the point. Otherwise the branch cut will the (b-pi,b+pi), where b is the complex portion of the exponent in the recursive fractal definition */ #ifdef EIGHT_BIT #undef EIGHT_BIT #endif #ifdef BRANCH #undef BRANCH #endif //#define EIGHT_BIT 8 #define BRANCH 1 /* Use the following definitions to define the IHDR header for the PNG file */ #ifdef EIGHT_BIT #define BIT_DEPTH 8 #else #define BIT_DEPTH 16 #endif #define COLOR_TYPE PNG_COLOR_TYPE_RGB #define INTERLACING PNG_INTERLACE_NONE // Define the minimum dimension allowed for a single side #define MIN_DIM 100 // Use a seperate folder for the #define FOLDER "./Output" /* Define the static variables which will uniquely describe the Mandelbrot image (Note this does not count the number of bits or the branching used) */ static uint32_t s_width; static uint32_t s_height; static uint32_t NUM_THREADS; static double s_scale; static double s_center_r; static double s_center_i; static double s_power_r; static double s_power_i; // The coorinates of the upper left corner of the image static double cornerR; static double cornerI; // The pointer for the PNG image static png_structp png_ptr; /* This struct is a single row of the image. Use this to keep track of the rows and ensure they are printed in the correct order */ struct row_data{ int row_number; png_bytep vals; }; /* This struct saves the pipes that will be used by the threads that are calculating the image The first pipe is read to find the row numbers and the second is used to write the row_data */ struct pipes{ int pipeRN; // Row Numbers int pipeRD; // Row Data }; int create_image(); void calc_image(); void *handle_pthread(void *ptr_pipe); png_bytep calculate_row(int i); double calculate_escape(int x, int y); void *handle_output(void *row_data_pipe); void _abort(const char * s, ...); double _absolute(double d); int main(int argc, char **argv){ // For optarg() extern char *optarg; extern int optind, opterr, optopt; // Command line arguments, with their default values // These values determine the location and type of plot to create s_width = 1920; // w s_height = 1080; // h s_scale = 0.002; // s s_center_r = -0.5; // r s_center_i = 0.0; // i s_power_r = 2.0; // a s_power_i = 0.0; // b NUM_THREADS = 4; // t // Collect Command Line arguments int opt; while((opt=getopt(argc, argv, "w:h:s:r:i:a:b:t:")) != -1){ if (optarg == NULL){ printf("Optarg is null!!"); return -1; } switch(opt) { case 'w': s_width=(uint32_t)strtoul(optarg, NULL, 0); break; case 'h': s_height=(uint32_t)strtoul(optarg, NULL, 0); break; case 't': NUM_THREADS=(uint32_t)strtoul(optarg, NULL, 0); break; case 's': s_scale=strtod(optarg,(char **) NULL); break; case 'r': s_center_r=strtod(optarg,(char **) NULL); break; case 'i': s_center_i=strtod(optarg,(char **) NULL); break; case 'a': s_power_r=strtod(optarg,(char **) NULL); break; case 'b': s_power_i=strtod(optarg,(char **) NULL); break; default: printf("Bad user argument: %c", (char) opt); break; } } // Test the parameters passed through the command line to confirm // that the height and width are within the desired range if((s_width < MIN_DIM) || (s_height < MIN_DIM)){ printf("Dimensions are too small: %d x %d\nMin: %d\n", s_width, s_height, MIN_DIM); return -1; } // Now that the parameters of the set have been determined, create the fractal return create_image(); } /* This function will create the PNG image which is used to store the Mandelbrot set. After creating the empty PNG image, it will call the function calc_image to calculate the fractal. After the image has been calculated the PNG image is ended. Input: None Output: Returns 0 on success and -1 on failure */ int create_image(){ png_FILE_p fp; png_infop info_ptr; char *name; int saveError; saveError = errno; mkdir(FOLDER, S_IRUSR|S_IWUSR|S_IXUSR| S_IRGRP|S_IWGRP|S_IXGRP| S_IROTH|S_IWOTH|S_IXOTH ); errno = saveError; // Create a filename based on the parameters given by the user // Uniquely describes a Mandelbrot image (within the accuracy of the printed values) if ((name = (char *)malloc(200*sizeof(char))) == NULL){ printf("Error allocating memory for image name!\n"); return -1; } #ifdef BRANCH sprintf(name, "%s/Dimension: %dx%d, Center: %.4f%+.4fi, Scale: %.2e, Exp: %0.2e+%0.2ei, Branch set.png", FOLDER, s_width, s_height, s_center_r, s_center_i, s_scale, s_power_r, s_power_i); #else sprintf(name, "%s/Dimension: %dx%d, Center: %.4f%+.4fi, Scale: %.2e, Exp: %0.2e+%0.2ei, Branch not set.png", FOLDER, s_width, s_height, s_center_r, s_center_i, s_scale, s_power_r, s_power_i); #endif printf("Output Filename: %s\n", name); if((fp = (png_FILE_p) fopen(name,"wb"))==NULL){ printf("File error creating file: %s\n", name); return -1; } free(name); // Initialize the PNG file which will hold the Mandelbrot image if (!(png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL, (png_error_ptr) NULL, (png_error_ptr) NULL))) { printf("Oh No!!! Bad pointer png_ptr\n"); return -1; } if (!(info_ptr=png_create_info_struct(png_ptr))) { printf("Oh No!!! Bad pointer png_infop\n"); return -1; } if (setjmp(png_jmpbuf(png_ptr))) _abort("[write_png_file] Error during init_io"); png_init_io(png_ptr,fp); if (setjmp(png_jmpbuf(png_ptr))) _abort("[write_png_file] Error during set IHDR"); // Set the type of png file based on the defaults, the specified size, and bit depth png_set_IHDR(png_ptr, info_ptr, s_width, s_height, BIT_DEPTH, COLOR_TYPE, INTERLACING, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (setjmp(png_jmpbuf(png_ptr))) _abort("[write_png_file] Error during write info"); png_write_info(png_ptr,info_ptr); // Capture the data required for the image calc_image(); // Write the end of file for the PNG image if (setjmp(png_jmpbuf(png_ptr))) _abort("[write_png_file] Error during ending"); png_write_end(png_ptr,info_ptr); // Close the file fclose((FILE *) fp); // Return zero on proper exit return 0; } /* Function: calc_image Creates the threads which will calculate the fractal for each row and the thread which uses those values to write a row to the PNG Input: None Output: None (PNG data is computed during this time) */ void calc_image(){ pthread_t threads[NUM_THREADS+1]; int i, j; int pipeRows[2], pipeRet[2]; struct pipes pipefd; // Find the upper lefthand corner of the image cornerR = s_center_r-s_scale*s_width/2; cornerI = s_center_i+s_scale*s_height/2; // Create a pipe to pass information to the pthreads if(pipe(pipeRows) != 0) { printf("Error Making Pipes!\n"); exit(-1); } // Create a pipe to return the row data from the pthreads if(pipe(pipeRet) != 0) { printf("Error Making Pipes!\n"); exit(-1); } // Create the thread which will print the row data to the image if(pthread_create(&threads[NUM_THREADS],NULL,handle_output,&(pipeRet[0])) != 0){ printf("thread Error!\n"); _exit(-1); } // Create the pthreads and start them waiting for the rows to calculate for (i=0; i < NUM_THREADS; i++){ pipefd.pipeRN = pipeRows[0]; pipefd.pipeRD = pipeRet[1]; if(pthread_create(&threads[i],NULL,handle_pthread,&pipefd) != 0){ printf("thread Error!\n"); _exit(-1); } } // Pass the row numbers to the pthreads for(j=0; j < s_height; j++){ if(write(pipeRows[1],&j,sizeof(int))!=sizeof(int)){ printf("Error writing: %d\n",j); exit(-1); } } // Write the end of row flag for each of the pthreads for (i=0; i<NUM_THREADS; i++){ j=-1; if(write(pipeRows[1],&j,sizeof(int))!=sizeof(int)){ printf("Error writing stop\n"); exit(-1); } } // Await the termination of the pthreads in order to finish the PNG image for (i=0; i<NUM_THREADS+1; i++){ if(pthread_join(threads[i],NULL)!=0){ printf("Error during thread join!\n"); _exit(-1); } } } /* Function: handle_pthread This function will read row numbers from an input pipe. From these row numbers, the function will use the calculate_row function to find the row data. After finding the row data, the function will pass the result to the image writing thread using the output pipe. Input: void *ptr_pipe: pointer to a struct ptr_pipe, which hold the pointer to the input and output pipe file descriptors Output: NULL */ void *handle_pthread(void *ptr_pipe){ struct pipes pp; struct row_data rowD; int value; // Initialize pipes and value pp = *((struct pipes *) ptr_pipe); value=0; // Take the row numbers passed in the pipe and calculate the color the entire row while(value>=0){ if(read(pp.pipeRN, &value, sizeof(int))!=sizeof(int)){ printf("Read Error!!\n"); exit(-1); } // If the value is less than zero, the image is done, otherwise continue calculating the row data if (value >= 0){ // Calculate the values in the row and keep them with the row number rowD.vals = calculate_row(value); rowD.row_number = value; // Pass the row data to the thread which is writing the row if(write(pp.pipeRD, &rowD, sizeof(struct row_data))!=sizeof(struct row_data)){ printf("Error writing the row data!!\n"); exit(-1); } } } return NULL; } /* Function: handle_output This function will read row data from the fractal calculating pthreads. As the pthreads calculate the row data, they will pass the data using the row_data struct, allowing the data for the row, and the row number, to be passed to the thread using this function. At such time, this thread will save the row data in an array. After saving the PNG image will be written, keeping track of proper row numbers. As the image is printed, the memory will be released, allowing the overall program a smaller overhead. Input: void *row_data_pipe: pointer to the file descriptor of the pipe for the row data Output: NULL */ void *handle_output(void *row_data_pipe){ int next_row; int read_pipe; png_bytep *rows; struct row_data read_data; read_pipe = *((int *) row_data_pipe); // Make an array to hold the data for the individual rows // and initilize all of the pointers to NULL rows = (png_bytep *)malloc(sizeof(png_bytep)*s_height); for (next_row=0; next_row<s_height; next_row++) rows[next_row]=NULL; /* Read the row data from one of the thread that are calculating the image. Once this data has been read, add the row data to the image, using the given row number. Next, use the array to write the next row in the image, until the first break in the image is found. At this point, start again with reading data from the from the calculation threads. */ next_row = 0; while(next_row != s_height){ if(read(read_pipe, &read_data, sizeof(struct row_data)) != sizeof(struct row_data)){ printf("Error reading return values\n"); exit(-1); } // Save row data rows[read_data.row_number]=read_data.vals; // Write as many rows as is possible, with the current information while(rows[next_row] != NULL){ png_write_row(png_ptr,rows[next_row]); // Write image row free(rows[next_row]); rows[next_row]=NULL; next_row++; } } free(rows); return NULL; // Required from pthread } /* Function: calculate_row This function takes a row number and calculates the value of the fractal at each pixel in the row. With this value, the proper color is found and converted using the proper bit depth. Preprocessor Flags: EIGHT_BIT: If this flag is set, the function will calculate the pixels using an eight bit color scheme. If the flag is not set, the pixels will be calculated using a sixteen bit scheme Input: int i: row number for the row that this function is computing Output: png_bytep: a pointer to the bytes which will be used to write a single row of the PNG image */ png_bytep calculate_row(int i){ png_bytep vals; double result; int j, start, ii; // Allocate space to store the row data if ((vals = (png_bytep) malloc(s_width*sizeof(png_byte)*(BIT_DEPTH/8)*3)) == NULL){ printf("Bad allocaion of row data!\n"); _exit(-1); } for(j=0; j < s_width; j++){ // Calculate the result result = calculate_escape(j, i); // Find the start of the correct pixel start = j*3*BIT_DEPTH/8; // If the pixel is in the set (recurses to the limit), set the pixel to black if (result >= 1.0){ for(ii=0;ii<((BIT_DEPTH/8)*3); ii++) vals[start++]=0x00; } /* Here we use the value returned by the calculat_escape function to determine the color of the pixel. For the eight bit encoding, there are three png_bytes of color data, whereas the sixteen bit encoding has 6 png_bytes */ #ifdef EIGHT_BIT else { vals[start++]=0xFF-(png_byte)(result*0xFF); vals[start++]=0xFF-(png_byte)(result*0x77); vals[start]=0xFF-(png_byte)(result*0xFF); } #else else{ vals[start++]=0xDD-(png_byte)(result*0xAA); vals[start++]=0xFF-(png_byte)(result*0xFF); vals[start++]=0xFF-(png_byte)(result*0xFF); vals[start++]=0xFF-(png_byte)(result*0xFF); vals[start++]=0xFF-(png_byte)(result*0x77); vals[start]=0xFF-(png_byte)(result*0xFF); } #endif } return vals; } /* Function: calculate_escape This is the function which tests each point to find if it is in the fractal and if not, the escape from that set. ------------------------------------------------------------------------ Background: ------------------------------------------------------------------------ For this, the following basic recursive definition of the fractal is used, assuming the complex value c is the point being tested. The Mandelbrot set is traditionally defined for (a+bi) = 2. Base Case: Z(0) = c Recursive Case: Z(N+1) = Z(N)^(a+bi)+c The fractal is defined to be the set of points C for which the following limit is held. lim N->Inf |Z(N)| < bound, bound > 0, bound element of the Reals. For the Mandelbrot set [(a+bi) = 2] is independant of the value of the bound, given that b >= 2. Traditionally, the Mandelbrot fractal is displayed as a colorful image. This is obtained by noting the value of N and |Z(N)| for the first value that is larger than the bound. The following formula is used to generate a value in the range (0,1), based on the Taylor expansion shown at http://linas.org/art-gallery/escape/escape.html. modN = N + 1 - log(log(|Z(N)|)) / log(r^a * e^(-b * theta)) The justification of the final term is shown below. The returned value is modN divided by the maximum number of iterations allowed by the program. ------------------------------------------------------------------------ Implementation: ------------------------------------------------------------------------ The recursive case can be solved using the following expressions: Define The Following: Z(N) = r e^(i * theta) -> Polar form of a complex number Coefficient = r^a * e^(-b * theta) = Coe Angle = a * theta + b * ln(r) = Ang From these definitions, we can write the recursive form in an easily calculable form, where Re{Z} is the real component of Z and Im{Z} is the imaginary component of Z: Re{Z(N+1)} = Coe * cos ( Ang ) + Re{c} Im{Z(N+1)} = Coe * sin ( Ang ) + Im{c} Now, we convert the value Z(N+1) from Standard Form to Polar Form: Z(N+1) = r e^(i * theta) r = Sqrt(Re{Z(N+1)}*Re{Z(N+1)}+Im{Z(N+1)}*Im{Z(N+1)}) theta = arctan2(Re{Z(N+1)}, Im{Z(N+1)}) In order to save us from using the square root function, we can use the following modifications Z(N+1) = Sqrt(rsq) * e^(i * theta) rsq = Re{Z(N+1)}*Re{Z(N+1)}+Im{Z(N+1)}*Im{Z(N+1)} theta = arctan2(Re{Z(N+1)}, Im{Z(N+1)}) For this to b used, we also must modify the original definitions: Z(N) = Sqrt(rsq) * e^(i * theta) Coefficient = rsq^(a/2) * e^(-b * theta) = Coe Angle = a * theta + 1/2 * b * ln(rsq) = Ang ------------------------------------------------------------------------ Branch Cuts: ------------------------------------------------------------------------ One more discussion must be had before generating using these formulas, and that involves branch cuts. Branch cuts are important when discussing the value returned by the arctangent function. The function is defined such that: tan(x) = y <==> arctan(y) = x However, the following is true of the tangent function: tan(x) = tan(x + 2*pi) = tan(x + 4*pi) = tan(x - 2*pi) = .... = tan(x+2*pi*i), i-> integer The arctangent function traditionally returns a value in the range (-pi, pi]. However, due to the property of the tangent function, the value returned by the arctangent function can be in any range (x-pi, x+pi] for any value of x. The range returned is known as the branch, and the extreme values of the range are known as the branch cut (Note that in polar form, the angles x+pi and x-pi are coincident in the polar plane). Unfortunately for complex exponentiation, the choice of which value of x to use to center the range will affect the result that is obtained in a very meaningful way (Consider the formula above for Coe) For the generation of fractals, there are many ways to pick a meaningful branch. Below are two methods 1. x = -b Use the imaginary component of the exponent to set the branch 2. x = Arg(c) Use the argument of the original point to determine the branch General Statements on branch cut: Generally I have used this modified exponent "Multibrot" set generator for three general cases and have the following generalizations about the "best" branch cut mode 1. Integer values of a and b=0 (ie. Z(N+1) = Z(N)^4 + C) Here the branch cut method makes little to no difference 2. Small values for b and a=2 ((ie. Z(N+1) = Z(N)^(2+0.01i) + C)) I find the images look best with the first method of branch cut (flag not set) 3. Non-integer values of a and b=0 I have liked the images with the second method of the branch cut (flag is set) ------------------------------------------------------------------------ Function: ------------------------------------------------------------------------ Preprocessor Flags: BRANCH: If this flag is set, the function will calculate the branch cut for the arctangent function using the argument of the initial point (r e ^ (i theta)). If not, the branch cut will be based on the complex component of the exponent in the recursive definition of the fractal. Input: int x,y: The coordinates of the pixel being calculated in the PNG image Output: double: a pointer to the bytes which will be used to write a single row of the PNG image */ double calculate_escape(int x, int y){ double reV, imV, a, b; double rsq, r, th, coe, ang; int i; /* if (x+y > 0) return ((double) x) /((double) s_width); */ #ifdef BRANCH double br; #endif reV = cornerR+s_scale*x; imV = cornerI-s_scale*y; a = reV, b = imV; rsq = a*a + b*b; if (rsq < MIN_R) i=DEPTH; else{ i=0; th = atan2(b,a); #ifdef BRANCH br = th; while (br > (M_PI-s_power_i)) br -= 2*M_PI; while (br < (-1.*s_power_i-M_PI)) br += 2*M_PI; #endif } for(; i < DEPTH; i++){ // Perform a branch cut for the complex exponential #ifdef BRANCH while (th > (br+M_PI)) th -= 2.0*M_PI; while (th < (br-M_PI)) th += 2.0*M_PI; #else while (th > (M_PI-s_power_i)) th -= 2*M_PI; while (th < (-1.*s_power_i-M_PI)) th += 2*M_PI; #endif coe = pow(rsq, s_power_r/2.)*exp(-1.0*s_power_i*th); ang = s_power_r*th+0.5*s_power_i*log(rsq); a = coe*cos(ang)+reV; b = coe*sin(ang)+imV; rsq = a*a + b*b; th = atan2(b,a); if (rsq < MIN_R) return 1.0; if (rsq >= ESCAPE) { coe = pow(rsq, s_power_r/2.)*exp(-1.0*s_power_i*th); coe = 2.0*log(coe)/log(rsq); r = 2.0 - log(0.5*log(rsq)) / log(coe); r += (double) i; r = log(r)/log((double) DEPTH); r = pow(r,0.5); if (r < 0.0) return 0.0; if (r > 1.0) return 1.0; return r; } } return 1.00; } void _abort(const char * s, ...) { va_list args; va_start(args, s); vfprintf(stderr, s, args); fprintf(stderr, "\n"); va_end(args); abort(); }
C
#include <linux/module.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include <linux/uaccess.h> #include <linux/slab.h> // #define MAX_BUF_SIZE 16 static int MAX_BUF_SIZE = 16; char *msg_init; // static char proc_buf[MAX_BUF_SIZE]; static char* proc_buf = NULL; static unsigned long proc_buf_size = 0; static ssize_t read_proc(struct file *filp, char *usr_buf, size_t count, loff_t *offp) { static int finished = 0; if(finished) { printk(KERN_INFO "read_proc: END\n"); finished = 0; return 0; } finished = 1; if(copy_to_user(usr_buf, proc_buf, proc_buf_size)) { printk(KERN_ERR "Copy to user unfinished\n"); return -EFAULT; } printk(KERN_INFO "read_proc: read %lu bytes\n", proc_buf_size); return proc_buf_size; } static ssize_t write_proc(struct file *filp, const char *usr_buf, size_t count, loff_t *offp) { if(count > MAX_BUF_SIZE) { printk(KERN_WARNING "write_proc: overflow, enlarge buffer...\n"); printk(KERN_WARNING "write_proc: MAX_BUF_SIZE %d -> %ld\n", MAX_BUF_SIZE, count + count / 2); MAX_BUF_SIZE = count + count / 2; kfree(proc_buf); proc_buf = (char*)kmalloc(MAX_BUF_SIZE * sizeof(char), GFP_KERNEL); } proc_buf_size = count; if(copy_from_user(proc_buf, usr_buf, proc_buf_size)) { printk(KERN_ERR "Copy from user unfinished\n"); return -EFAULT; } printk(KERN_INFO "write_proc: write %lu bytes\n", proc_buf_size); return proc_buf_size; } struct file_operations proc_fops = { .read = read_proc, .write = write_proc }; struct proc_dir_entry *base = NULL; struct proc_dir_entry *entry = NULL; static int __init M4_init (void) { base = proc_mkdir("M4_proc_dir", NULL); if(!base) { printk(KERN_ERR "Unable to create /proc/M4_proc_dir/\n"); return -EINVAL; } entry = proc_create("M4_proc", 0666, base, &proc_fops); if(!entry) { printk(KERN_ERR "Unable to create /proc/M4_proc_dir/M4_proc\n"); proc_remove(base); return -EINVAL; } proc_buf = (char*)kmalloc(MAX_BUF_SIZE * sizeof(char), GFP_KERNEL); printk(KERN_INFO "/proc/M4_proc_dir/M4_proc successfully created\n"); msg_init = "Hello /proc!\n"; strcpy(proc_buf, msg_init); proc_buf_size = strlen(msg_init); return 0; } void __exit M4_exit(void) { kfree(proc_buf); proc_remove(entry); proc_remove(base); printk(KERN_INFO "Exiting Module4...\n"); } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Module4"); MODULE_AUTHOR("Hongzhou Liu"); module_init(M4_init); module_exit(M4_exit);
C
#include <stdio.h> extern int work(); void main() { int i; i = work(); printf("i is %d\n",i); }
C
#include<stdio.h> main() { char *name="name"; change(name); printf("%s",name); } change(char **name) { char *nm="newname"; name=nm; }
C
#include "queue.h" static node *create_node(int id, int time, node *link) //c { struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->id = id; temp->time = time; temp->link = NULL; return temp; } void list_initialize(List *ptr_list) //c { ptr_list = (List*) malloc(sizeof(List)); ptr_list->head = NULL; ptr_list->tail = NULL; ptr_list->number_of_nodes = 0; } const int node_get_id(node *node_ptr) //c { return node_ptr->id; } const int node_get_time(node *node_ptr) //c { return node_ptr->time; } void list_insert_rear(List *ptr_list, int id, int time) //c { struct node* temp = create_node(id, time, NULL); if (ptr_list->tail == NULL) { ptr_list->head = ptr_list->tail = temp; ptr_list->number_of_nodes+=1; return; } ptr_list->tail->link= temp; ptr_list->tail = temp; ptr_list->number_of_nodes+=1; //printf("%s","1a"); } void list_delete_front(List *ptr_list) { struct node* temp = (struct node*)malloc(sizeof(struct node)); temp=ptr_list->head; if(temp==NULL) { return; } else { if(ptr_list->head==ptr_list->tail) { ptr_list->head=NULL; ptr_list->tail=NULL; } else { ptr_list->head=ptr_list->head->link; } ptr_list->number_of_nodes-=1; free(temp); } } void list_destroy(List *ptr_list) { node *t, *u=NULL; t=ptr_list->head; while (t->link!=NULL){ u=t; t=t->link; free(u); } free(ptr_list); } void queue_initialize(Queue *queue_list) //c { queue_list = (Queue*) malloc(sizeof(Queue)); list_initialize(queue_list->ptr_list); //printf("%s","6a"); } void queue_enqueue(Queue *ptr, int id, int time) //c { list_insert_rear(ptr->ptr_list, id, time); } void queue_dequeue(Queue *ptr) { list_delete_front(ptr->ptr_list); } int queue_is_empty(Queue *ptr) { printf("%s","4a"); if(ptr->ptr_list->tail==NULL) return 0; return 1; } void queue_peek(Queue *ptr) { if(queue_is_empty(ptr)==0) { printf("%s","Empty Queue"); } else { printf("%d",node_get_id(ptr->ptr_list->head)); printf("%d",node_get_time(ptr->ptr_list->head)); } } void queue_destroy(Queue *ptr) { list_destroy(ptr->ptr_list); free(ptr); } const int queue_find_person(Queue *ptr_queue, int t) { /*if(queue_is_empty(ptr)==1) { //printf("%s","5a"); printf("%s","Empty Queue"); return; }*/ /*struct node* next = (struct node*)malloc(sizeof(struct node)); struct node* last = (struct node*)malloc(sizeof(struct node)); int time=0; int id=0; while(time<t && temp!=NULL) { temp=ptr_queue->ptr_list->head; time+=temp->time; id= }*/ }
C
/* * Problem 17 - Reverse() * * Write an iterative Reverse() function that reverses a list by rearranging * all the .next pointers and the head pointer. Ideally, Reverse() should only * need to make one pass of the list. The iterative solution is moderately * complex. It's not so difficult that it needs to be this late in the * document, but it goes here so it can be next to #18 Recursive Reverse which * is quite tricky. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }; void Push(struct node** headRef, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = *headRef; *headRef = newNode; } void PrintList(struct node* head) { struct node* current; int count = 0; for (current = head; current != NULL; current = current->next) { printf("index: %d, value: %d\n", count, current->data); count++; } printf("---\n"); } void ReverseList(struct node** headRef) { assert(*headRef != NULL); struct node* current = *headRef; struct node* newList = NULL; while (current != NULL) { struct node* next = current->next; current->next = newList; newList = current; current = next; } *headRef = newList; } int main(int argc, char* argv[]) { struct node* list = NULL; Push(&list, 1); Push(&list, 2); Push(&list, 3); Push(&list, 4); Push(&list, 5); Push(&list, 6); Push(&list, 7); Push(&list, 8); Push(&list, 9); Push(&list, 10); PrintList(list); ReverseList(&list); PrintList(list); }
C
#include "fifo.h" #include "stddef.h" #include "stdint-gcc.h" #include "stdlib.h" #include <stdint.h> #include <stdbool.h> /** * \brief This function initializes fifo. It should be done only once for one fifo. The initialization process depends on assigning the buffer to the fifo, and setting its size * \param[in] fifo - fifo to initialize * \param[in] buffer - the buffer which will be connected with the fifo. It must be global array * \param[in] buffer_size - the size of the assigned buffer in bytes */ void Fifo_Init(fifo_t* fifo, uint8_t* buffer, uint16_t buffer_size) { // Set the queue fifo->queue = buffer; // Set the buffer size in the fifo fifo->buffer_size = buffer_size; // Clear the input and output indices fifo->input_index = 0; fifo->output_index = 0; // Clear the byte counter fifo->byte_counter = 0; } /** * \brief This function checks if the given fifo is empty * \param fifo - The fifo to be checked * \return true - If fifo empty * false - If fifo not empty */ bool Fifo_Empty(fifo_t* fifo) { // If the output pointer is equal to the input pointer then the fifo is empty if(fifo->byte_counter == 0) return true; return false; } /** * \brief This function extracts a character from the fifo * \param[in] fifo - the fifo from which the character will be extracted * \param[out] character - the buffer where the extracted from fifo sign will be held * \return FIFO_EMPTY - If there is no character to get from fifo * FIFO_OP_OK - If everthing went fine */ uint8_t Fifo_Get(fifo_t* fifo, uint8_t* character) { if(Fifo_Empty(fifo)) return FIFO_EMPTY; // Load the character from the fifo to the buffer *character = fifo->queue[fifo->output_index]; // Increase the output index fifo->output_index++; // If it is bigger than the fifo queue size, then set it to 0 if(fifo->output_index >= fifo->buffer_size) fifo->output_index = 0; // Decrease the byte counter fifo->byte_counter--; // return the current character return FIFO_OP_OK; } /** * \brief This function puts a character in the fifo buffer. If the fifo is full, then the newest data is discarded * \param[in] fifo - fifo which queue will be modified * \param[in] char_to_put - The character which is to be written to the fifo. */ uint8_t Fifo_Put(fifo_t* fifo, uint8_t char_to_put) { #ifdef FIFO_OVERRUN_NEEDED // Check if there wouldn'n be an overrun of data if((fifo->input_index == fifo->output_index) && (fifo->byte_counter != 0)) return FIFO_OVERRUN; #endif // Load the character in the fifo fifo->queue[fifo->input_index] = char_to_put; // Increase the input data index fifo->input_index++; // Wrap the index if necessary if(fifo->input_index >= fifo->buffer_size) fifo->input_index = 0; // Increase the byte counter fifo->byte_counter++; return FIFO_OP_OK; } /** * \brief This function clears the input and output indices and resets the byte counter * \param fifo - the fifo to flush */ uint8_t Fifo_Flush(fifo_t* fifo) { // Clear the input data index fifo->input_index = 0; // Clear the output data index fifo->output_index = 0; // Clear the byte counter fifo->byte_counter = 0; return FIFO_OP_OK; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ int /*<<< orphan*/ init_signal_tables () ; int num_signal_names ; char** signal_names ; int /*<<< orphan*/ sprintf (char*,char*,int) ; const char * strsigno (int signo) { const char *name; static char buf[32]; if (signal_names == NULL) { init_signal_tables (); } if ((signo < 0) || (signo >= num_signal_names)) { /* Out of range, just return NULL */ name = NULL; } else if ((signal_names == NULL) || (signal_names[signo] == NULL)) { /* In range, but no signal_names or no entry at this index. */ sprintf (buf, "Signal %d", signo); name = (const char *) buf; } else { /* In range, and a valid name. Just return the name. */ name = signal_names[signo]; } return (name); }
C
#include <stdio.h> #include <stdlib.h> int main(void) { char *names[] = {"Miller","Jones","Anderson"}; printf("%c\n",*(*(names+1)+2)); printf("%c\n",names[1][2]); return 0; }
C
#include "2-us_xfr.h" #include <errno.h> int main(int argc,char *argv[]){ int sfd,cfd; ssize_t numRead; struct sockaddr_un uaddr; char buf[BUF_SIZE]; sfd = socket(AF_UNIX,SOCK_STREAM,0); if(sfd == -1){ fprintf(stderr,"socket\n"); exit(EXIT_FAILURE); } if(remove(SV_SOCK_PATH) == -1 && errno != ENOENT){ fprintf(stderr,"remove\n"); exit(EXIT_FAILURE); } memset(&uaddr,0,sizeof(struct sockaddr_un)); uaddr.sun_family = AF_UNIX; snprintf(uaddr.sun_path,sizeof(uaddr.sun_path) - 1,"%s",SV_SOCK_PATH); if(bind(sfd,(struct sockaddr *)&uaddr,sizeof(struct sockaddr_un)) == -1){ fprintf(stderr,"bind\n"); exit(EXIT_FAILURE); } if(listen(sfd,5) == -1){ fprintf(stderr,"listen\n"); exit(EXIT_FAILURE); } while(1){ cfd = accept(sfd,NULL,0); if(cfd == -1){ fprintf(stderr,"accept\n"); exit(EXIT_FAILURE); } while((numRead = read(cfd,buf,BUF_SIZE)) > 0){ if(write(STDOUT_FILENO,buf,numRead) != numRead){ fprintf(stderr,"write\n"); exit(EXIT_FAILURE); } } if(numRead == -1){ fprintf(stderr,"read\n"); exit(EXIT_FAILURE); } close(cfd); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <zlib.h> #define BUF 0x200 int main(int argc, char** argv) { unsigned char buf[BUF]; unsigned long adler = adler32(0, Z_NULL, 0); size_t len; while((len = fread(buf, sizeof(unsigned char), BUF, stdin)) != 0) adler = adler32(adler, buf, len); printf("0x%08lx\n", adler); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include "hwlib.h" #include "socal/socal.h" #include "socal/hps.h" #include "socal/alt_gpio.h" #include "hps_0.h" #include "perifericos.h" #define HW_REGS_BASE ( ALT_STM_OFST ) #define HW_REGS_SPAN ( 0x04000000 ) #define HW_REGS_MASK ( HW_REGS_SPAN - 1 ) #define CHANNEL1 0x00001 //FUNCIONA PARA EL ADC LEER EN CUALQUIER PUERTO // ADC_BASE + 0X04 <== 1 PARA ACTIVAR LA CONVERSION A-D EN TODOS LOS CANALES //OFFSET LECTURA: ADC_BASE CH0 // ADC_BASE + 0X04 CH1 // ADC_BASE + 0X08 CH2 // ADC_BASE + 0X0C CH3 // ADC_BASE + 0X10 CH4 // ADC_BASE + 0X14 CH5 // ADC_BASE + 0X18 CH6 // ADC_BASE + 0X1C CH7 float adc_value(int channel) { void *virtual_base; int fd; void *h2p_lw_adc_addr; int value; int offset=0; // map the address space for the LED registers into user space so we can interact with them. // we'll actually map in the entire CSR span of the HPS since we want to access various registers within that span if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) { printf( "ERROR: could not open \"/dev/mem\"...\n" ); return( 1 ); } virtual_base = mmap( NULL, HW_REGS_SPAN, ( PROT_READ | PROT_WRITE ) , MAP_SHARED, fd, HW_REGS_BASE ); if( virtual_base == MAP_FAILED ) { printf( "ERROR: mmap() failed...\n" ); close( fd ); return( 1 ); } switch(channel) { case 0: offset = 0; break; case 1: offset = 0x04; break; case 2: offset = 0x08; break; case 3: offset = 0x0C; break; case 4: offset = 0x10; break; case 5: offset = 0x14; break; case 6: offset = 0x18; break; case 7: offset = 0x1C; break; default: offset = 0; break; } h2p_lw_adc_addr=virtual_base + ( ( unsigned long )( ALT_LWFPGASLVS_OFST + DE1_SOC_ADC_0_BASE + offset ) & ( unsigned long)( HW_REGS_MASK ) ); value=*(long int *)(h2p_lw_adc_addr); printf("CH 0=%.3fV (0x%04x)\r\n", (float)value/1000.0, value); if( munmap( virtual_base, HW_REGS_SPAN ) != 0 ) { printf( "ERROR: munmap() failed...\n" ); close( fd ); return( 1 ); } close( fd ); return (float)value/1000.0; } int adc_init(void) { void *virtual_base; int fd; void *h2p_lw_adc_addr; // map the address space for the LED registers into user space so we can interact with them. // we'll actually map in the entire CSR span of the HPS since we want to access various registers within that span if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) { printf( "ERROR: could not open \"/dev/mem\"...\n" ); return( 1 ); } virtual_base = mmap( NULL, HW_REGS_SPAN, ( PROT_READ | PROT_WRITE ) , MAP_SHARED, fd, HW_REGS_BASE ); if( virtual_base == MAP_FAILED ) { printf( "ERROR: mmap() failed...\n" ); close( fd ); return( 1 ); } printf("ADC ON\n"); h2p_lw_adc_addr=virtual_base + ( ( unsigned long )( ALT_LWFPGASLVS_OFST + DE1_SOC_ADC_0_BASE + 0x00000004 ) & ( unsigned long)( HW_REGS_MASK ) ); *(uint32_t *)h2p_lw_adc_addr=(uint32_t)0x01; usleep(100); if( munmap( virtual_base, HW_REGS_SPAN ) != 0 ) { printf( "ERROR: munmap() failed...\n" ); close( fd ); return( 1 ); } close( fd ); return 0; } void pwm_value(int porcentaje) { void *virtual_base; int fd; long int value; int i; void *h2p_lw_pwm_addr; // map the address space for the LED registers into user space so we can interact with them. // we'll actually map in the entire CSR span of the HPS since we want to access various registers within that span if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) { printf( "ERROR: could not open \"/dev/mem\"...\n" ); return ; } virtual_base = mmap( NULL, HW_REGS_SPAN, ( PROT_READ | PROT_WRITE ), MAP_SHARED, fd, HW_REGS_BASE ); if( virtual_base == MAP_FAILED ) { printf( "ERROR: mmap() failed...\n" ); close( fd ); return ; } h2p_lw_pwm_addr=virtual_base + ( ( unsigned long )( ALT_LWFPGASLVS_OFST + PWM_GENERATOR_BASE ) & ( unsigned long)( HW_REGS_MASK ) ); //SE ESCRIBE DIRECTAMENTE SOBRE EL REGISTRO BASE EL VALOR ENTRE 0 Y 100 EL PORCENTAJE DEL CICLO DE TRABAJO //EL OFFSET NO ES NECESARIO POR USAR OFFSET: 0X00 if(porcentaje > 100) value = 100; else if ( porcentaje < 0) value = 0; else value=porcentaje; *(uint32_t *)h2p_lw_pwm_addr = value; if( munmap( virtual_base, HW_REGS_SPAN ) != 0 ) { printf( "ERROR: munmap() failed...\n" ); close( fd ); return ; } close( fd ); return ; }
C
#include <stdio.h> #include <stdlib.h> #include "tetris.h" #include <Windows.h> enum ConsoleColor { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = 14, White = 15 }; int main(void) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); system("color F0"); SetConsoleTextAttribute(hConsole, (WORD) ((DarkGray << 4) | Yellow)); puts("@"); SetConsoleTextAttribute(hConsole, (WORD) ((Yellow << 4) | LightGreen)); puts("#"); tetris_run(10, 10); return EXIT_SUCCESS; }
C
/* A simple SSL client. It connects and then forwards data from/to the terminal to/from the server */ #include "common.h" #include "client.h" #include "read_write.h" static char *host=HOST; static int port=PORT; static int require_server_auth=1; static char *ciphers=0; static int s_server_session_id_context = 1; int main(argc,argv) int argc; char **argv; { SSL_CTX *ctx; SSL *ssl; BIO *sbio; int sock; extern char *optarg; int c; while((c=getopt(argc,argv,"h:p:ia:r"))!=-1){ switch(c){ case 'h': if(!(host=strdup(optarg))) err_exit("Out of memory"); break; case 'p': if(!(port=atoi(optarg))) err_exit("Bogus port specified"); break; case 'i': require_server_auth=0; break; case 'a': if(!(ciphers=strdup(optarg))) err_exit("Out of memory"); break; } } /* Build our SSL context*/ ctx=initialize_ctx(KEYFILE,PASSWORD); /* Set our cipher list */ if(ciphers){ SSL_CTX_set_cipher_list(ctx,ciphers); } SSL_CTX_set_session_id_context(ctx, (void*)&s_server_session_id_context, sizeof s_server_session_id_context); /* Connect the TCP socket*/ sock=tcp_connect(host,port); /* Connect the SSL socket */ ssl=SSL_new(ctx); sbio=BIO_new_socket(sock,BIO_NOCLOSE); SSL_set_bio(ssl,sbio,sbio); if(SSL_connect(ssl)<=0) berr_exit("SSL connect error"); check_cert(ssl,host); /* read and write */ read_write(ssl,sock); destroy_ctx(ctx); exit(0); }
C
/* * Copyright 2014 Chen Ruichao <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (__STDC_VERSION__ >= 199901L) # include <stdbool.h> #else typedef enum { false, true = !false } bool; #endif #include <stdio.h> #include <string.h> #define maxN 10000000 #define maxP 664579 /* number of prime numbers */ #define maxQ 10000 typedef long long lint; lint R; bool np[maxN+1]; int plist[maxP], pcnt; lint fac[maxN+1], *inv=fac, f[maxN+1]; /* f[M] = φ(M!)/M! */ int QN[maxQ], QM[maxQ]; /* we use the same array for inverse and factorial to save memory space */ void work(void) { int Q, N, i, j; R = 0; scanf("%d%d", &Q, (int*) &R); /* only works on little-endian machines */ N = 0; for(i=0; i<Q; i++) { scanf("%d%d", QN+i, QM+i); if(N < QN[i]) N = QN[i]; } inv[1] = 1; f [1] = 1; pcnt = 0; memset(np+1, false, sizeof(np[0])*N); for(i=2; i<=N; i++) { inv[i] = (-R/i*inv[R%i] % R + R) % R; if(!np[i]) { f[i] = f[i-1] * (i-1) % R * inv[i] % R; plist[pcnt++] = i; } else f[i] = f[i-1]; // (f[i] = f[i-1] * i * inv[i]) for(j=0; j<pcnt && i*plist[j] <= N; j++) { np[i * plist[j]] = true; if(i % plist[j] == 0) break; } } fac[1] = 1; for(i=2; i<=N; i++) fac[i] = fac[i-1] * i % R; for(i=0; i<Q; i++) printf("%d\n", (int)(fac[ QN[i] ] * f[ QM[i] ] % R)); } int main(void) { freopen("cash.in" ,"r",stdin ); freopen("cash.out","w",stdout); work(); return 0; }
C
#include <stdio.h> #include <unistd.h> #define claimedMemory syscall(354) #define freeMemory syscall(353) int main() { float fragmentation; printf("Running 3 tests:\n"); int i; for (i = 0; i < 3; i++) { fragmentation = (float)freeMemory / (float)claimedMemory; printf("Claimed Memory: \t%lu\n", claimedMemory); printf("Free Memory: \t\t%lu\n", freeMemory); printf("Fragmentation: \t\t%f\n", fragmentation); printf("-----\n"); sleep(1); } }
C
void putnonintrablk(short *blk) { int n, run, signed_level, first; run = 0; first = 1; for (n = 0;n<1<<6;n++) { /* use appropriate entropy scanning pattern */ signed_level = blk[(altscan?alternate_scan:zig_zag_scan)[n]]; if (signed_level!=0) { if (first) { /* first coefficient in non-intra block */ putACfirst(run, signed_level); first = 0; } else putAC(run, signed_level, 0); run = 0; } else run++; } /* End of Block -- normative block punctuation */ putbits(2, 2); }
C
/************************* SELECT C File Author : Yonatan Zaken Date : 05/04/2020 *************************/ #define _POSIX_C_SOURCE 200112L #include <stdio.h> /* stderr */ #include <stdlib.h> #include <string.h> /* memset */ #include <unistd.h> /* close */ #include <sys/types.h> #include <sys/socket.h> /* socket */ #include <netinet/in.h> #include <arpa/inet.h> /* inet_ntop */ #include <netdb.h> /* getaddrinfo */ #include <sys/select.h> /* select */ #include "socket.h" #define PORT "4443" /* port we're listening on*/ #define BACKLOG 10 #define MAXBUFLEN 50 /******************************* declarations ********************************/ /*int GetSocket(int family, int socktype, int flags);*/ /*int SearchInternetAddr(struct addrinfo* node);*/ void InitTimeVal(struct timeval *tv); void HandleConnections(fd_set *master, int *fdmax, int listener); void CloseConnection(int nbytes, int index, fd_set *master); int TCPDataTransfer(int sockfd, fd_set *master); int UDPDataTransfer(int sockfd); int MonitorSockets(int listener, int udp_fd); /*****************************************************************************/ int main(int argc, char *argv[]) { int listener = 0; int udp_fd = 0; struct addrinfo hints = {0}; InitHints(&hints, AF_INET, SOCK_STREAM, AI_PASSIVE); if (-1 == (listener = GetSocket("y10", PORT, &hints, TCP, SERVER))) { return 1; } if (-1 == listen(listener, BACKLOG)) { perror("listen"); close(listener); return 1; } InitHints(&hints, AF_INET, SOCK_DGRAM, AI_PASSIVE); if (-1 == (udp_fd = GetSocket("y10", PORT, &hints, UDP, SERVER))) { return 1; } if (-1 == MonitorSockets(listener, udp_fd)) { return 1; } return 0; } /******************************************************************************/ /* int GetSocket(int family, int socktype, int flags) { struct addrinfo hints = {0}; struct addrinfo *addr_info = NULL; int socket = 0; int rv = 0; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = socktype; hints.ai_flags = flags; if (0 != (rv = getaddrinfo(NULL, PORT, &hints, &addr_info))) { fprintf(stderr, "selectserver: %s\n", gai_strerror(rv)); return -1; } if (-1 == (socket = SearchInternetAddr(addr_info))) { return -1; } freeaddrinfo(addr_info); return socket; } */ void InitTimeVal(struct timeval *tv) { tv->tv_sec = 5; tv->tv_usec = 0; } /* int SearchInternetAddr(struct addrinfo* node) { struct addrinfo *runner = NULL; int sockfd = 0; int yes = 1; for(runner = node; runner != NULL; runner = runner->ai_next) { if (-1 == (sockfd = socket(runner->ai_family, runner->ai_socktype, runner->ai_protocol))) { perror("server: socket"); continue; } if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))) { perror("setsockopt"); return -1; } if (-1 == bind(sockfd, runner->ai_addr, runner->ai_addrlen)) { close(sockfd); perror("server: bind"); continue; } break; } if (NULL == runner) { fprintf(stderr, "server: failed to bind\n"); sockfd = -1; } return sockfd; } */ /******************************************************************************/ void HandleConnections(fd_set *master, int *fdmax, int listener) { struct sockaddr_storage remoteaddr = {0}; socklen_t addrlen = {0}; int newfd = 0; char remoteIP[INET_ADDRSTRLEN] = {0}; addrlen = sizeof(remoteaddr); newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen); if (-1 == newfd) { perror("accept"); } else { FD_SET(newfd, master); if (newfd > *fdmax) { *fdmax = newfd; } printf("selectserver: new connection from %s on socket %d\n", inet_ntop(remoteaddr.ss_family, &(((struct sockaddr_in *)&remoteaddr)->sin_addr), remoteIP, INET_ADDRSTRLEN), newfd); } } /******************************************************************************/ void CloseConnection(int num_of_bytes, int index, fd_set *master) { if (0 == num_of_bytes) { printf("selectserver: socket %d hung up\n", index); } else { perror("recv"); } close(index); FD_CLR(index, master); } /******************************************************************************/ int TCPDataTransfer(int sockfd, fd_set *master) { char msg_to_send[MAXBUFLEN] = {0}; char buffer[MAXBUFLEN] = {0}; int num_of_bytes = 0; if (STDIN_FILENO == sockfd) { if (-1 == read(STDIN_FILENO, msg_to_send, sizeof(msg_to_send))) { perror("read"); return -1; } msg_to_send[strlen(msg_to_send) - 1] = '\0'; if (-1 == write(STDOUT_FILENO, msg_to_send, strlen(msg_to_send))) { perror("write"); return -1; } return 0; } if (0 >= (num_of_bytes = recv(sockfd, buffer, sizeof(buffer), 0))) { CloseConnection(num_of_bytes, sockfd, master); } else { printf("message from tcp client: %s\n",buffer); if (-1 == send(sockfd, "pong\0", 5, 0)) { perror("send"); return -1; } } return 0; } /******************************************************************************/ int UDPDataTransfer(int sockfd) { struct sockaddr_storage their_addr = {0}; socklen_t addr_len; char buffer[MAXBUFLEN] = {0}; char pong[5] = "pong"; addr_len = sizeof(their_addr); if (-1 == (recvfrom(sockfd, buffer, MAXBUFLEN - 1 , 0, (struct sockaddr *)&their_addr, &addr_len))) { perror("recvfrom"); return -1; } printf("message from client: %s\n", buffer); if (-1 == (sendto(sockfd, pong, strlen(pong), 0, (struct sockaddr *)&their_addr, addr_len))) { perror("sendto"); return -1; } return 0; } /******************************************************************************/ int MonitorSockets(int listener, int udp_fd) { fd_set master = {0}; fd_set read_fds = {0}; struct timeval tv = {0}; int fdmax = 0; int i = 0; InitTimeVal(&tv); FD_ZERO(&master); FD_ZERO(&read_fds); FD_SET(listener, &master); FD_SET(udp_fd, &master); FD_SET(STDIN_FILENO, &master); fdmax = listener > udp_fd ? listener : udp_fd; while(1) { read_fds = master; if (-1 == select(fdmax+1, &read_fds, NULL, NULL, &tv)) { perror("select"); return 1; } for(i = 0; i <= fdmax; ++i) { if (FD_ISSET(i, &read_fds)) { if (i == listener) { HandleConnections(&master, &fdmax, listener); } else if (i == udp_fd) { if (-1 == UDPDataTransfer(i)) { close(i); FD_CLR(i, &master); } } else if (-1 == TCPDataTransfer(i, &master)) { close(i); FD_CLR(i, &master); } } } } return 0; }
C
#include "adc.h" #include <util/delay.h> uint8_t _adc_mode; RingBuffer* _adc_buffer; // Sets the sampling schedule for the different ADC channels. uint8_t* _adc_mux_schedule; uint8_t _adc_schedule_mask; volatile uint8_t _adc_busy; /*uint8_t _findbit(uint8_t needle, uint8_t haystack){ ++needle; uint8_t pos = 0; uint8_t counter = 0; while(pos < 8 && counter < needle){ if(haystack & (1<<pos)){ ++counter; if(counter != needle){ ++pos; } } else{ ++pos; } } return pos; }*/ // This guy handles storing the ADC result when it is done ISR (ADC_vect) { unsigned char tmphead; #ifdef DEBUG ADC_OUT_ON(); #endif // Equivalent to head = (head+1) mod adc_buffer_len tmphead = ( _adc_buffer->head + 1) & _adc_buffer->mask; if(tmphead == _adc_buffer->tail){ // Overwrite the old contents of the buffer. _adc_buffer->tail = (tmphead + 1) & _adc_buffer->mask; } // This is the result from the current scheduled MUX #ifdef DUMMY_ADC_READINGS uint8_t tmp = ((_adc_mux_schedule[(tmphead + _adc_schedule_mask - 1) & _adc_schedule_mask] & ~((1 << ADLAR) | (ADC_REFERENCE << REFS0))) >> MUX0); if(tmp < 10){ _adc_buffer->buffer[tmphead] = '0'+tmp; } else{ _adc_buffer->buffer[tmphead] = ('A'-10)+tmp; } //_adc_buffer->buffer[tmphead] = tmp; #else _adc_buffer->buffer[tmphead] = adc_read(); #endif _adc_buffer->head = tmphead; // The MUX schedule tmphead = tmphead & _adc_schedule_mask; if(_adc_mode == ADC_MODE_MANUAL){ _adc_busy = 1; // Stop auto-converting on the next-to-last element of the // schedule, since the last element of the schedule is // already running. if(tmphead == _adc_schedule_mask){ ADCSRA &= ~(1<<ADATE); } // Re-enable auto-converting on the last element of the schedule, // so that the next ADC trigger will trigger the schedule to // run again. else if(tmphead == 0){ ADCSRA |= (1<<ADATE); _adc_busy = 0; } } ADMUX = _adc_mux_schedule[tmphead]; #ifdef DEBUG ADC_OUT_OFF(); #endif } void adc_trigger(void){ _adc_busy = 1; // Set the MUX for the first conversion. // We have rotated the schedule to the left by 1, so this is the first element of the schedule. // remember, that adc_schedule_mask is nothing more than adc_schedule_len - 1 ADMUX = _adc_mux_schedule[(_adc_buffer->head + _adc_schedule_mask) & _adc_schedule_mask]; // Start the conversion ADCSRA = (1 << ADATE) | (1<<ADEN) | (1<<ADIE) | (ADC_PRESCALER << ADPS0) | (1<<ADSC) | (1<<ADIF); // delay loop 2 has four CPU cycles per iteration, so wait four CPU cycles past the first ADC cycle. // we must do this to ensure that the MUX really gets set. _delay_loop_2(((1<<ADC_PRESCALER)/4) + 1); // Set the MUX for the next conversion. // We have rotated the schedule to the left by 1, so this is the second element of the schedule. ADMUX = _adc_mux_schedule[(_adc_buffer->head) & _adc_schedule_mask]; } void adc_disable(void){ _adc_busy = 0; ADCSRA = (1<<ADIF); } uint8_t adc_is_busy(void){ return _adc_busy; } void adc_enable(){ #ifdef ADHSM ADCSRB = (1<<ADHSM) | ((_adc_mode & 0xF) << ADTS0); #else ADCSRB = (_adc_mode & 0xF) << ADTS0; #endif // Enable the ADC. We use the auto conversion mode to make the // muxed measurements as close as possible together. ADCSRA = (1 << ADATE) | (1<<ADEN) | (1<<ADIE) | (ADC_PRESCALER << ADPS0) | (1<<ADIF); } void adc_encode_muxSchedule(uint8_t* scheduleIndices, uint8_t scheduleLen){ uint8_t scheduleMask = scheduleLen-1; uint8_t i; uint8_t j; uint8_t tmp; /*if(scheduleLen & scheduleMask){ // must be a power of two return; }*/ // Pre-populate the left-adjust bit into the mux schedule, so you don't have to do it in the ISR for(i = 0; i < scheduleLen; ++i){ scheduleIndices[i] = (1 << ADLAR) | (ADC_REFERENCE << REFS0) | (scheduleIndices[i] << MUX0); } // Shift the mux schedule left by 1. This is done so that the ISR code can be as fast as possible. i=0; for(i=0; i < scheduleLen-1; ++i){ // i is source index // j is destination index j = (i + scheduleLen - 1) & scheduleMask; // swap contents mux elements i and j tmp = scheduleIndices[j]; scheduleIndices[j] = scheduleIndices[i]; scheduleIndices[i] = tmp; } } void adc_reset_schedule(void){ _adc_buffer->head = 0; _adc_buffer->tail = 0; } uint16_t adc_single_conversion(uint8_t muxVal){ uint16_t ret; ADCSRA = 0; ADMUX = (1<<ADLAR) | (ADC_REFERENCE << REFS0) | ((muxVal & 0xF) << MUX0); ADCSRA = (1<<ADEN) | (ADC_PRESCALER << ADPS0) | (1<<ADSC) | (1<<ADIF); while(ADCSRA & (1<<ADSC)){ // Wait until the ADC is populated. } ret = ADC; ADCSRA = (1 << ADATE) | (1<<ADEN) | (1<<ADIE) | (ADC_PRESCALER << ADPS0) | (1<<ADIF); return ret; } /* The sequence of ADC measurement goes: 1. Set MUX=0 2. Trigger ADC 3. Wait 1 ADC cycle 4. Set MUX=1 5. 0: Read ADC (MUX=0), auto-trigger ADC Set MUX=2 1: Read ADC (MUX=1), auto-trigger ADC Set MUX=3 n-1: Read ADC (MUX=n-1), auto-trigger ADC Set MUX=n+2 Alternately, you can left-shift the MUX schedule first, and then replace with 1. Set MUX-2=n-2 2. Trigger ADC 3. Wait 1 ADC cycle 4. Set MUX-2=n-1 5. 0: Read ADC (MUX-2=n-2), auto-trigger ADC Set MUX-2=0 1: Read ADC (MUX-2=n-1), auto-trigger ADC Set MUX-2=1 2: Read ADC (MUX-2=0), auto-trigger ADC Set MUX-2=2 n-1: Read ADC (MUX-2=n-3), auto-trigger ADC Set MUX-2=n */ void adc_init( uint8_t mode, RingBuffer* buffer, uint8_t* muxSchedule, uint8_t scheduleLen) { #ifdef DEBUG ADC_OUT_DDR |= 1<<ADC_OUT_PIN; #endif uint16_t mask = 0; uint8_t i; adc_disable(); // Store the memory locations. _adc_mode = mode; _adc_buffer = buffer; _adc_mux_schedule = muxSchedule; _adc_schedule_mask = scheduleLen-1; /*if ( adc_buffer->size & adc_buffer->mask || scheduleLen & adc_schedule_mask){ // RX buffer size is not a power of 2 return; }*/ for (i = 0; i < scheduleLen; ++i){ mask |= 1 << ((muxSchedule[i] & ~((1 << ADLAR) | (ADC_REFERENCE << REFS0))) >> MUX0); } //DIDR0 = mask & 0x1F; // Because ADC6 and ADC7 do not have digital input buffers, you don't have to disable them. DIDR0 |= mask & 0xFF; DIDR1 |= (mask >> 8) & 0xFF; adc_enable(); }
C
#include<stdio.h> #include<stdlib.h> int totaltime=0; void choose(int **box,int n) { int i,j =0,a; int temp; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - 1; j++) { if (box[j][1] > box[j + 1][1]) { temp = box[j][1]; box[j][1] = box[j+1][1]; box[j + 1][1] = temp; temp = box[j][0]; box[j][0] = box[j + 1][0]; box[j + 1][0] = temp; temp = box[j][2]; box[j][2] = box[j + 1][2]; box[j + 1][2] = temp; } } } for (i = 0; i < n - 1; i++) { for (j = 0; j < n - 1; j++) { if (box[j][1] == box[j + 1][1]) { if (box[j][0] > box[j + 1][0]) { temp = box[j][1]; box[j][1] = box[j + 1][1]; box[j + 1][1] = temp; temp = box[j][0]; box[j][0] = box[j + 1][0]; box[j + 1][0] = temp; temp = box[j][2]; box[j][2] = box[j + 1][2]; box[j + 1][2] = temp; } } } } } void cal(int **box,int n, FILE *oup) { int i,m; int wait=0; for (i = 0; i < n;i++) { if (box[i][1] == 0 && totaltime == 0) { totaltime += box[i][2]; } else if (box[i][1] != 0 && totaltime == 0) { totaltime = box[i][2]; } else if (totaltime < box[i][1]) { m = box[i][1] - totaltime; totaltime = totaltime + m + box[i][2]; } else { wait = wait + totaltime - box[i][1]; totaltime = totaltime + box[i][2]; } } fprintf(oup,"%d", wait); } int main() { FILE *inp, *oup; inp = fopen("fcfs.inp","r"); oup = fopen("fcfs.out", "w"); int **box; int n,i,j,k; fscanf(inp, "%d\n", &n); box = (int**)malloc(sizeof(int*)*n); for (k = 0; k<n; k++) { box[k] = (int*)malloc(sizeof(int) * 3); } for (i=0;i<n;i++) { fscanf(inp,"%d %d %d\n",&box[i][0],&box[i][1],&box[i][2]); } choose(box, n); for (i = 0; i < n; i++) { for (j = 0; j < 3; j++) { printf("%d ", box[i][j]); } printf("\n"); } cal(box,n,oup); fclose(inp); fclose(oup); return 0; }
C
// Copyright (2018) Baidu Inc. All rights reserved. /** * File: lightduer_flash.h * Auth: Sijun Li([email protected]) * Desc: Common defines for flash strings module. */ #ifndef BAIDU_DUER_LIGHTDUER_FLASH_H #define BAIDU_DUER_LIGHTDUER_FLASH_H #ifdef __cplusplus extern "C" { #endif #include "lightduer_types.h" #define FLASH_MAGIC 0x56BD50C4 #define FLASH_MAGIC_BITMASK 0xffffffff #define FLASH_LEN_BITMASK 0xffffffff #define FLASH_INVALID_ADDR 0xffffffff typedef enum { DUER_ERR_FLASH_CORRUPT = -2, DUER_ERR_FLASH_FULL = -3, }duer_flash_errcode; /* * Configuration of flash operations. * xxx_align_bits: Number of last bits of address to be aligned. * For example, Bits=5 indicates header's last 5 bits are '0'. */ typedef struct { // For erase. int sector_align_bits; // For write. int page_align_bits; // For read. int word_align_bits; } duer_flash_config_t; typedef struct { void *handle; unsigned int len; void *object; } duer_flash_context_t; typedef struct { unsigned int magic; // Magic number to check data valid; unsigned int len; // Length of payload string; // Used to know the sequence of the data in the flash, it's used in flash ring buf unsigned int sequence_num; } duer_flash_data_header; inline unsigned int flash_addr_align_floor(unsigned int addr, int bits) { addr >>= bits; addr <<= bits; return addr; } inline unsigned int flash_addr_align_ceil(unsigned int addr, int bits) { unsigned int bitmask = (1 << bits) - 1; if (addr & bitmask) { addr >>= bits; addr += 1; addr <<= bits; } return addr; } inline unsigned int flash_addr_cycle(unsigned int addr, int size) { if (addr >= size) { return (addr - size); } else { return addr; } } /** * DESC: * Developer needs to implement this interface to read flash. * * @PARAM[in] ctx: pointer of context. * @PARAM[in] addr: the address offset of flash to read. * @PARAM[out] buf: the buffer to store read data. * @PARAM[in] len: length of byte to read. * * @RETURN: 0 when success, else when fail. */ extern int duer_flash_read( duer_flash_context_t *ctx, unsigned int addr, void *buf, unsigned int len); /** * DESC: * Developer needs to implement this interface to write flash. * * @PARAM[in] ctx: pointer of context. * @PARAM[in] addr: the address offset of flash to write. * @PARAM[in] buf: the buffer stored writing data. * @PARAM[in] len: length of byte to write. * * @RETURN: 0 when success, else when fail. */ extern int duer_flash_write( duer_flash_context_t *ctx, unsigned int addr, void *buf, unsigned int len); /** * DESC: * Developer needs to implement this interface to erase flash. * * @PARAM[in] ctx: pointer of context. * @PARAM[in] addr: the address offset start of flash to erase. * @PARAM[in] len: length of byte to erase. * * @RETURN: 0 when success, else when fail. */ extern int duer_flash_erase( duer_flash_context_t *ctx, unsigned int addr, unsigned int len); int duer_payload_write_flash( duer_flash_context_t *ctx, unsigned int addr_start, duer_flash_data_header *p_flash_header, const char *payload_string, int payload_len, int page_size); #ifdef __cplusplus } #endif #endif//BAIDU_DUER_LIGHTDUER_FLASH_H
C
#include <stdio.h> #include <string.h> #include <stdlib.h> // initializing functions float get_num(); char get_op(); float m_exp(float sub_exp, char op); float s_exp(float sub_exp, char op); int main() { char choice; printf("Please enter a simple arithmetic expression: "); float ans = s_exp(0, '+'); printf("%.2f\n", ans); printf("Do you want to Continue? Y/N: "); scanf("%c", &choice); if (choice == 'Y') main(); else exit; } float s_exp(float sub_exp, char op) { // when op is \n it's the end of the expression so return it. if (op == '\n') return sub_exp; // otherwise call m_exp because it's not the end of the expression else { float f1 = m_exp(1, '*'); // regets the op used in m_exp char op1 = get_op(); if (op == '+') f1 = sub_exp + f1; else if (op == '-') f1 = sub_exp - f1; return s_exp(f1, op1); } } float m_exp(float sub_exp, char op) { // if it's any of these three, return what you have so far, and unget the op, // this is important because s_exp needs to use that op. if (op == '\n' || op == '+' || op == '-') { ungetc(op, stdin); return sub_exp; } // if it's a * or / do the appropriate calculation on the next num and next op else { float f1 = get_num(); char op1 = get_op(); if (op == '*') f1 = f1 * sub_exp; else if (op == '/') f1 = sub_exp / f1; return m_exp(f1,op1); } } float get_num() { float var; scanf(" %f", &var); return var; } char get_op() { char var; do scanf("%c", &var); while (var == ' '); return var; }
C
#include "header.h" //GLOBAL VARIABLES //They are global because the might be needed in multiple //functions and the signal handler in case of signal //from child processes or SIGINT etc DIR* working_dir = NULL; char* file = NULL; char* dir_name = NULL; //bloom filter info int bloom_size = 0; char* bloom_string = NULL; //pass as argument to exec //number of child process int no_childs = 0; //Buffer size info int buffer = 0; char* buffer_string = NULL; //pass as argument to exec //Array to store the ids of child processes int* pids = NULL; //Array to store the ids of the original child process(in case one terminated) int* terminated_pids = NULL; //Arrays for holding the names and file descriptors of read and write fifos of processes char** write_fifos = NULL; int* write_fds = NULL; char** read_fifos = NULL; int* read_fds = NULL; //Flag so that if parent gets SIGINT signal the execution of the last command continues int current_command = 0; //flag that indicates if the process must terminate after executing last command int sigint_flag = 0; //Structures we will need PIDHASH records = NULL; catalog* country_responsible_pid = NULL; int responsible_size = 0; //variables that store the total number of requests, total number of accepted requests //and total number of rejected requests.These are send to logger int accepted = 0; int requests = 0; int rejected = 0; //flags regarding child processes and signals int waiting = 0; int received = 0; //flag that is 1 if /exit command is given. int termination_flag = 0; //Signal set for sigwait sigset_t set; int sig; int *sigptr = &sig; struct pollfd* global_pfds; //declarations of local functions void free_global_variables(void); void initialize_global_variables(void); int main(int argc, char *argv[]){ //checks if arguments are correct if(argument_check(argc, argv)){ printf("Run command is as follows:\n"); printf("./travelMonitor –m numMonitors -b bufferSize -s sizeOfBloom -i input_dir"); exit(1); } //Initialize signal set sigemptyset(&set); sigaddset(&set, SIGUSR1); sigaddset(&set, SIGCHLD); //Initialize signal handler struct sigaction sa = {0}; sa.sa_handler = monitor_signal_handler; sigaction(SIGINT, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGSEGV, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); initialize_global_variables(); struct pollfd pfds[no_childs]; waiting = no_childs; char buf[buffer]; for(int i = 0 ; i < no_childs ; i++){ //Create read and write fifo file for specific child sprintf(buf, "%d", i+1); write_fifos[i] = malloc(strlen("writefifo") + strlen(buf) + 1); strcpy(write_fifos[i], "writefifo"); strcat(write_fifos[i], buf); sprintf(buf, "%d", i+1); read_fifos[i] = malloc(strlen("readfifo") + strlen(buf) + 1); strcpy(read_fifos[i], "readfifo"); strcat(read_fifos[i], buf); if(mkfifo(write_fifos[i], 0777) == -1){ if(errno != EEXIST){ printf("Could not create fifo file\n"); exit(1); } } if(mkfifo(read_fifos[i], 0777) == -1){ if(errno != EEXIST){ printf("Could not create fifo file\n"); exit(1); } } //Open read fifo if((read_fds[i] = open(read_fifos[i], O_CREAT|O_RDONLY|O_NONBLOCK, 0777)) == -1){ perror("line 78:"); } //Initialize pollfd struct pfds[i].fd = read_fds[i]; pfds[i].events = 0; pfds[i].events |= POLLIN; int tempid = fork(); if(tempid == 0){ if(execl("./Monitor","./Monitor",write_fifos[i], read_fifos[i], bloom_string, buffer_string, "1", "0", (char *)NULL) == -1){ perror("exec :"); exit(1); } }else{ //Wait for children to initialize sigwait(&set,sigptr); //In case the child terminates prematurely exit program if(*sigptr == SIGCHLD){ printf("SIGCHLD before initializing.EXITING\n"); exit(1); } //Accosiate array chells with process ids pids[i] = tempid; terminated_pids[i] = tempid; pid_hash_insert(records, tempid, write_fifos[i], read_fifos[i], i); } //open write fifo file if((write_fds[i] = open(write_fifos[i], O_CREAT | O_WRONLY|O_NONBLOCK, 0777)) == -1){ perror("line 82:"); exit(1); } } //So that they can be accessed from everywhere in the program global_pfds = pfds; struct dirent *dir = NULL; //send work load equally to proccesses int rrobin = 0; //navigate directories while((dir = readdir(working_dir)) != NULL){ if(!strcmp(dir->d_name, ".")) continue; if(!strcmp(dir->d_name, "..")) continue; //create fullpath of file char* fullpath = malloc(strlen(dir_name) + strlen(dir->d_name) + 2); strcpy(fullpath, dir_name); strcat(fullpath,"/"); strcat(fullpath,dir->d_name); //restart indexes if(rrobin > no_childs - 1){ rrobin = 0; } //Add country to catalogs and associate it with the process id that is responsible for it responsible_size++; if(country_responsible_pid == NULL){ country_responsible_pid = malloc(sizeof(catalog) * responsible_size); country_responsible_pid[responsible_size-1] = malloc(sizeof(country_catalog)); country_responsible_pid[responsible_size-1]->country = malloc(strlen(dir->d_name) + 1); strcpy(country_responsible_pid[responsible_size-1]->country, dir->d_name); country_responsible_pid[responsible_size-1]->pid = pids[rrobin]; }else{ country_responsible_pid = realloc(country_responsible_pid,sizeof(catalog) * responsible_size); country_responsible_pid[responsible_size-1] = malloc(sizeof(country_catalog)); country_responsible_pid[responsible_size-1]->country = malloc(strlen(dir->d_name) + 1); strcpy(country_responsible_pid[responsible_size-1]->country, dir->d_name); country_responsible_pid[responsible_size-1]->pid = pids[rrobin]; } //Write to proccess that is responsible for country write(write_fds[rrobin], fullpath, strlen(fullpath)); write(write_fds[rrobin], "\n", strlen("\n")); //associate hash table with country and directories pid_hash_search_insert(records, pids[rrobin], fullpath, dir->d_name); rrobin++; free(fullpath); } printf("Sending signals to children\n"); //Inform children parent has finished writting info to fifos for(int i = 0 ; i < no_childs ; i++){ kill(pids[i], SIGUSR1); } //Initialize new set to accept only one signal int ret = 1; int timeout = 5000; //Wait until there is something to read while(ret > 0){ ret = poll(global_pfds, no_childs, timeout); if(ret == -1) perror("246"); if(ret > 0){ for(int i = 0 ; i < no_childs ; i++){ //if there is data to read if(global_pfds[i].revents == POLLIN){ int size = 0; char* desease = NULL; //read size of the next send info if(read(global_pfds[i].fd, &size, sizeof(int)) == -1){ perror("257"); } //Inform child you have read first message kill(pids[i],SIGUSR1); //wait for child to write another message while(received == 0); received = 0; //If the word length send is smaller than the buffer //one read if(size <= buffer && size > 0){ char temp_buf[size]; if(read(global_pfds[i].fd, temp_buf, size) == -1){ perror("276:"); } desease = malloc(size + 1); for(int j = 0 ; j < size ; j++){ desease[j] = temp_buf[j]; } desease[size] = '\0'; }else{ //else if the buffer is not enough //Calculate how many reads it will take to rea int divi = size / buffer; int mod = size % buffer; desease = malloc(size + 1); for(int j = 0 ; j < divi ; j++){ if(read(global_pfds[i].fd, buf, buffer) == -1){ perror("294:"); } if(j==0){ for(int k = 0 ; k < buffer ; k++){ desease[k] = buf[k]; } desease[(j+1)*buffer] = '\0'; }else{ int n = 0; for(int k = j*buffer ; k < (j+1)*buffer ; k++){ desease[k] = buf[n]; n++; } desease[(j+1)*buffer] = '\0'; } } if(mod > 0){ char temp_buf[mod]; if(read(global_pfds[i].fd,temp_buf,mod) == -1){ perror("316"); } int n = 0; for(int j = divi * buffer ; j < divi * buffer + mod ; j++){ desease[j] = temp_buf[n]; n++; } desease[divi * buffer + mod] = '\0'; } } //inform and wait kill(pids[i],SIGUSR1); while(received == 0); received = 0; //read size of bloom filter send if(read(global_pfds[i].fd, &size, sizeof(int)) == -1){ perror("245"); } //inform and wait kill(pids[i],SIGUSR1); while(received == 0); received = 0; //allocate temporary bloom int* temp_bloom = malloc(sizeof(int) * size); //if the size is smaller than the buffer and the size of the bloom filter //is not that large to block the pipe,read it in one go if(size <= buffer && size <= 10000){ if(read(read_fds[i], temp_bloom, sizeof(int) * size) == -1){ perror("251"); } }else{ //else calculate how many reads it will take int div = size / buffer; int mod = size % buffer; for(int j = 0 ; j < div ; j++){ //continue reading from pointer if(read(read_fds[i], &temp_bloom[j*buffer], sizeof(int)*buffer) == -1){ perror("273"); } //inform and wait kill(pids[i], SIGUSR1); while(received == 0); received = 0; } if(mod > 0){ if( read(read_fds[i], &temp_bloom[div], sizeof(int)*mod) == -1){ perror("281"); } } } //initialize or update bloom filter for a specific desease for all countries pid_hash_initialize_bloom(records, pids[i], desease, temp_bloom); free(temp_bloom); free(desease); desease = NULL; //reinitialize pollfd global_pfds[i].fd = read_fds[i]; global_pfds[i].events = POLLIN; printf("Data read %d\n",pids[i]); } } } } //go to command line(Line 661) command_line(); } //signal handler for travleMonitor void monitor_signal_handler(int sig){ switch (sig){ case SIGUSR1: received = 1; break; case SIGUSR2: waiting--; break; case SIGINT: case SIGQUIT: //raise termination flag termination_flag = 1; //if parent was in the middle of executing a command return if(current_command){ //raise flag so that the parent will know after execution of last command to terminate sigint_flag = 1; break; } //close file descriptors, delete files and kill children processes for(int i = 0 ; i < no_childs ; i++){ close(write_fds[i]); close(read_fds[i]); unlink(write_fifos[i]); unlink(read_fifos[i]); free(write_fifos[i]); free(read_fifos[i]); kill(pids[i],SIGKILL); } free_global_variables(); exit(1); break; case SIGCHLD: //if a child terminated and parent is not ready to exit execution //reinitialize child process.Else ignore SIGCHLD to terminate program if(termination_flag == 0){ int temppid = -1; int wstatus; //find the id of the terminated child if((temppid = wait(&wstatus))){ printf("terminated child = %d\n",temppid); if(WIFSIGNALED(wstatus)){ printf("%d\n",WTERMSIG(wstatus)); } //return the fifos associated with previous process char* rfile = pid_hash_return_read_fifo(records, temppid); char* wfile = pid_hash_return_write_fifo(records, temppid); char temp_buf[1024]; //find the index of the global variables that info of the terminated //process is stored int temp_index = pid_hash_return_index(records, temppid); //convert the first proccess that was terminated id into a string //to pass as argument.This is in case there have been multiple terminations //of processes responsible for same countries.So that all the next processes //read the file of the first process and reinitialize the structures sprintf(temp_buf, "%d", terminated_pids[temp_index]); int new_id = fork(); if(new_id == 0){ if(execl("./Monitor","./Monitor", wfile, rfile, buffer_string, buffer_string, "0", temp_buf, (char *)NULL) == -1){ perror("exec :"); exit(1); } }else{ sigwait(&set, sigptr); //change all the structures associated with previous id to new process id change_catalog_pid(country_responsible_pid, responsible_size, temppid, new_id); int index = pid_hash_update(records, temppid, new_id); pids[index] = new_id; } } } break; case SIGSEGV: printf("Segmentation fault\n"); //delete files and kill children process and then exit for(int i = 0 ; i < no_childs ; i++){ close(write_fds[i]); close(read_fds[i]); unlink(write_fifos[i]); unlink(read_fifos[i]); kill(pids[i],SIGKILL); } exit(1); break; default: break; } } //check if arguments are passed properly int argument_check(int argc, char* argv[]){ if(argc < 9){ printf("Not enough arguments\n"); return 1; }else if(argc > 9){ printf("Too many arguments\n"); return 1; }else{ int iflag = 0; int bflag = 0; int mflag = 0; int sflag = 0; for(int i = 1 ; i < argc ; i += 2){ if(!strcmp(argv[i],"-i")){ iflag++; if(iflag == 2){ printf("-i flag is repeated\n"); return 1; } if(!strcmp(argv[i+1],"-s")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-m")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-b")){ printf("Arguments are in the wrong order\n"); return 1; } if((working_dir = opendir(argv[i+1])) == NULL){ perror("file :"); return 1; } dir_name = argv[i+1]; }else if(!strcmp(argv[i],"-s")){ sflag++; if(sflag == 2){ printf("-s flag is repeated\n"); return 1; } if(!strcmp(argv[i+1],"-i")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-m")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-b")){ printf("Arguments are in the wrong order\n"); return 1; } for(int j = 0 ; j < strlen(argv[i+1]) ; j++){ if(!isdigit(argv[i+1][j])){ printf("Argument after -s flag must be a number\n"); return 1; } } bloom_size = atoi(argv[i+1]); bloom_string = malloc(strlen(argv[i+1]) + 1); strcpy(bloom_string, argv[i+1]); if(bloom_size < 10){ printf("Bloom size cant be less than 10. Setting bloom size to default value\n"); bloom_size = default_bloom_size; free(bloom_string); bloom_string = malloc(strlen(default_bloom_string_size) + 1); strcpy(bloom_string, default_bloom_string_size); } set_bloom_size(bloom_size); }else if(!strcmp(argv[i], "-m")){ mflag++; if(mflag == 2){ printf("-m flag is repeated\n"); return 1; } if(!strcmp(argv[i+1],"-i")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-s")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-b")){ printf("Arguments are in the wrong order\n"); return 1; } for(int j = 0 ; j < strlen(argv[i+1]) ; j++){ if(!isdigit(argv[i+1][j])){ printf("Argument after -m flag must be a number\n"); return 1; } } no_childs = atoi(argv[i+1]); if(no_childs <= 0){ printf("Number of child processes cant be 0. Setting number of children to default value\n"); no_childs = DEFAULT_CHILD; } }else if(!strcmp(argv[i], "-b")){ bflag++; if(bflag == 2){ printf("-b flag is repeated\n"); return 1; } if(!strcmp(argv[i+1],"-i")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-s")){ printf("Arguments are in the wrong order\n"); return 1; } if(!strcmp(argv[i+1],"-m")){ printf("Arguments are in the wrong order\n"); return 1; } for(int j = 0 ; j < strlen(argv[i+1]) ; j++){ if(!isdigit(argv[i+1][j])){ printf("Argument after -b flag must be a number\n"); return 1; } } buffer = atoi(argv[i+1]); buffer_string = malloc(strlen(argv[i+1]) + 1); strcpy(buffer_string,argv[i+1]); if(buffer < 1){ printf("Buffer size cant be less than 1. Setting buffer size to default value 1024\n"); buffer = DEFAULT_BUFFER; free(buffer_string); buffer_string = malloc(strlen(DEFAULT_BUFFER_STRING) + 1); strcpy(buffer_string,DEFAULT_BUFFER_STRING); } } } return 0; } } //reads commands from terminal void command_line(){ int flag = 0; do{ printf("\nPlease enter a command\n"); char* copy = NULL; char line[1024]; int len = 1024; //Get user input if((fgets(line, len, stdin)) == NULL){ continue; } //If user input is just newline continue if(!strcmp(line , "\n")){ continue; } //make a copy of user input copy = malloc(strlen(line) + 1); strcpy(copy,line); char** commands; int commands_size = 0; char* saveptr; //break user input into tokens and add them to commands table char* token = strtok_r(copy, " ", &saveptr); commands_size++; commands = malloc(sizeof(char *) * commands_size); commands[0] = malloc(strlen(token) + 1); strcpy(commands[0],token); while(token != NULL){ token = strtok_r(NULL, " ", &saveptr); if(token == NULL) break; commands_size++; commands = realloc(commands, sizeof(char *) * commands_size); commands[commands_size - 1] = malloc(strlen(token) + 1); strcpy(commands[commands_size - 1],token); } //remove newline from last string strtok(commands[commands_size - 1], "\n"); if(!strcmp(commands[0],"/travelRequest")){ current_command = 1; if(!no_of_arguments(commands_size, 6, 0)){ if(is_integer(commands[1])){ if(is_date(commands[2])){ if(is_string(commands[3]) && is_string(commands[4])){ int return_id; //return the process id of the process responsible from given origin country if((return_id = return_catalog_pid(country_responsible_pid, responsible_size,commands[3]))){ int index = -1; //checks the bloom filter to see if we need to comunicate with child process //to confirm request.Else reject it if((index = pid_hash_check_bloom(records, return_id, commands[5], commands[1], commands[3], commands[2])) >= 0){ for(int i = 0 ; i < commands_size ; i++){ //we dont need to send country info if(i != 3 && i != 4){ write(write_fds[index], commands[i], strlen(commands[i])); if(i != commands_size - 1) write(write_fds[index], " ", strlen(" ")); } } kill(pids[index],SIGUSR2); requests++; waiting = 1; int timeout = 5000; int ret = 1; int answer = 0; int gflag = 0; int break_flag = 0; char buf[buffer]; char* chop = NULL; char* string = NULL; //wait for child to write all info while(waiting){ global_pfds[index].fd = read_fds[index]; global_pfds[index].events = 0; global_pfds[index].events |= POLLIN; ret = poll(global_pfds, no_childs, timeout); if(ret > 0){ int size = 0; //read size of answer read(global_pfds[index].fd, &size, sizeof(int)); //read info in one go if(size <= buffer && size > 0){ char temp_buf[size]; if(read(global_pfds[index].fd, temp_buf, size) == -1){ perror("769"); } string = malloc(size + 1); for(int j = 0 ; j < size ; j++){ string[j] = temp_buf[j]; } string[size] = '\0'; }else{ //else construct returned info int divi = size / buffer; int mod = size % buffer; string = malloc(size + 1); for(int j = 0 ; j < divi ; j++){ if(read(global_pfds[index].fd, buf, buffer) == -1){ perror("785:"); } if(j==0){ for(int k = 0 ; k < buffer ; k++){ string[k] = buf[k]; } string[(j+1)*buffer] = '\0'; }else{ int n = 0; for(int k = j*buffer ; k < (j+1)*buffer ; k++){ string[k] = buf[n]; n++; } string[(j+1)*buffer] = '\0'; } } if(mod > 0){ char temp_buf[mod]; if(read(global_pfds[index].fd,temp_buf,mod) == -1){ perror("807"); } int n = 0; for(int j = divi * buffer ; j < divi * buffer + mod ; j++){ string[j] = temp_buf[n]; n++; } string[divi * buffer + mod] = '\0'; } } char* saveptr = NULL; chop = strtok_r(string," ", &saveptr); //error in reading if(chop == NULL){ printf("Error %s\n",chop); gflag = -1; break; } //if answer is YES if(!strcmp(chop, "YES")){ //take the date chop = strtok_r(NULL," ",&saveptr); //Again error if(chop == NULL){ printf("Error %s\n",chop); gflag = -1; break; } //See if vaccination date is after travel date and reject if(compareDate(chop, commands[2]) >= 0){ printf("Vaccination date cant be bigger than travel date.Error\n"); gflag = -1; break; } //check if vaccination date was less than 6 months before travel date if(six_months_prior(chop, commands[2])){ printf("REQUEST ACCEPTED – HAPPY TRAVELS\n"); accepted++; answer = 1; break; }else{ printf("REQUEST REJECTED – YOU WILL NEED ANOTHER VACCINATION BEFORE TRAVEL DATE\n"); rejected++; break; } }else if(!strcmp(chop, "NO")){ printf("REQUEST REJECTED – YOU ARE NOT VACCINATED\n"); rejected++; break; }else{ printf("Error %s\n",chop); gflag = -1; break; } }else{ //If poll times out two times break break_flag++; if(break_flag == 2) break; printf("Waiting for answer\n"); } } if(string) free(string); //if there was no error record new request if(gflag != -1) pid_new_request(records, return_id, commands[3], commands[5], commands[2], answer); }else{ printf("REQUEST REJECTED – YOU ARE NOT VACCINATED\n"); rejected++; } }else{ printf("Origin country does not exist\n"); } } }else{ printf("Third argument must be a date\n"); } }else{ printf("Second argument must be an integer\n"); } } }else if(!strcmp(commands[0],"/travelStats")){ current_command = 1; if(!no_of_arguments(commands_size, 4, 5)){ if(commands_size == 5){ if(is_date(commands[2]) && is_date(commands[3])){ if(compareDate(commands[2], commands[3])){ if(is_string(commands[4])){ int return_id; //return process id responsible for requested country if((return_id = return_catalog_pid(country_responsible_pid, responsible_size,commands[4]))){ travelStats(records, commands[1], commands[2], commands[3], commands[4], return_id); }else{ printf("Country not found\n"); } }else{ printf("Fourth argument cant contain numbers\n"); } }else{ printf("First date cant be bigger than the second date\n"); } }else{ printf("Second and third argument must be a date\n"); } }else{ //else find requests for all countries travelStats(records, commands[1], commands[2], commands[3], NULL, -1); } } }else if(!strcmp(commands[0],"/addVaccinationRecords")){ current_command = 1; if(!no_of_arguments(commands_size, 2, 0)){ if(is_string(commands[1])){ int return_id; if((return_id = return_catalog_pid(country_responsible_pid, responsible_size,commands[1]))){ //find index for global structures int index = pid_hash_return_index(records, return_id); //same process as when the processes where initializing and sending info //but this time only for one process char buf[buffer]; int ret = 1; int timeout = 2000; waiting = 1; kill(return_id, SIGUSR1); while(waiting); while(ret > 0){ ret = poll(global_pfds, no_childs, timeout); if(ret == -1) perror("957"); if(ret > 0){ if(global_pfds[index].revents == POLLIN){ int size = 0; char* desease = NULL; if(read(global_pfds[index].fd, &size, sizeof(int)) == -1){ perror("967"); } kill(pids[index],SIGUSR1); while(received == 0); received = 0; if(size <= buffer && size > 0){ char temp_buf[size]; if(read(global_pfds[index].fd, temp_buf, size) == -1){ perror("982:"); } desease = malloc(size + 1); for(int j = 0 ; j < size ; j++){ desease[j] = temp_buf[j]; } desease[size] = '\0'; }else{ int divi = size / buffer; int mod = size % buffer; desease = malloc(size + 1); //printf("size = %d divi %d mod %d\n",size,divi,mod); for(int j = 0 ; j < divi ; j++){ if(read(global_pfds[index].fd, buf, buffer) == -1){ perror("999:"); } if(j==0){ for(int k = 0 ; k < buffer ; k++){ desease[k] = buf[k]; } desease[(j+1)*buffer] = '\0'; }else{ int n = 0; for(int k = j*buffer ; k < (j+1)*buffer ; k++){ desease[k] = buf[n]; n++; } desease[(j+1)*buffer] = '\0'; } } if(mod > 0){ char temp_buf[mod]; if(read(global_pfds[index].fd,temp_buf,mod) == -1){ perror("1021"); } int n = 0; for(int j = divi * buffer ; j < divi * buffer + mod ; j++){ desease[j] = temp_buf[n]; n++; } desease[divi * buffer + mod] = '\0'; } } kill(pids[index],SIGUSR1); while(received == 0); received = 0; if(read(global_pfds[index].fd, &size, sizeof(int)) == -1){ perror("1041"); } kill(pids[index],SIGUSR1); while(received == 0); received = 0; int* temp_bloom = malloc(sizeof(int) * size); if(size <= buffer && size <= 10000){ if(read(read_fds[index], temp_bloom, sizeof(int) * size) == -1){ perror("1054"); } }else{ int div = size / buffer; int mod = size % buffer; for(int j = 0 ; j < div ; j++){ if(read(read_fds[index], &temp_bloom[j*buffer], sizeof(int)*buffer) == -1){ perror("1063"); } kill(pids[index], SIGUSR1); while(received == 0); received = 0; } if(mod > 0){ if( read(read_fds[index], &temp_bloom[div], sizeof(int)*mod) == -1){ perror("1076"); } } } //update bloom filters for desease for all countries pid_hash_update_bloom(records, return_id, desease, temp_bloom); free(temp_bloom); free(desease); desease = NULL; global_pfds[index].fd = read_fds[index]; global_pfds[index].events = POLLIN; } } } }else{ printf("Country not found\n"); } }else{ printf("Second argument cant contain numbers\n"); } } }else if(!strcmp(commands[0],"/searchVaccinationStatus")){ current_command = 1; if(!no_of_arguments(commands_size, 2, 0)){ if(is_integer(commands[1])){ //send citizen id to all children to find which one is responsible for it for(int i = 0 ; i < no_childs ; i++){ global_pfds[i].fd = read_fds[i]; global_pfds[i].events = 0; global_pfds[i].events |= POLLIN; if(write(write_fds[i], commands[0], strlen(commands[0])) == -1){ perror("1113"); } write(write_fds[i], " ", strlen(" ")); write(write_fds[i], commands[1], strlen(commands[1])); kill(pids[i], SIGUSR2); } int timeout = 5000; int ret = 1; char word[buffer]; int n = 0; while(ret > 0){ ret = poll(global_pfds, no_childs, timeout); if(ret == -1) perror("1132"); if(ret > 0){ //read all info given by children for(int i = 0 ; i < no_childs ; i++){ if(global_pfds[i].revents == POLLIN){ if((n = read(global_pfds[i].fd, word, buffer)) > 0){ for(int j = 0 ; j < n ; j++){ printf("%c",word[j]); } } global_pfds[i].fd = read_fds[i]; global_pfds[i].events = 0; global_pfds[i].events |= POLLIN; } } } } }else{ printf("Second argument cant contain characters\n"); } } }else if(!strcmp(commands[0],"/exit")){ printf("Exiting program\n"); //to ignore SIGCHLD termination_flag = 1; flag = 1; }else{ printf("Wrong command\n"); } for(int i = 0 ; i < commands_size ; i++){ free(commands[i]); } free(commands); free(copy); //free(line); current_command = 0; //if a sigint was sent during execution of a command //when it finishes resent signal if(sigint_flag){ kill(getpid(), SIGINT); } if(flag) break; }while(1); for(int i = 0 ; i < no_childs ; i++){ kill(pids[i], SIGKILL); close(write_fds[i]); close(read_fds[i]); unlink(write_fifos[i]); unlink(read_fifos[i]); free(write_fifos[i]); free(read_fifos[i]); } free_global_variables(); } //just for the name(code is in pid_print_requests) void travelStats(PIDHASH records, char* desease, char* start_date, char* end_date, char* country, int pid){ if(records == NULL) return; pid_print_requests(records, desease, start_date, end_date, country, pid); } //Initializes the global variables void initialize_global_variables(void){ records = pid_hash_initialize(); pids = malloc(sizeof(int) * no_childs); terminated_pids = malloc(sizeof(int) * no_childs); for(int i = 0 ; i < no_childs ; i++){ pids[i] = -1; terminated_pids[i] = -1; } write_fifos = malloc(sizeof(char*) * no_childs); write_fds = malloc(sizeof(int) * no_childs); read_fifos = malloc(sizeof(char*) * no_childs); read_fds = malloc(sizeof(int) * no_childs); } //frees global variables and deletes temporary reading files void free_global_variables(void){ if(pids != NULL) free(pids); for(int i = 0 ; i < no_childs ; i++){ char buf[100]; sprintf(buf, "%d", terminated_pids[i]); char* temp = malloc(strlen(buf) + strlen(".txt") + 1); strcpy(temp, buf); strcat(temp, ".txt"); unlink(temp); free(temp); } if(terminated_pids != NULL) free(terminated_pids); if(write_fifos != NULL) free(write_fifos); if(read_fifos != NULL) free(read_fifos); if(write_fds != NULL) free(write_fds); if(read_fds != NULL) free(read_fds); if(bloom_string != NULL) free(bloom_string); if(buffer_string != NULL) free(buffer_string); if(working_dir != NULL) closedir(working_dir); pid_hash_free(records); //returns all countries the program was responsible for to send to logger char** temp = return_catalog_countries(country_responsible_pid, responsible_size); //call logger and create log_file logger(getpid(), temp, responsible_size, requests, accepted, rejected); for(int i = 0 ; i < responsible_size ; i++){ free(temp[i]); } free(temp); free_catalog(country_responsible_pid, responsible_size); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int u8 ; /* Variables and functions */ int /*<<< orphan*/ os_snprintf (char*,int,char*,int const) ; void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len) { char *end = txt + maxlen; size_t i; for (i = 0; i < len; i++) { if (txt + 4 >= end) break; switch (data[i]) { case '\"': *txt++ = '\\'; *txt++ = '\"'; break; case '\\': *txt++ = '\\'; *txt++ = '\\'; break; case '\033': *txt++ = '\\'; *txt++ = 'e'; break; case '\n': *txt++ = '\\'; *txt++ = 'n'; break; case '\r': *txt++ = '\\'; *txt++ = 'r'; break; case '\t': *txt++ = '\\'; *txt++ = 't'; break; default: if (data[i] >= 32 && data[i] <= 127) { *txt++ = data[i]; } else { txt += os_snprintf(txt, end - txt, "\\x%02x", data[i]); } break; } } *txt = '\0'; }
C
/*______________mystring_ars.c_____________ * assignement 1 * hy255 * Tsolis Dimitris * email:[email protected] * * Contains a function implementation of the interface introduced by * mystring.h library. * This implementation is done with use of arrays * */ #include<assert.h> #include<stddef.h> /*******HELPING FUNCTIONS*********/ /*--------------Function last_index----------------- * Returns the index of NULL char <'\0'>. * * Arguments: * -string *a: The string that the character is in * * Returns: * -size_t i: The index of NULL char * */ size_t last_index(char *a){ size_t i; for(i=0U;a[i]!='\0';i++){ ; } return i; } /**************FUNCTION IMPLEMENTATION******************/ /*--------Function: ms_length--------- * Retunrs the length of the string passed sa an argument. * * Arguments: * -const char *:The string to find its length * Returns: * -size_t :The unsigned integer representing the length * * Assertions: * -Checks if the string argument is <NULL>.If true then exit * printing an error message else continue. * */ size_t ms_length(const char *cs){ size_t length=0U; assert(cs); while(cs[length]!='\0'){ length+=1; } return length; } /*---------Function: ms_copy---------- * Copies the second string argument to the first including the '\0' * character. * * Arguments: * -char *: The destination string.Must be large enough to fit the * source string. * * -const char*: The source string that will be copied * * Return: * -char *: The pointer to start of the copied string (destination string * "first arg") * * Assertions: * -Checks if the string (destination,source) are NULL. * If true exits the programm printing an error message. * * */ char *ms_copy(char *str,const char *cs){ size_t i; assert(str); assert(cs); if(str[0]=='\0' && cs[0]=='\0'){ return ""; } for(i=0U;i<ms_length(cs)+1U;i++){ str[i]=cs[i]; } return str; } /*---------Function: ms_ncopy---------- * Copies at most n chars from the second string argument to the first including the '\0' * character.If the destination argument is bigger then the remaining chars are replaced * by '\0'. * * Arguments: * -char *: The destination string.Must be large enough to fit the * source string. * * -const char*: The source string that will be copied * * -size_t : The number of chars to be copied. * * Return: * -char *: The pointer to start of the copied string (destination string * "first arg") * * Assertions: * -Checks if the string (destination,source) are NULL. * If true exits the programm printing an error message. * * */ char *ms_ncopy(char *str,const char *cs,size_t n){ size_t i; assert(str); assert(cs); if(str[0]=='\0' && cs[0]=='\0'){ return ""; } for(i=0U;i<n && cs[i]!='\0';i++){ str[i]=cs[i]; } str[i]='\0'; return str; } /*----------Function: ms_concat------------ * Concats the second argument string at the fo the first. * * Arguments: * -char *: The first arguments string at whose the end the first is concated. * * -const char* : The second argument string. * * Return: * -char *: The pointer to start of the first string argument. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ char *ms_concat(char *str,const char *cs){ size_t i=0U,j; assert(str); assert(cs); if(str[0]=='\0' && cs[0]=='\0'){ return ""; } i=last_index(str); for(j=0U;cs[j]!='\0';j++){ str[i++]=cs[j]; } str[i]='\0'; return str; } /*----------Function: ms_nconcat------------ * Concats the first n characters shown by the 3rd argument of the second string * argument at the end of the first. * * Arguments: * -char *: The first arguments string at whose the end the first is concated. * * -const char* : The second argument string. * * -size_t: The number of characters to be concated. * * Return: * -char *: The pointer to start of the first string argument. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ #include<stdio.h> char *ms_nconcat(char *str,const char *cs,size_t n){ size_t i=0U,j; assert(str); assert(cs); if(str[0]=='\0' && cs[0]=='\0'){ return ""; } i=last_index(str); for(j=0U;j<n && cs[j]!='\0';j++){ str[i++]=cs[j]; } str[i]='\0'; return str; } /*---------Function: ms_compare---------- * Compares lexicographically the 2 strigns passed as argumets to this function. * * Arguments: * -const char* : The first of the 2 strings to be compared. * * -const char* : The second string to be compared. * Return: * -An integer inticating the result of the comparison. * Return value <0 if the first str< second str, 0 if first str==second str, * and >0 if the first str> second str. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ int ms_compare(const char *csa,const char *csb){ size_t i; int res; assert(csa); assert(csb); if(csa[0]=='\0' && csb[0]=='\0'){ return 0; } for(i=0U;csa[i]!='\0' || csb[i]!='\0';i++){ res=csa[i]-csb[i]; if(res<0 || res>0){ return res; } } return res; } /*-----------Function: ms_ncompare--------------- * Compares lexicographically at most n chars(n is the 3rd argument) of the first string * with the 2nd string passed as argumets to this function. * * Arguments: * -const char* : The first of the 2 strings to be compared. * * -const char* : The second string to be compared. * * -size_t : The number of chars of the first string argument. * Return: * -An integer inticating the result of the comparison. * Return value <0 if the first str< second str, 0 if first str==second str, * and >0 if the first str> second str. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ int ms_ncompare(const char *csa,const char *csb,size_t n){ size_t i; int res; assert(csa); assert(csb); if(csa[0]=='\0' && csb[0]=='\0'){ return 0; } for(i=0U;(csa[i]!='\0' || csb[i]!='\0') && i<n;i++){ res=csa[i]-csb[i]; if(res<0 || res>0){ return res; } } return res; } /*-------------Function: ms_search-------------- * Searches and finds the first apereance of the second string argument in the first. * * Arguments: * -const char *: The string to look in. * * -const char *: The pattern to find in the first. * * Returns: * -A pointer to the first appearance of the pattern in the first * NULL if the pattern does not exist. * * * Assertions: * -Checks if the 2 string arguments are NULL. * If true exits the function printing an error message. * */ char *ms_search(const char *cs,const char *pat){ size_t i; char *a=(char *)cs; assert(cs); assert(pat); for(i=0U;i<ms_length(cs);i++){ if(ms_ncompare(a,pat,ms_length(pat))==0){ return a; } a++; } return NULL; }
C
/************************************************************************* > FileName: ipc-shm.c > Author : DingJing > Mail : [email protected] > Created Time: 2021年03月16日 星期二 15时59分36秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include<string.h> #include<errno.h> typedef struct _Teacher { char name[64]; int age; } Teacher; int main(int argc, char *argv[]) { int ret = 0; int shmid; //创建共享内存 ,相当于打开文件,文件不存在则创建 shmid = shmget(0x2234, sizeof(Teacher), IPC_CREAT | 0666); if (shmid == -1) { perror("shmget err"); return errno; } printf("shmid:%d \n", shmid); Teacher *p = NULL; //将共享内存段连接到进程地址空间 p = shmat(shmid, NULL, 0);//第二个参数shmaddr为NULL,核心自动选择一个地址 if (p == (void *) - 1) { perror("shmget err"); return errno; } strcpy(p->name, "aaaa"); p->age = 33; //将共享内存段与当前进程脱离 shmdt(p); printf("键入1 删除共享内存,其他不删除\n"); int num; scanf("%d", &num); if (num == 1) { //用于控制共享内存 ret = shmctl(shmid, IPC_RMID, NULL);//IPC_RMID为删除内存段 if (ret < 0) { perror("rmerrr\n"); } } return 0; }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "xyutils.h" #define TAG "[xyutils] " #define STRING_LEN 256 int check_ptr_invalid(void *ptr) { xylogd(); if (NULL == ptr) { return -1; } else { return 0; } } int print_util_usage(char *command, char *param1, char *usage) { xylogd(); //xylogd("command\t%s", command); //xylogd("param1\t%s", param1); if ( check_ptr_invalid(command) != 0 && check_ptr_invalid(param1) != 0 ) { return -1; } sprintf(usage, "\n[Usage]\n\t%s <%s>\n\n", command, param1); //xylogd("usage\t%s", usage); return 0; } int check_file_exist(char *path) { xylogd(); if (check_ptr_invalid(path) != 0) { return -1; } if (access(path, F_OK) != 0) { return -1; } return 0; } int check_has_substr(char *str, char *substr) { xylogd(); if(strstr(str, substr) == NULL) { return -1; } return 0; }
C
// $Date: 2018-05-22 06:24:02 +1000 (Tue, 22 May 2018) $ // $Revision: 1330 $ // $Author: Peter $ #include "Ass-03.h" // // This task can be used as the main pulse rate application as it takes // input from the front panel. // // *** MAKE UPDATES TO THE CODE AS REQUIRED *** // // Draw the boxes that make up the buttons and take action when the // buttons are pressed. See suggested updates for the touch panel task // that checks for button presses. Can do more in that task. #define XOFF 55 #define YOFF 80 #define XSIZE 250 #define YSIZE 150 #define GREEN 0x3722 #define RED 0xE0A2 #define BLUE 0x131C #define ORANGE 0xFCE0 #define WHITE 0xFFFF #define BLACK 0x0000 #define MAX_LEN 18 #define Second 1000 typedef struct button{ void (*handler)(void); uint16_t x, y ,width, hight; char * text; uint16_t fillColour; uint16_t altfillColour; uint16_t textColour; }; void button_show(struct button B){ osMutexWait(myMutex01Handle, osWaitForever); BSP_LCD_SetTextColor(B.fillColour); BSP_LCD_FillRect(B.x, B.y, B.width, B.hight); BSP_LCD_SetTextColor(B.textColour); BSP_LCD_SetBackColor(B.fillColour); BSP_LCD_DisplayStringAt(B.x+B.width/2, B.y+B.hight/2, B.text, CENTER_MODE); osMutexRelease(myMutex01Handle); } bool is_pressed(struct button B,Coordinate *point){ osMutexWait(myMutex01Handle, osWaitForever); if (point->x > B.x && point->x < B.x+B.width && point->y > B.y && point->y < B.y+B.hight){ BSP_LCD_SetTextColor(B.altfillColour); BSP_LCD_SetBackColor(B.altfillColour); BSP_LCD_FillRect(B.x, B.y, B.width, B.hight); BSP_LCD_SetTextColor(B.textColour); BSP_LCD_SetBackColor(B.altfillColour); BSP_LCD_DisplayStringAt(B.x+B.width/2, B.y+B.hight/2, B.text, CENTER_MODE); osMutexRelease(myMutex01Handle); B.handler(); osDelay(Second/4); osMutexWait(myMutex01Handle, osWaitForever); BSP_LCD_SetTextColor(B.fillColour); BSP_LCD_SetBackColor(B.fillColour); BSP_LCD_FillRect(B.x, B.y, B.width, B.hight); BSP_LCD_SetTextColor(B.textColour); BSP_LCD_SetBackColor(B.fillColour); BSP_LCD_DisplayStringAt(B.x+B.width/2, B.y+B.hight/2, B.text, CENTER_MODE); osMutexRelease(myMutex01Handle); return true; } else{ BSP_LCD_SetTextColor(B.fillColour); BSP_LCD_SetBackColor(B.fillColour); BSP_LCD_FillRect(B.x, B.y, B.width, B.hight); BSP_LCD_SetTextColor(B.textColour); BSP_LCD_SetBackColor(B.fillColour); BSP_LCD_DisplayStringAt(B.x+B.width/2, B.y+B.hight/2, B.text, CENTER_MODE); osMutexRelease(myMutex01Handle); return false; } } void Start(void){ safe_printf("Start button\n\r"); return; } void Stop(void){ safe_printf("Stop button\n\r"); return; } void Load(void){ safe_printf("Load button\n\r"); return; } void Store(void){ safe_printf("Store button\n\r"); return; } struct button buttons[]={ //{handler, X,Y,Width,Height,Lable,Fill, pressed fill, text colour} {Start, (1/6.0)*XOFF, YOFF ,XOFF*(2.0/3),40,"Start",GREEN,BLUE,BLACK}, {Stop, (1/6.0)*XOFF, YOFF+50 ,XOFF*(2.0/3),40,"Stop",RED,BLUE,BLACK}, //{Load,0*xgrid,1*ygrid,xgrid,ygrid,"Load",FILL_COLOUR,ALT_COLOUR,TEXT_COLOUR}, //{Store,0*xgrid,1*ygrid,xgrid,ygrid,"Store",FILL_COLOUR,ALT_COLOUR,TEXT_COLOUR}, //{NULL,0*xgrid,1*ygrid,xgrid,ygrid,"Mem 1",FILL_COLOUR,ALT_COLOUR,TEXT_COLOUR}, //{NULL,0*xgrid,1*ygrid,xgrid,ygrid,"Mem 2",FILL_COLOUR,ALT_COLOUR,TEXT_COLOUR}, //{NULL,0*xgrid,1*ygrid,xgrid,ygrid,"Mem 3",FILL_COLOUR,ALT_COLOUR,TEXT_COLOUR}, {NULL,NULL,NULL,NULL,NULL,NULL,NULL} }; void Ass_03_Task_02(void const * argument) { uint32_t loop=0; Coordinate display; osSignalWait(1,osWaitForever); safe_printf("Hello from Task 2 - Pulse Rate Application (touch screen input)\n\r"); for (int i=0;buttons[i].handler!=NULL;i++){ button_show(buttons[i]); } while (1) { if (getfp(&display) == 0) { for (int i=0;buttons[i].handler!=NULL;i++){ if (is_pressed(buttons[i],&display)) break; } if((display.y > YOFF+5) && (display.y < YOFF+YSIZE-5) && (display.x > XOFF+5) && (display.x < XOFF+XSIZE-5)) { osMutexWait(myMutex01Handle, osWaitForever); BSP_LCD_FillCircle(display.x, display.y, 2); osMutexRelease(myMutex01Handle); loop++; safe_printf("Task 2: %d (got %3d,%3d)\n\r", loop, display.x, display.y); } } } }
C
#include <stdio.h> #include <Windows.h> #include <string.h> #include <locale.h> BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lparam) { wchar_t** programs = (wchar_t**) lparam; static int index = 0; // 여러번 실행 시, static 변수의 값 유지에 의한 오류 방지 if(getArrayLength(programs) == 0) { index = 0; } if(hwnd != NULL) { if(IsWindowVisible(hwnd) == 1) { wchar_t* program = (wchar_t*)malloc(sizeof(wchar_t) * 1000); _wsetlocale(LC_ALL, L"korean"); GetWindowTextW(hwnd, (LPWSTR) program, 1000); if(wcslen(program) != 0) { programs[index++] = program; } } } return TRUE; } __declspec(dllexport) wchar_t** getVisiableProgram() { wchar_t** programs = (wchar_t**)malloc(sizeof(wchar_t*) * 20); for(int i=0; i<20; i++) { programs[i] = NULL; } EnumWindows((WNDENUMPROC) EnumWindowsProc, (LPARAM) programs); return programs; } __declspec(dllexport) int getArrayLength(wchar_t** arr) { int index = 0; while(arr[index] != NULL) { index++; } return index; } __declspec(dllexport) void freeArray(wchar_t** arr) { for(int i=0; i<getArrayLength(arr); i++) { free(arr[i]); } free(arr); }
C
#include <stdio.h> #include <stdlib.h> #include "matriz.h" struct matriz{ int nlinhas; int ncolunas; int** mat; }; Matriz* inicializaMatriz(int nlinhas, int ncolunas){ Matriz* matrix; int i, j; matrix = (Matriz*)malloc(sizeof(Matriz)); matrix->nlinhas = nlinhas; matrix->ncolunas = ncolunas; matrix->mat = (int**)malloc(nlinhas*sizeof(int*)); for(i=0; i<nlinhas; i++){ matrix->mat[i] = (int*)malloc(ncolunas*sizeof(int)); } return matrix; } void modificaElemento(Matriz* mat, int linha, int coluna, int elem){ mat->mat[linha][coluna] = elem; } void imprimeMatriz(Matriz* mat){ int i, j; for(i=0; i<mat->nlinhas; i++){ for(j=0; j<mat->ncolunas; j++){ printf("%d ", mat->mat[i][j]); } printf("\n"); } } int recuperaElemento(Matriz* mat, int linha, int coluna){ return mat->mat[linha][coluna]; } int recuperaNColunas (Matriz* mat){ return mat->ncolunas; } int recuperaNLinhas(Matriz* mat){ return mat->nlinhas; } Matriz* transposta (Matriz* mat){ int i, j; Matriz* trans; trans = inicializaMatriz(mat->ncolunas, mat->nlinhas); for(i=0; i<trans->nlinhas; i++){ for(j=0; j<trans->ncolunas; j++){ trans->mat[i][j] = mat->mat[j][i]; } } return trans; } Matriz* multiplicacao(Matriz* mat1, Matriz* mat2){ Matriz* produto; int i, j, op; produto = inicializaMatriz(mat1->nlinhas, mat2->ncolunas); for(i=0; i<produto->nlinhas; i++){ for(j=0; j<produto->ncolunas; j++){ produto->mat[i][j] = 0; } } for(i=0; i<produto->nlinhas; i++){ for(j=0; j<produto->ncolunas; j++){ for(op=0; op<mat1->ncolunas; op++){ produto->mat[i][j] += mat1->mat[i][op]*mat2->mat[op][j]; } } } return produto; } void destroiMatriz(Matriz* mat){ int i, j; for(i=0; i<mat->nlinhas; i++){ free(mat->mat[i]); } free(mat->mat); free(mat); }
C
#include "common.h" int replace (int ind) { int i, j; int distances[framesz]; //find distances of each frame and chose maximum distance to replace for (i=0; i<framesz; i++) { for (j=ind+1; j<n; j++) if (refstr[j]==pages[i]) { break; } distances[i]=j-ind; } int maxm=distances[0]; int repl=0; for (i=0; i<framesz; i++) { if (distances[i]>maxm) { maxm=distances[i]; repl=i; } } return repl; } void doOptimal() { int count=0, ptr=-1; int i, j; for (i=0; i<n; i++) { printf ("%d\n", refstr[i]); if (lookup(refstr[i])==1) { hit++; printf ("Page hit\n"); } else { miss++; printf ("Page miss\n"); //check if page table is full. //If not full we don't need to replace a page if (count<framesz) { count++;//frame added pages[++ptr]=refstr[i]; } else { //replace a page //find index in table of the page to replace ptr=replace (i); pages[ptr]=refstr[i]; } } showtable(); } } void main() { init(); doOptimal(); printf ("\nPage hits\t\t%d\nPage misses\t\t%d\n", hit, miss); } /* 3 20 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 */
C
// File: emi_files.c - emi program file functions #include <stdio.h> #include "emi.h" /* f_underline: underline string of characters */ void f_underline(const char *filename, char line, const int strlen) { FILE *file; file = fopen(filename, "a+"); for (int i = 0; i < strlen; i++) fprintf(file, "%c", line); fprintf(file, "\n"); fclose(file); } /* write_results_to_file: write results to file */ void write_results_to_file(const char *filename, int index_number, float continuous_score, float actual_end_of_sem, float end_of_sem) { FILE *file; file = fopen(filename, "a+"); fprintf(file, "| %7d | %6.2f | %6.2f | %6.2f | %6.2f | %6.2f |\n", index_number, continuous_score, actual_end_of_sem, compute_actual_total(continuous_score, actual_end_of_sem), end_of_sem, compute_total(continuous_score, end_of_sem) ); fclose(file); } /* write_filename: write filename to file */ void write_filename(const string filename) { FILE *file; file = fopen(filename, "a+"); fprintf(file, "File: %s\n\n\n", filename); fclose(file); } /* write_heading_to_file: write heading to file */ void write_heading_to_file(const char *filename, int len) { FILE *file; f_underline(filename, '-', len); file = fopen(filename, "a+"); fprintf(file, "| %s | %s | %s | %s | %s | %s |\n", "INDEX NUMBER", "CONTINUOUS", "ACTUAL END OF SEM", "ACTUAL TOTAL", "END OF SEM", "TOTAL" ); fprintf(file, "| %s | %s | %s | %s | %s | %s |\n", " ", "SCORE(30%)", "SCORE(70%)", "SCORE(100%)", "SCORE(50% + 20%)", "SCORE(100%)" ); fclose(file); f_underline(filename, '-', len); } /* write_end_to_file: close data table */ void write_end_to_file(const char *filename, int len) { f_underline(filename, '-', len); }
C
#include <stdlib.h> #include <stdio.h> #include "definicions.h" void num_malformado(int tipo_num, char* lexema, int linha){ switch(tipo_num){ case INT_MAL: printf("------------------------------------------------------------------------------------------------------------\n-->O enteiro %s da liña %d está mal formado. Contén caracter non aceptado.<--\n------------------------------------------------------------------------------------------------------------\n", lexema, linha); return; break; case FLOAT_MAL: printf("------------------------------------------------------------------------------------------------------------\n-->O flotante %s da liña %d está mal formado. Contén caracter non aceptado.<--\n------------------------------------------------------------------------------------------------------------\n", lexema, linha); return; break; case BIN_MAL: printf("------------------------------------------------------------------------------------------------------------\n-->O número binario %s da liña %d está mal formado. Contén caracter non aceptado.<--\n------------------------------------------------------------------------------------------------------------\n", lexema, linha); return; break; } }
C
// ---------------------------------------------------------------------------------------- // Implementation of Example target.3c (Section 52.3, page 196) from Openmp 4.0.2 Examples // on the document http://openmp.org/mp-documents/openmp-examples-4.0.2.pdf // // // // // ---------------------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> void init(float* a, float* b, int n) { int i; for(i=0;i<n;i++) { a[i] = i/2.0; b[i] = ((n-1)-i)/3.0; } return; } void output(float* a, int n) { int i; for(i=0;i<n;i++) printf("%f ", a[i]); printf("\n"); return; } void vec_mult(int n) { int i; float p[n], v1[n], v2[n]; init(v1, v2, n); #pragma omp target map(to: v1[:n], v2[:n]) map(from: p[:n]) device(0) #pragma omp parallel for for (i=0; i<n; i++) p[i] = v1[i] * v2[i]; output(p, n); } int main(int argc, char * argv[]) { vec_mult(1000); return 0; }
C
/* Write a program which returns addition of all element from singly linear linked list. Function Prototype :int Addition( PNODE Head); Input linked list : |10|->|20|->|30|->|40| Output : 100 */ #include "Header.h" int main() { PNODE First = NULL; int iRet = 0; InsertFirst(&First, 40); InsertFirst(&First, 30); InsertFirst(&First, 20); InsertFirst(&First, 10); iRet = Addition(First); printf("Addition of Linked List elements is : %d", iRet); return 0; }
C
#include "socketCrawler.h" #define TRUE 1 #define FALSE 0 #define LENBUFFER 512 #define LEN_VETOR 1024 //definir a estrutura do socket servidor struct addrinfo criarServidor(struct addrinfo hints, struct addrinfo **res, char *endereco){ memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if(getaddrinfo(endereco, "80", &hints, res)!=0){ perror("getaddrinfo"); } return **res; } //Criar o socket //socket(dominio, tipo de socket, protocolo) //AF_INET = ipv4, SOCK_STREAM = TCP, protocolo 0 é o padrão int criarSocket(int *sock_desc, struct addrinfo *res){ *sock_desc = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(*sock_desc == -1){ printf("Nao foi possivel criar o socket!"); return *sock_desc; } return *sock_desc; } void conversarServidor(int sock_desc, struct addrinfo *res, char *endereco, char *subEndereco, char *caminho_arquivo){ char msg[512]; //msg = mensagem que será enviada ao servidor char resp_servidor[LENBUFFER]; //variável que irá receber a resposta do servidor int bytes_read; //variável de suporte para capturar a resposta do servidor FILE *fp = fopen(caminho_arquivo, "w"); if(fp == NULL){return;} //Enviar dados ao servidor //msg = "GET /index.html HTTP/1.1\r\nHost: www.site.com\r\n\r\n"; comando HTTP para pegar a pagina principal de um website.html //index.html fica subentendido quando não se coloca nada após o primeiro / //Host: precisa ser especificado pois vários endereços podem utilizar o mesmo servidor ip //Connection: close simplesmente fecha a conexão após a resposta do servidor ser enviada if(subEndereco == NULL){ strcpy(msg, "GET / HTTP/1.1\nHost: "); }else{ strcpy(msg, "GET "); strcat(msg, subEndereco); strcat(msg, " HTTP/1.1\nHost: "); } strcat(msg, endereco); strcat(msg, "\r\nConnection: close\n\n"); printf("%s\n",msg); if(send(sock_desc, msg, strlen(msg), 0) < 0){ printf("Nao foi possivel enviar os dados!"); } else{ printf("Os dados foram enviados com sucesso!\n"); } //Receber resposta do servidor //recv(descritor do socket, variável onde será armazenada a resposta do servidor, tamanho da variável, flags, padrão 0) //do while usado para que enquanto a resposta do servidor não for completamente capturada, continuar pegando o que falta do{ bytes_read = recv(sock_desc, resp_servidor, LENBUFFER, 0); if(bytes_read == -1){ perror("recv"); } else{ fprintf(fp, "%.*s", bytes_read, resp_servidor); } } while(bytes_read > 0); fclose(fp); //Checa se houve um erro de HTTPS, caso sim, tenta realizar uma conexão https agora FILE *arquivo = fopen(caminho_arquivo,"r"); int c, i = 0; while(i<10){ c = fgetc(arquivo); i++; } fclose(arquivo); if(c == '3' || c == '4'){ int sockSSL_desc; //descritor do socket int *psock = &sockSSL_desc; criarServSockSSL(psock, endereco); conectarServidorSSL(psock, endereco, subEndereco, caminho_arquivo); } } //Conectar a um servidor remoto e conversar com ele void conectarServidor(int sock_desc, struct addrinfo *res, char *endereco, char *subEndereco, char *caminho_arquivo){ //connect(descritor do socket, struct do servidor, tamanho do servidor if(connect(sock_desc , res->ai_addr , res->ai_addrlen) < 0){ printf("Nao foi possivel estabelecer a conexao!"); perror("connect"); } else{ printf("Conexao estabelecida com sucesso!\n"); } freeaddrinfo(res); conversarServidor(sock_desc, res, endereco, subEndereco, caminho_arquivo); } //definir a estrutura do socket servidor SSL int criarServSockSSL(int *sock_desc, char *endereco){ //É necessário concatenar o endereco recebido com https:// para que se possa capturar o endereco //https de forma correta char end[LENBUFFER] = "https://"; strcat(end, endereco); char protocolo[10] = ""; char nomeHost[LENBUFFER] = ""; //O port padrão para conexões https é 443, ao contrário do port 80 para conexões http char numPort[10] = "443"; int port; char *pointer = NULL; struct hostent *host; struct sockaddr_in dest_addr; //As instruções abaixo estão sendo realizadas para modificar a string do endereco de forma que ele //seja usado de forma correta pelas funções que criarão o socket //remove o / no final do link caso exista if(end[LENBUFFER-1] == '/'){ end[LENBUFFER-1] = '\0'; } //O primeiro : termina a string do protocolo strncpy(protocolo, end, (strchr(end, ':')-end)); //O hostname começa após o :// strncpy(nomeHost, strstr(end, "://")+3, sizeof(nomeHost)); //Se o host possui um :, capturar o port if(strchr(nomeHost, ':')){ pointer = strchr(nomeHost, ':'); //O ultimo : começa o port strncpy(numPort, pointer+1, sizeof(numPort)); *pointer = '\0'; } port = atoi(numPort); if((host = gethostbyname(nomeHost)) == NULL){ printf("Não foi possivel capturar o host %s.\n", nomeHost); } *sock_desc = socket(AF_INET, SOCK_STREAM, 0); if(*sock_desc == -1){ printf("Nao foi possivel criar o socket!"); return *sock_desc; } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); dest_addr.sin_addr.s_addr = *(long*)(host->h_addr); memset(&(dest_addr.sin_zero), '\0', 8); pointer = inet_ntoa(dest_addr.sin_addr); if(connect(*sock_desc, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) == -1){ printf("Erro, nao foi possivel conectar-se ao host"); } return *sock_desc; } void conectarServidorSSL(int *sock_desc,char *endereco, char *subEndereco, char *caminho_arquivo){ BIO *bioSaida = NULL; BIO *web; const SSL_METHOD *method; SSL_CTX *ctx; SSL *ssl; int servidor = 0; //As funções abaixo inicializam as funcionalidades necessárias da biblioteca openssl OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); //Cria as BIOs de input e output bioSaida = BIO_new_fp(stdout, BIO_NOCLOSE); //Inicializa a biblioteca SSL if(SSL_library_init() < 0){ BIO_printf(bioSaida, "Não foi possível iniciar a biblioteca OpenSSL!\n"); } //Abaixo estão sendo implementados os passos para a criação objeto context, o SSL_CTX //Este objeto é usado para criar um novo objeto de conexão para cada conexão SSL, objetos //de conexão são usados para realizar handshakes, escritas e leituras //Faz com que o handshake tente utilizar o protocolo SSLv2, mas também coloca como opções //o SSLv3 e TLSv1 method = SSLv23_client_method(); //Cria o objeto context if((ctx = SSL_CTX_new(method)) == NULL){ BIO_printf(bioSaida, "Não foi possivel criar um objeto SSL!\n"); } //Caso o protocolo SSLv2 não funcione, tenta negociar com SSLv3 e o TSLv1 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); //Cria o objeto de estado SSL ssl = SSL_new(ctx); web = BIO_new_ssl_connect(ctx); BIO_get_ssl(web, &ssl); //Cria a conexão TCP servidor = criarServSockSSL(sock_desc, endereco); if(servidor == 0){ BIO_printf(bioSaida, "Não foi possível criar a conexão TCP"); } //Conecta a sessão SSL com o descritor do socket SSL_set_fd(ssl, servidor); //Realiza a conexão SSL if(SSL_connect(ssl)!=1){ BIO_printf(bioSaida, "Não foi possivel reazilar a conexão SSL"); } //Realizar a requisição HTTP para baixar as informações do site char msg[LENBUFFER]; //msg = mensagem que será enviada ao servidor char resp_servidor[LENBUFFER]; //variável que irá receber a resposta do servidor int bytes_read; //variável de suporte para capturar a resposta do servidor //Enviar dados ao servidor //msg = "GET /index.html HTTP/1.1\r\nHost: www.site.com\r\n\r\n"; comando HTTP para pegar a pagina principal de um website //index.html fica subentendido quando não se coloca nada após o primeiro / //Host: precisa ser especificado pois vários endereços podem utilizar o mesmo servidor ip //Connection: close simplesmente fecha a conexão após a resposta do servidor ser enviada //char *subEndereco = NULL; if(subEndereco == NULL){ strcpy(msg, "GET / HTTP/1.1\nHost: "); }else{ strcpy(msg, "GET "); strcat(msg, subEndereco); strcat(msg, " HTTP/1.1\nHost: "); } strcat(msg, endereco); strcat(msg, "\r\nConnection: close\r\n\r\n"); printf("%s\n",msg); BIO_puts(web, msg); BIO_puts(bioSaida, "\n"); //a saida agora será direcionada para um arquivo chamado site.html bioSaida = BIO_new_file(caminho_arquivo, "w"); //Receber resposta do servidor e escrever no arquivo usando as funções BIO_read que lê a resposta e //a funcão BIO_write que escreve a resposta. int tam = 0; do{ tam = BIO_read(web, resp_servidor, sizeof(resp_servidor)); if(tam>0){ BIO_write(bioSaida, resp_servidor, tam); } }while(tam>0 || BIO_should_retry(web)); if(bioSaida!=NULL){ BIO_free(bioSaida); } //Liberar as estruturas que não serão mais usadas SSL_free(ssl); close(servidor); SSL_CTX_free(ctx); } int salvar_link_visitado(char *link, char *dominio){ char *file_name = "linksVisitados.txt", *path = get_path(dominio, file_name); FILE *arquivo = fopen(path,"a"); int status = TRUE; printf("============================================\n"); if(arquivo == NULL){ printf("ERRO AO ADICIONAR LINK NO ARQUIVO!!!\n"); status = FALSE; }else{ fprintf(arquivo,"%s\n", link); fclose(arquivo); printf("%sLINK: %s VISITADO!!!%s\n", BLUE, link, RESET); } printf("============================================\n"); return status; } ListaLinks* listar_links_visitados(char *dominio){ ListaLinks *lista = startLista(); char *buffer_link = malloc(LENBUFFER*sizeof(char)); char *file_name = "linksVisitados.txt", *path = get_path(dominio, file_name); int fim; FILE *arquivo = fopen(path,"r"); if(arquivo != NULL){ printf("%s\n================ LINKS VISITADOS =================%s\n", YELLOW, GREEN); int i = 1; while(fgets(buffer_link, LENBUFFER, arquivo) != NULL){ finalizar_string(buffer_link); printf("%d => %s \n", i, buffer_link); addLista(lista, buffer_link); buffer_link = malloc(LENBUFFER*sizeof(char)); i++; } No *temp = lista->primeiro; while(temp!=NULL){ printf("%s\n", temp->link); temp = temp->proximo; } printf("%s==================================================%s\n", YELLOW, RESET); fclose(arquivo); } return lista; } // Checa se um link já foi visitado. int link_visitado(char *link, char *dominio){ int boolean = FALSE; ListaLinks *lista = listar_links_visitados(dominio); char *link_lista = pop(lista); while (link_lista != NULL && boolean != TRUE){ if(strcmp(link, link_lista) == 0){ boolean = TRUE; } link_lista = pop(lista); } free_lista(lista); return boolean; } // Função para ser utilizado com threads. Faz download de uma pagina. // O parametro passado é do tipo struct devido ser necessário mais de um // argumento para a função. // funções que são usadas com threads só tem um argumento do tipo void, que pode // ser convertido internamento no tipo necessário a funcao, no caso uma struct. void *baixar_pagina(void *args){ Arg_download *arg = (Arg_download*)args; int sock_desc; //descritor do socket int *psock = &sock_desc; struct addrinfo hints, *res; struct addrinfo **pres = &res; char *caminho_arquivo = get_path(arg->endereco, arg->nome_arquivo_saida); criarServidor(hints, pres, arg->endereco); criarSocket(psock, res); conectarServidor(sock_desc, res, arg->endereco, arg->subEndereco, caminho_arquivo); close(sock_desc); ListaLinks *lista = filtrar_lista(buscarLinks(caminho_arquivo), arg->endereco); ListaLinks *lista_link_arquivo = buscar_links_de_arquivo(lista, arg->endereco, arg->extensao_arquivo); printf("%s--------------------- LINKS COM EXTENSÃO %s ------------------------\n",BLUE, arg->extensao_arquivo ); printf("----------------------- ENCOTRADOS %d ---------------------------\n",lista_link_arquivo->quantLinks); exibir_links_lista(lista_link_arquivo); printf("--------------------------------------------------------------------\n"); printf("%s++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n", PINK); if(arg->subEndereco == NULL){ printf("ARVORE DO LINKS (PAGINA PRINCIPAL) :%s %s %s\n", RED, arg->endereco, PINK); } else{ printf("ARVORE DO LINKS :%s %s %s\n" , RED, arg->subEndereco, PINK); } print_lista(lista); exibir_links_lista(lista); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n%s", RESET); salvar_links_econtrados(lista, arg->endereco); } // Percorre os links encontrados e salvos no arquivo. void percorrer_links(char* dominio, char* tipo_arquivo){ char buffer_link[LENBUFFER]; char nome_arquivo_saida[LENBUFFER], temp[LENBUFFER]; char *arq_links = "linksEncontrados.txt", *path = get_path(dominio, arq_links); int contador = 1; FILE *arquivoLinks = fopen(path,"r"); if(arquivoLinks != NULL){ while(fgets(buffer_link, LENBUFFER, arquivoLinks) != NULL){ if(link_visitado(buffer_link, dominio) == FALSE){ buffer_link[strlen(buffer_link)-1] = '\0'; snprintf(temp, 10, "%d", contador);//converte int em string strcpy(nome_arquivo_saida, "link "); strcat(nome_arquivo_saida, temp); strcat(nome_arquivo_saida, ".html"); Arg_download *args = start_arg(dominio, buffer_link, nome_arquivo_saida, tipo_arquivo); pthread_t thread; // Para cada link não visitado é criado um thred para baixa a respectiva página pthread_create(&thread,NULL,baixar_pagina,(void*)args); // Join cria sequencia e garante a executação de todos os threads. pthread_join(thread,NULL); contador++; salvar_link_visitado(buffer_link, dominio); } } fclose(arquivoLinks); } } // Cria a struct com parametros necessários para baixar uma página. Arg_download* start_arg(char *endereco, char *subEndereco, char* nome_arquivo_saida, char *ext_arq){ Arg_download *arg = malloc(sizeof(Arg_download)); arg->endereco = endereco; arg->subEndereco = subEndereco; arg->nome_arquivo_saida = nome_arquivo_saida; arg->extensao_arquivo = ext_arq; return arg; } int criar_pasta_dominio(char *dominio){ int result = mkdir(dominio, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); int boolean = FALSE; // Caso a pasta seja criada o retorno será 0(zero). if(!result){ printf("%s============================================\n",GREEN); printf("DIRETORIO %s CRIADO COM SUCESSO!!!\n",dominio); boolean = TRUE; }else{ printf("%s============================================\n",RED); printf("FALHA AO CRIAR DIRETORIO!!!\n"); } printf("============================================%s\n", RESET); return boolean; } // Baixa a pagina inicial do dominio. void *percorrer_dominio(void *args){ Arg_percorrer_dominio *arg = (Arg_percorrer_dominio*)args; char *end = arg->dominio; //endereço do site a ser visitado char *nome_arquivo_saida = "site.html"; char *tipo_arq = arg->tipo_arquivo; char *path = get_path(end, nome_arquivo_saida); criar_pasta_dominio(end); // Cria os argumentos necessário a função thread que baixa a página Arg_download *arg_site = start_arg(end, NULL, nome_arquivo_saida, arg->tipo_arquivo); pthread_t thread; // Criação do thread com a função requeira, e dando o cast para void pois só se pode // parra uma variavel como argumento. void* pode ser convetido internamente na funcao. pthread_create(&thread, NULL, baixar_pagina, (void*)arg_site); // Join garante que o thread será executado e cria uma sequencia de execução dos threads. pthread_join(thread, NULL); percorrer_links(end,arg->tipo_arquivo); } // cria a struct com paramentros necessários para percorrer um dominio. Arg_percorrer_dominio* start_arg_dominio(char *dominio, char *tipo_arquivo){ Arg_percorrer_dominio *arg = malloc(sizeof(Arg_percorrer_dominio)); arg->dominio = dominio; arg->tipo_arquivo = tipo_arquivo; return arg; } Arg_statistica* start_arg_statistica(char *dominio, char *tipo_arquivo){ Arg_statistica* arg = malloc(sizeof(Arg_statistica)); arg->dominio = dominio; arg->tipo_arquivo = tipo_arquivo; return arg; }
C
// Graph接口 #pragma once #include "config.h" #include "window.h" #include "point.h" #include "common.h" static int __static_graph_id = 0; //全局变量:待分配的Graph ID序号 struct graph_description { //图形通用描述信息 int id; // 图元ID序号 char name[__GRAPH_DESCRIPTION_NAME_MAX__]; //图元名称 struct point center; //图元中心 }; //图形图元接口(抽象类) struct graph { __DATA__ int object_id; //图元代号 __DATA__ struct graph * parent; __DATA__ struct graph ** child; __DATA__ int child_count; __DATA__ int child_max; __DATA__ struct graph_description info; //构造函数 __FUNCTION__ void (*init)(struct graph *cthis); //析构函数 __FUNCTION__ void (*exit)(struct graph *cthis); //添加子元:返回值:图元序号 __FUNCTION__ int (*insert)(struct graph *cthis,struct graph *item); //删除子元 __FUNCTION__ int (*del)(struct graph *cthis,int item_id); //返回子元序列 __FUNCTION__ struct graph** (*get_child)(struct graph *cthis); //返回父元 __FUNCTION__ struct graph* (*get_parent)(struct graph *cthis); //返回子代数量 __FUNCTION__ int (*get_child_count)(struct graph *cthis); //虚函数: //绘制图形 __FUNCTION__ __VIRTUAL__ int (*draw)(struct graph *cthis,struct window * draw_object); //判断是否相交 __FUNCTION__ __VIRTUAL__ int (*is_cross)(struct graph *cthis,struct point point); //平移 __FUNCTION__ __VIRTUAL__ int (*move)(struct graph *cthis,struct point base,struct point vector); //旋转 __FUNCTION__ __VIRTUAL__ int (*rot)(struct graph *cthis,struct point base,float angle); //缩放 __FUNCTION__ __VIRTUAL__ int (*resize)(struct graph *cthis,struct point base,float rate); //获得图形中心 __FUNCTION__ __VIRTUAL__ struct point (*get_center)(struct graph *cthis); //复制自身 __FUNCTION__ __VIRTUAL__ struct graph *(*deepcopy)(struct graph *cthis); //在画板上画出图元标志 __FUNCTION__ __VIRTUAL__ int (*draw_tag)(struct graph *cthis,struct window * draw_object); //返回图元信息 __FUNCTION__ __VIRTUAL__ int (*get_tag)(struct graph *cthis, struct graph_description *out_info, char *out_info_str); }; //---------------------------------------------------------------------------------------- void graph_init(struct graph *cthis); void graph_exit(struct graph *cthis); int graph_insert(struct graph *cthis,struct graph *item); int graph_del(struct graph *cthis,int item_id); struct graph * graph_get_parent(struct graph *cthis); struct graph ** graph_get_child(struct graph *cthis); int graph_get_child_count(struct graph *cthis); //---------------------------------------------------------------------------------------- //虚函数 int graph_draw(struct graph * cthis,struct window * draw_object); int graph_is_cross(struct graph *cthis,struct point point); int graph_move(struct graph *cthis,struct point base,struct point vector); int graph_rot(struct graph *cthis,struct point base,float angle); int graph_resize(struct graph *cthis,struct point base,float rate); struct point graph_get_center(struct graph *cthis); struct graph *graph_deepcopy(struct graph *cthis); int graph_draw_tag(struct graph *cthis,struct window * draw_object); int graph_get_tag(struct graph *cthis, struct graph_description *out_info, char *out_info_str);
C
/* * <Melarpise5.c Adelson-Velskii and Landis Tree Implementation> * Copyright (C) <2014> <Ferriel Lisandro B. Melarpis> * NOTE: * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // libraries #include<stdio.h> #include<stdlib.h> // precompiler definitions #define LEFT 10 #define RIGHT 20 #define max(a,b) a>b?a:b // bst structure typedef struct node{ int value; int height; struct node *left; struct node *right; struct node *parent; }BST; // function prototjpes int menu(); void createNode(BST **, int); void insertNode(BST **, BST *); void deleteNode(BST **, int); void removeNode(BST **); BST *search(BST *, int ); BST *successor(BST *); BST *findMin(BST *); void printBST(BST *root,int); void EXIT(BST **); void updateHeight(BST *); void balanceTree(BST **, BST **); void rrotate(BST **, BST **); void lrotate(BST **, BST **); // main int main(void){ BST *root=NULL; int i; int choice; while((choice=menu())!=2){ printf("Value: "); scanf("%i",&i); switch(choice){ case 1: createNode(&root, i); break; default: fprintf(stderr, "Invalid Choice!\n"); break; } } EXIT(&root); // deallocate all pointers then eiit if(root==NULL){ printf("Exited Successfully.\n"); exit(EXIT_SUCCESS); }else{ exit(EXIT_FAILURE); } } // function for deleting the BST void EXIT(BST **root){ while(*root!=NULL){ removeNode(root); } } // menu function int menu(){ int choice; printf("\n MENU "); printf("\n[1] - Insert"); printf("\n[2] - Exit"); printf("\nYour choice: "); scanf("%i",&choice); return choice; } void createNode(BST **root, int i){ //creates new node with value i BST *temp = malloc(sizeof(BST)); temp->parent=temp->left=temp->right=NULL; temp->value=i; //calls insertNode to add the new node to the BST if(*root==NULL) printf("Tree is Empty.\n"); else{ printf("Previous Tree:\n"); printBST(*root, 1); printf("\n=================================================\n"); } insertNode(root, temp); printf("Tree after insertion:\n"); printBST(*root, 1); printf("\n=================================================\n"); } void insertNode(BST **root, BST *temp){ //inserts node pointed bj temp to the BST if(*root==NULL){ *root=temp; }else{ //recursive insert /*temp->parent=*root; if(temp->value>(*root)->value) insertNode(&(*root)->right, temp); else insertNode(&(*root)->left, temp);*/ BST *t=*root; while(t!=NULL){ if(temp->value<=t->value){ if(t->left==NULL){ temp->parent=t; t->left=temp; break; } t=t->left; }else{ if(t->right==NULL){ temp->parent=t; t->right=temp; break; } t=t->right; } } } updateHeight(temp); //for debugging purposes printf("Height of %d is now %d which is %d - %d\n", temp->value, temp->height, getHeight(temp->right), getHeight(temp->left)); balanceTree(root, &temp); } // function for getting the height of the node int getHeight(BST *t){ if(t==NULL) return -1; return 1+(max(getHeight(t->left),getHeight(t->right))); } // function for updating the height of each node void updateHeight(BST *t){ BST *p=t; while(p->parent!=NULL){ p->height=getHeight(p); // if(p->parent==NULL) break; p=p->parent; } } // function for balancing the tree void balanceTree(BST **root, BST **temp){ BST *flag; int i,j; flag = *temp; while(flag->parent!=NULL){ /*if(flag->parent == NULL) break;*/ flag = flag->parent; if(flag->left == NULL) i = -1; else i = flag->left->height; if(flag->right == NULL) j = -1; else j = flag->right->height; if(i-j>=2||i-j<=-2){ if(i>j){ if(flag->left->right==NULL){ rrotate(root,&flag); }else if(flag->left->left==NULL){ lrotate(root,&flag->left); rrotate(root,&flag); }else if(flag->left->left->height>=flag->left->right->height){ rrotate(root,&flag); }else{ lrotate(root,&flag->left); rrotate(root,&flag); } }else{ if(flag->right->left==NULL){ lrotate(root,&flag); }else if(flag->right->right==NULL){ rrotate(root,&flag->right); lrotate(root,&flag); }else if(flag->right->left->height>=flag->right->right->height){ rrotate(root,&flag->right); lrotate(root,&flag); }else{ lrotate(root,&flag); } } updateHeight(flag); } } } // function for left rotation void lrotate(BST **treeRoot, BST **temp){ BST *root = *temp; BST *pivot = root->right; BST *s = root; if(root->parent != NULL){ pivot->parent = root->parent; if(root->parent->value >= root->value){ root->parent->left = pivot; } else{ root->parent->right = pivot; } } else pivot->parent = NULL; root->parent = pivot; if(pivot->left != NULL){ root->right = pivot->left; pivot->left->parent = root; } else root->right = NULL; pivot->left = root; for(;s->parent!=NULL;s=s->parent);//update the root of the tree to point on the new root *treeRoot = s; } // function for right rotation void rrotate(BST **treeRoot, BST **temp){ BST *root = *temp; BST *pivot = root->left; BST *s = root; if(root->parent != NULL){ pivot->parent = root->parent; if(root->parent->value >= root->value){ root->parent->left = pivot; } else root->parent->right = pivot; } else pivot->parent = NULL; root->parent = pivot; if(pivot->right != NULL){ root->left = pivot->right; pivot->right->parent = root; } else root->left = NULL; pivot->right = root; for(;s->parent!=NULL;s=s->parent);//update the root of the tree to point on the new root *treeRoot = s; } // function for flaging what child is the node int isLeft(BST *temp){ if(temp->parent->left==temp) return LEFT; else return RIGHT; } // function for flaging what child the node has int hasOne(BST *temp){ if(temp->left!=NULL&&temp->right==NULL) return LEFT; else if(temp->left==NULL&&temp->right!=NULL) return RIGHT; else return 0; } // function for removing the node from the tree void removeNode(BST **root){ BST *tmp=*root; if(tmp->left!=NULL&&tmp->right!=NULL){ BST *s=successor(tmp); tmp->value=s->value; removeNode(&s); }else{ if(tmp->left==NULL&&tmp->right==NULL){ if(tmp->parent!=NULL){ if(isLeft(tmp)==LEFT){ tmp->parent->left=NULL; }else{ tmp->parent->right=NULL; } free(tmp); }else{ *root=NULL; free(*root); } }else{ if(hasOne(tmp)==LEFT){ if(tmp->parent==NULL){ tmp->left->parent=NULL; *root=tmp->left; }else if(isLeft(tmp)==LEFT){ tmp->parent->left=tmp->left; tmp->left->parent=tmp->parent; }else{ tmp->parent->right=tmp->left; tmp->left->parent=tmp->parent; } free(tmp); }else{ if(tmp->parent==NULL){ tmp->right->parent=NULL; *root=tmp->right; }else if(isLeft(tmp)==LEFT){ tmp->parent->left=tmp->right; tmp->right->parent=tmp->parent; }else{ tmp->parent->right=tmp->right; tmp->right->parent=tmp->parent; } free(tmp); } } } } // function for deleting nodes void deleteNode(BST **root, int i){ if(*root==NULL){ printf("Tree is Emptj.\n"); return; } BST *tmp=search(*root, i); if(tmp==NULL){ printf("Node not found.\n"); return; }else{ printf("Previous Tree:\n"); printBST(*root, 1); printf("\n=================================================\n"); if(tmp==*root){ removeNode(root); }else{ removeNode(&tmp); } printf("Tree after deletion:\n"); *root==NULL? printf("Tree is now emptj.\n") : printBST(*root, 1); printf("\n=================================================\n"); } } BST *search(BST *root, int i){ //returns a pointer to the node with value i if(root==NULL){ printf("Tree is emptj.\n"); return NULL; }else{ if(root->value==i){ return root; }else if(root->value>i){ return search(root->left, i); }else if(root->value<i){ return search(root->right, i); }else{ printf("Node not found.\n"); return NULL; } } } BST *successor(BST *root){ //returns a pointer to the successor of node rooted at pointer root if(root==NULL&&root->right==NULL){ printf("No successor.\n"); return root; }else{ return findMin(root->right); } } BST *findMin(BST *root){ //returns a pointer to the node with the minimum value if(root==NULL||root->left==NULL) return root; else return findMin(root->left); } // function for printing the BST void printBST(BST *root,int tabs){ int i; if(root!=NULL){ printBST(root->right,tabs+1); for(i=0;i<tabs;i++) printf("\t"); printf("%3i\n",root->value); printBST(root->left,tabs+1); } }
C
// T.U.Senasinghe - IT21073878 - 2021 Batch - group 05.1.A #include<stdio.h> int main(void) { //ariables char trancTyp; double bal; double amt; double newbal; printf("Enter Transaction type (W - withdrawls , D - Deposit) : "); trancTyp = getchar(); //Transcaction type if (trancTyp == 'W' || trancTyp == 'w') { printf("You have selected to withdraw money \n"); printf("====================================\n"); printf("Enter the bank balance : "); scanf("%lf", &bal); // bank balance printf("Enter withhdraw ammount : "); scanf("%lf", &amt); //withhdraw ammount newbal = bal - amt ; printf("New Bank balance : %.2f", newbal); //New Bank balance } else if (trancTyp == 'D'|| trancTyp == 'd') { printf("You have selected to deposit money\n"); printf("==================================\n"); printf("Enter the bank balance : "); scanf("%lf", &bal);// bank balance printf("Enter deposit ammount : "); scanf("%lf", &amt); //deposit ammount newbal = bal + amt ; printf("New Bank balance : %.2f", newbal); //New Bank balance } else { printf("You have selected an invalid transaction type"); } return 0; }
C
/* ü Ʈ ĭ (ε ) 밢 ĭ ̵ ϹǷ 8 Ѱ ̵ մϴ. Ʈ ġ ־ ̵ ϼ. */ #include <stdio.h> #include <stdlib.h> void SetINFO(char*); int solution(char pos[]) { char pos_x = pos[0]; char pos_y = pos[1]; int i, count = 0; // Ʈ ̵ϴ ǥ int arr[][2] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; // ó for(i=0; i<8; ++i) { // ̵ϴ ǥ x, y ϱ pos_x += arr[i][0]; pos_y += arr[i][1]; //  count if(!(pos_x<'A' || pos_x>'H' || pos_y<'1' || pos_y>'8')) count++; // ʱȭ pos_x = pos[0]; pos_y = pos[1]; } // ̵Ÿ return return count; } void main(void) { char str[2]; SetINFO(str); printf("Result Solution: %d\n", solution(str)); } void SetINFO(char *str) { scanf("%s", str); // ü ǥ ó if(str[0]<'A' || str[0]>'H' || str[1]<'1' || str[1]>'8') exit(1); }
C
#include <stdio.h> int main() { int * p; int arr[] = { 2, 7, 9, 3}; printf("Address of array and address of pointer are two totally different things\n"); printf("Address of array is the address of its first component\n"); printf("Address of pointer is the address of the memory location where the pointer is stored\n"); printf("Address of array\n"); printf("%d\n", arr);/* address of array: equivalent ways */ printf("%d\n", &arr);/* address of array: equivalent ways */ printf("%d\n", &(arr[0]));/* address of array: equivalent ways */ printf("Address of pointer - before\n"); printf("%d\n", &p); /* address of pointer: the pointer is located in a memory position */ printf("%d\n", p); /* random */ printf("Address of pointer - after\n"); p = arr; printf("%d\n", &p); /* address of pointer doesn't change */ printf("%d\n", p); /* From now on, you can access the array - both by using the array itself - and by using the pointer */ /* How to access the array */ printf("How to access the array with the array\n"); printf("%d\n", arr[2]); /* through subscript operator */ printf("%d\n", *(arr + 2) ); /* through pointer arithmetic */ printf("%d\n", *((&arr[0]) + 2) ); printf("%d\n", *((&arr) + 2) ); /* This one doesn't do what you may expect... It doesn't seem to follow pointer arithmetic but standard arithmetic... */ printf("%d\n", (&arr) + 2 ); /* Seems like you cannot dereference it... */ printf("How to access the array with the pointer\n"); printf("%d\n", p[2]); /* through subscript operator */ printf("%d\n", *(p + 2) ); /* through pointer arithmetic */ return 0; }
C
/****************************************************** * FILE NAME : data_traffic_proc.c * VERSION : 1.0 * DESCRIPTION : output the recorded host information * * AUTHOR : tangyupeng * CREATE DATE : 08/10/2016 * HISTORY : ******************************************************/ #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/if_ether.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/list.h> #include <linux/jiffies.h> #include "data_traffic_proc.h" #include "data_traffic_host_entry.h" #include "data_traffic_tbl_ops.h" static void *proc_seq_start(struct seq_file *m, loff_t *pos); static void *proc_seq_next(struct seq_file *m, void *v, loff_t *pos); static void proc_seq_stop(struct seq_file *m, void *v); static int proc_seq_show(struct seq_file *m, void *v); /********************************************* Function: dump_ip_addr Description: output the IP address Input: m, to which seq_file to output ip_addr, IP address to output **********************************************/ static void dump_ip_addr(struct seq_file *m, unsigned int ip_addr) { unsigned char *temp = (unsigned char *)(&ip_addr); seq_printf(m, "%d.%d.%d.%d\t", temp[0], temp[1], temp[2], temp[3]); } /*********************************************** Function: dump_mac_addr Description: output the MAC address Input: m, to which seq_file to output mac_addr, pointer to MAC address ************************************************/ static void dump_mac_addr(struct seq_file *m, unsigned char *mac_addr) { if (mac_addr == NULL) { printk(KERN_ERR "Parameter error, MAC address is NULL\n"); return; } seq_printf(m, "%02X:%02X:%02X:%02X:%02X:%02X\t", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); } /************************************************************ Function: dump_host_entry Description: output the host information, including IP/MAC address, download/upload speed and total data count. Input: m, to which seq_file to output host, which host entry to output ************************************************************/ static void dump_host_entry(struct seq_file *m, struct host_entry *host) { if (host == NULL) return; dump_mac_addr(m, host->info.mac_addr); dump_ip_addr(m, host->info.ip_addr); seq_printf(m, "%d\t", host->stat.download_speed); seq_printf(m, "%d\t", host->stat.upload_speed); seq_printf(m, "%llu\t", host->stat.download_total); seq_printf(m, "%llu\t", host->stat.upload_total); seq_printf(m, "%s\n", host->info.access_device_name); } /*********************************************************** Function: proc_seq_start Description: iteration functions, return parameter passed to "next" function Input: pos, iterator position ************************************************************/ static void *proc_seq_start(struct seq_file *m, loff_t *pos) { if (*pos >= table_size(g_lru_table)) return NULL; return g_lru_table->next; } /************************************************************** Function: proc_seq_next Description: iteration function, stops when receives NULL, return parameter passed to this function itself and "show" function ***************************************************************/ static void *proc_seq_next(struct seq_file *m, void *v, loff_t *pos) { struct list_head *temp_entry = (struct list_head *)v; (*pos)++; if (temp_entry->next == g_lru_table) return NULL; else return temp_entry->next; } static void proc_seq_stop(struct seq_file *m, void *v) { return; } /****************************************************** Function: proc_seq_show Description: iteration function, output the host info *******************************************************/ static int proc_seq_show(struct seq_file *m, void *v) { struct list_head *temp = (struct list_head *)v; struct host_entry *host = list_entry(temp, struct host_entry, lru_tbl_node); dump_host_entry(m, host); return 0; } static const struct seq_operations proc_seq_ops = { .start = proc_seq_start, .next = proc_seq_next, .stop = proc_seq_stop, .show = proc_seq_show, }; int proc_seq_open(struct inode *inode, struct file *filp) { return seq_open(filp, &proc_seq_ops); }
C
/****************************************************************************** Realizar un programa que determine si una persona es mayor o menor de edad. Datos de entrada Entero: edad Proceso Escribir "Ingrese su edad" Leer edad Si(edad>=17) Escribir "Mayor de edad" Sino Escribir "Menor de edad" Salida Mayor o menor de edad *******************************************************************************/ #include <stdio.h> void main() { int edad; char nombre[10]; printf("Ingrese su nombre: "); scanf("%s", nombre); printf("Ingrese su edad: "); scanf("%d", &edad); if(edad>=18) printf("%s es mayor de edad", nombre); else printf("%s es menor de edad", nombre); }
C
#include "../../reowolf.h" #include "../utility.c" int main(int argc, char** argv) { // Create a connector, configured with our (trivial) protocol. Arc_ProtocolDescription * pd = protocol_description_parse("", 0); char logpath[] = "./pres_3_bob.txt"; Connector * c = connector_new_logging(pd, logpath, sizeof(logpath)-1); rw_err_peek(c); // ... with 2 outgoing network connections PortId ports[2]; FfiSocketAddr addr = {{127,0,0,1}, 8000}; connector_add_net_port(c, &ports[0], addr, Polarity_Getter, EndpointPolarity_Active); rw_err_peek(c); addr.port = 8001; connector_add_net_port(c, &ports[1], addr, Polarity_Getter, EndpointPolarity_Active); rw_err_peek(c); // Connect with peers (5000ms timeout). connector_connect(c, 5000); rw_err_peek(c); for(int i=0; i<3; i++) { printf("\nNext round...\n"); printf("\nOption 0: Get {A}\n"); connector_get(c, ports[0]); connector_next_batch(c); rw_err_peek(c); printf("\nOption 1: Get {B}\n"); connector_get(c, ports[1]); connector_next_batch(c); rw_err_peek(c); printf("\nOption 2: Get {A, B}\n"); connector_get(c, ports[0]); connector_get(c, ports[1]); int code = connector_sync(c, 1000); printf("Outcome: %d\n", code); rw_err_peek(c); } printf("Exiting\n"); protocol_description_destroy(pd); connector_destroy(c); sleep(1.0); return 0; }
C
char buffer_client[1024]; int clientSocket; struct sockaddr_in serverAddr; pthread_t thread1, thread2; int iret1, iret2; socklen_t addr_size; int port; /* Status Bar*/ void status_bar(int i,int total){ int j; int percent = (25*i)/total; printf("["); for(j=0;j<=percent;j++){ printf(">"); } for(j=0;j<25-percent;j++){ printf(" "); } printf("] %d %% \r\n",percent*4); fflush(stdout); } void upload_file_to_Server(char FILE_TO_SEND[]){ int fd; int sent_bytes = 0; char file_size[BUFSIZ]; struct stat file_stat; fd = open(FILE_TO_SEND, O_RDONLY); if (fd == -1) { fprintf(stderr, "Error opening file --> %s", strerror(errno)); return; } /* Get file stats */ if (fstat(fd, &file_stat) < 0) { fprintf(stderr, "Error fstat --> %s", strerror(errno)); return; } fprintf(stdout, "File Size: \n%d bytes\n", file_stat.st_size); sprintf(file_size, "%d", file_stat.st_size); /* Sending file size */ int len = send(clientSocket, file_size, sizeof(file_size), 0); if (len < 0) { fprintf(stderr, "Error on sending greetings --> %s", strerror(errno)); return; } fprintf(stdout, "Server sent %d bytes for the size\n", len); int offset = 0; int remain_data = file_stat.st_size; printf("remaining data: %d\n", remain_data); /* Sending file data */ while (((sent_bytes = sendfile(clientSocket, fd, offset, BUFSIZ)) > 0) && (remain_data >= 0)) { //fprintf(stdout, "1. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data); remain_data -= sent_bytes; //fprintf(stdout, "2. Server sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data); status_bar(file_stat.st_size - remain_data, file_stat.st_size); //fflush(stdout); } close(fd); printf("----------Completed uploading----------\n"); } void recv_file_from_server(char FILENAME[]){ ssize_t len; char buffer_client[BUFSIZ]; int file_size; FILE *received_file; int remain_data = 0; /* Receiving file size */ recv(clientSocket, buffer_client, BUFSIZ, 0); file_size = atoi(buffer_client); //fprintf(stdout, "\nFile size : %d\n", file_size); received_file = fopen(FILENAME, "w"); if (received_file == NULL) { fprintf(stderr, "Failed to open file foo --> %s\n", strerror(errno)); return ; } remain_data = file_size; while (((remain_data > 0) && ((len = recv(clientSocket, buffer_client, BUFSIZ, 0)) > 0)) ) { //fwrite(buffer_client, sizeof(char), len, received_file); remain_data -= len; //fprintf(stdout, "Receive %d bytes and we hope :- %d bytes\n", len, remain_data); status_bar(file_size - remain_data, file_size); } fclose(received_file); printf("------------Completed Receiving File-------\n"); } void *Recv_From_Server(){ while(1){ bzero(buffer_client, sizeof(buffer_client)); if(recv(clientSocket, buffer_client, 1024, 0) > 0){ printf("[Server]>>: %s\n", buffer_client); int n = strlen(buffer_client); char FILE_TO_SEND[256]; if( n > 4){ if((buffer_client[n-4]==' ' && buffer_client[n-3]=='U' && buffer_client[n-2]=='D' && buffer_client[n-1]=='P') || (buffer_client[n-4]==' ' && buffer_client[n-3]=='T' && buffer_client[n-2]=='C' && buffer_client[n-1]=='P')){ printf("Recv the file...\n"); char FILENAME[BUFSIZ]; strncpy(FILENAME, buffer_client,n-4); printf("%s\n", FILENAME); FILE_TO_SEND[n-3] = '\0'; recv_file_from_server(FILENAME); } } } else{ return 0; } } } void *Send_To_Server(){ while(1){ bzero(buffer_client, sizeof(buffer_client)); getchar(); //printf("[Client]>>: "); scanf("%[^\n]s",buffer_client); if(send(clientSocket,buffer_client,sizeof(buffer_client),0) < 0){ return 0; } int n = strlen(buffer_client); char FILE_TO_SEND[256]; if( n > 4){ if((buffer_client[n-4]==' ' && buffer_client[n-3]=='U' && buffer_client[n-2]=='D' && buffer_client[n-1]=='P') || (buffer_client[n-4]==' ' && buffer_client[n-3]=='T' && buffer_client[n-2]=='C' && buffer_client[n-1]=='P')){ strncpy(FILE_TO_SEND, buffer_client,n-4); FILE_TO_SEND[n-3] = '\0'; printf("The upload file name is %s\n", FILE_TO_SEND); upload_file_to_Server(FILE_TO_SEND); } } } }
C
#include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <ctype.h> int main(int argc, char *argv[]) { int sock_conn, sock_listen, ret; struct sockaddr_in serv_adr; char buff[512]; char buff2[512]; // INICIALITZACIONS // Obrim el socket if ((sock_listen = socket(AF_INET, SOCK_STREAM, 0)) < 0) printf("Error creant socket"); // Fem el bind al port memset(&serv_adr, 0, sizeof(serv_adr));// inicialitza a zero serv_addr serv_adr.sin_family = AF_INET; // asocia el socket a cualquiera de las IP de la m?quina. //htonl formatea el numero que recibe al formato necesario serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); // escucharemos en el port 9050 serv_adr.sin_port = htons(9050); if (bind(sock_listen, (struct sockaddr *) &serv_adr, sizeof(serv_adr)) < 0) printf ("Error al bind"); //La cola de peticiones pendientes no podr? ser superior a 4 if (listen(sock_listen, 2) < 0) printf("Error en el Listen"); int i; // Atenderemos solo 5 peticione for(i=0;i<7;i++) { printf ("Escuchando\n"); sock_conn = accept(sock_listen, NULL, NULL); printf ("He recibido conexion\n"); //sock_conn es el socket que usaremos para este cliente //Bucle de atencin al cliente int terminar=0; while (terminar == 0) { // Ahora recibimos su nombre, que dejamos en buff ret=read(sock_conn,buff, sizeof(buff)); printf ("Recibido\n"); // Tenemos que a?adirle la marca de fin de string // para que no escriba lo que hay despues en el buffer buff[ret]='\0'; //Escribimos el nombre en la consola printf ("Se ha conectado: %s\n",buff); char *p = strtok (buff, "/"); int codigo = atoi (p); int grados; if (codigo !=0) { printf("Codigo!=0"); p = strtok( NULL, "/"); grados = atoi (p); printf ("Codigo: %d, Grados: %i\n", codigo, grados); } if (codigo == 0){ printf("Codigo=0"); terminar = 1; } else if (codigo == 1){ // Conversion de Celsius a Fahrenheit int res = grados; res = (res * 9/5) + 32; sprintf (buff2, "%i oC son %d oF", grados, res); if (codigo != 0) { printf ("%s\n", buff2); // Y lo enviamos write (sock_conn,buff2, strlen(buff2)); } } else if (codigo == 2){ // Conversion de Celsius a Fahrenheit int res = grados; res = (res - 32) * 5/9; sprintf (buff2, "%i oF son %d oC", grados, res); if (codigo != 0) { printf ("%s\n", buff2); // Y lo enviamos write (sock_conn,buff2, strlen(buff2)); } } } // Se acabo el servicio para este cliente close(sock_conn); } }
C
/* Tim M. Lael CS4280 p3 14-APR 2017 */ /* semantics.h This is the source file containing function the definition for stack and semantic operations */ /* Begin inclusion-prevention mechanism */ #ifndef SEMANTICS_H #define SEMANTICS_H #define MAXSTACKSIZE 100 /* Stack size limit per project spec */ #include "token.h" #include "node.h" /* Stack operations */ void push(token_t stack_tk); void pop(int scopeStart); void stackInit(void); /* Variable/stack search operations */ int find(char *var); int varExists(char *var); /* Main semantic checking function */ void semanticCheck(node_t *node, int count); /* End inclusion-prevention mechanism */ #endif /* SEMANTICS_H */
C
#include "red_black_tree.h" #include <stdlib.h> #include <stdio.h> #include "common.h" #define NIL (&p_tree->nil) #define ROOT (p_tree->p_root) #define _set_nil(p_node) (p_node = NIL) #define _is_red(p_node) (p_node->color == red) #define _set_left_child(parent,child) \ do { \ parent->p_left = child; \ child->p_parent = parent; \ } while (0) #define _set_right_child(parent,child) \ do { \ parent->p_right = child; \ child->p_parent = parent; \ } while (0) #define _set_child(parent,left,right) \ do { \ _set_left_child(parent, left); \ _set_right_child(parent, right); \ } while (0) #define _ini_insert_node(value,p_insert,parent) \ do { \ p_insert = (PRB_node_t)malloc(sizeof(RB_node_t)); \ p_insert->value = value; \ p_insert->cnt = 1; \ _set_nil(p_insert->p_left); \ _set_nil(p_insert->p_right); \ _set_red(p_insert); \ p_insert->p_parent = parent; \ if (value < parent->value) { \ _set_left_child(parent, p_insert); \ } else { \ _set_right_child(parent, p_insert); \ } \ } while (0) #define _change_child(parent,old_child,new_child) \ do { \ new_child->p_parent = parent; \ if (parent->p_left == old_child) { \ parent->p_left = new_child; \ } else { \ parent->p_right = new_child; \ } \ } while (0) #define _set_red(p_node) p_node->color=red #define _set_black(p_node) p_node->color=black #define _set_root(p_node) \ do { \ _set_black(p_node); \ _set_nil(p_node->p_parent); \ ROOT = p_node; \ } while (0) #define _reset_nil(...) \ do { \ NIL->p_parent = NIL; \ NIL->p_left = NIL; \ NIL->p_right = NIL; \ } while (0) #define _swap_p(p1, p2) do { p_tmp_ = p1; p1 = p2; p2 = p_tmp_; } while (0) #define _adopt_child(p_node) \ do { \ p_node->p_left->p_parent = p_node; \ p_node->p_right->p_parent = p_node; \ } while (0) #define _swap_node(upper,lower) \ do { \ PRB_node_t p_tmp_; \ PRB_node_t upper_parent = upper->p_parent; \ uint32_t upper_color = upper->color; \ upper->color = lower->color; \ lower->color = upper_color; \ if (lower->p_parent == upper) { \ if (upper->p_left == lower) { \ upper->p_left = lower->p_left; \ lower->p_left = upper; \ _swap_p(upper->p_right, lower->p_right); \ _adopt_child(lower); \ _adopt_child(upper); \ } else { \ upper->p_right = lower->p_right; \ lower->p_right = upper; \ _swap_p(upper->p_left, lower->p_left); \ _adopt_child(lower); \ _adopt_child(upper); \ } \ } else { \ _swap_p(lower->p_left, upper->p_left); \ _swap_p(lower->p_right, upper->p_right); \ _swap_p(lower->p_parent, upper->p_parent); \ _change_child(upper->p_parent, lower, upper); \ _adopt_child(lower); \ _adopt_child(upper); \ } \ if (upper_parent == NIL) { \ _set_root(lower); \ /*_reset_nil();*/ \ break; \ } else { \ _change_child(upper_parent, upper, lower); \ /*_reset_nil();*/ \ break; \ } \ } while (0) #define _rotate_left(parent,right) \ do { \ _change_child(parent->p_parent, parent, right); \ _set_right_child(parent, right->p_left); \ _set_left_child(right, parent); \ } while (0) #define _rotate_right(parent,left) \ do { \ _change_child(parent->p_parent, parent, left); \ _set_left_child(parent, left->p_right); \ _set_right_child(left, parent); \ } while (0) void RBTree_ini(PRB_tree_t p_tree) { p_tree->p_root = NIL; _reset_nil(); NIL->value = 0; NIL->cnt = 0; _set_black(NIL); } PRB_node_t RBTree_search_node(PRB_node_t p_node, value_t value) { while (p_node && p_node->value != value) { p_node = p_node->value > value ? p_node->p_left : p_node->p_right; } return p_node; } PRB_node_t RBTree_insert(PRB_tree_t p_tree, value_t value) { PRB_node_t p_insert = ROOT; //the first node insert to the tree if (p_insert == NIL) { ROOT = (PRB_node_t)malloc(sizeof(RB_node_t)); ROOT->value = value; ROOT->cnt = 1; _set_nil(ROOT->p_parent); _set_nil(ROOT->p_left); _set_nil(ROOT->p_right); _set_black(ROOT); return ROOT; } PRB_node_t p_p; while (p_insert != NIL && p_insert->value != value) { p_p = p_insert; p_insert = value < p_insert->value ? p_insert->p_left : p_insert->p_right; } //after this while loop, p_p mustn't be NIL //the insert value already in the tree, just add the `cnt' of the corresponding node. if (p_insert != NIL) { p_insert->cnt++; return p_insert; } //create one node, whose child nodes are `NIL' and color is red _ini_insert_node(value, p_insert, p_p); while (_is_red(p_p)) { //p_p is not the node of the tree, because its color is black PRB_node_t p_pp = p_p->p_parent; //p_pp is not `NIL' PRB_node_t p_ppp = p_pp->p_parent; if (p_p == p_pp->p_left) { if (_is_red(p_pp->p_right)) { _set_black(p_p); _set_black(p_pp->p_right); if (p_ppp == NIL) { //is this case p_pp is the root node, and already be black _xx_assert_(p_pp == ROOT); return p_pp; } _set_red(p_pp); p_insert = p_pp; p_p = p_ppp; continue; } if (p_insert == p_p->p_left) { _set_left_child(p_pp, p_p->p_right); _set_right_child(p_p, p_pp); _set_black(p_insert); if (p_ppp == NIL) { _set_root(p_p); return ROOT; } _change_child(p_ppp, p_pp, p_p); p_insert = p_p; p_p = p_ppp; continue; } else { _set_right_child(p_p, p_insert->p_left); _set_left_child(p_pp, p_insert->p_right); _set_child(p_insert, p_p, p_pp); _set_black(p_p); if (p_ppp == NIL) { _set_root(p_insert); return ROOT; } _change_child(p_ppp, p_pp, p_insert); //p_insert does not change p_p = p_ppp; continue; } } else { if (_is_red(p_pp->p_left)) { _set_black(p_p); _set_black(p_pp->p_left); if (p_ppp == NIL) { //is this case p_pp is the root node, and already be black _xx_assert_(p_pp == ROOT); return ROOT; } _set_red(p_pp); p_insert = p_pp; p_p = p_ppp; continue; } if (p_insert == p_p->p_right) { _set_right_child(p_pp, p_p->p_left); _set_left_child(p_p, p_pp); _set_black(p_insert); if (p_ppp == NIL) { _set_root(p_p); return ROOT; } _change_child(p_ppp, p_pp, p_p); p_insert = p_p; p_p = p_ppp; continue; } else { _set_right_child(p_pp, p_insert->p_left); _set_left_child(p_p, p_insert->p_right); _set_child(p_insert, p_pp, p_p); _set_black(p_p); if (p_ppp == NIL) { _set_root(p_insert); return ROOT; } _change_child(p_ppp, p_pp, p_insert); //p_insert does not change p_p = p_ppp; continue; } } } return p_p; } PRB_node_t RBTree_delete_p(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node || p_node == NIL) return NULL; uint32_t choose_left = p_node->value & 1; uint32_t delete_red; PRB_node_t p_p; PRB_node_t p_pp; PRB_node_t p_sibling; PRB_node_t p_tmp; if (p_node->p_left == NIL && p_node->p_right == NIL) { if (p_node == ROOT) { free(p_node); _set_nil(ROOT); return NULL; } } else { if (p_node->p_right == NIL || (p_node->p_left != NIL && choose_left)) { p_tmp = p_node->p_left; while (p_tmp->p_right != NIL) { p_tmp = p_tmp->p_right; } } else { p_tmp = p_node->p_right; while (p_tmp->p_left != NIL) { p_tmp = p_tmp->p_left; } } _swap_node(p_node, p_tmp); // swich the pointer's position, but another way, is just swiching ther pointer's value } p_p = p_node->p_parent; p_pp = p_p->p_parent; p_sibling = p_node == p_p->p_left ? p_p->p_right : p_p->p_left; p_tmp = p_node; p_node = p_node->p_left != NIL ? p_node->p_left : p_node->p_right; // p_node->p_left and p_node->p_right can be both NIL, so this line may make p_node be NIL, and in this case, the next line will make NIL's parent be p_p, this is significant and we will not `_reset_nil()' _change_child(p_p, p_tmp, p_node); delete_red = p_tmp->color == red; free(p_tmp); if (delete_red) { return NULL; } if (_is_red(p_node)) { // p_node: red _set_black(p_node); return NULL; } // the sub tree's bh need to increase 1, whose root is `p_node' while (1) { if (_is_red(p_p)) { // p_node: black, p_p: red, p_sibling: black if (p_node == p_p->p_left) { if (_is_red(p_sibling->p_left)) { p_tmp = p_sibling->p_left; _rotate_right(p_sibling, p_tmp); _xx_assert_(p_tmp == p_p->p_right); _rotate_left(p_p, p_tmp); _set_black(p_p); return NULL; } else { _rotate_left(p_p, p_sibling); return NULL; } } else { if (_is_red(p_sibling->p_right)) { p_tmp = p_sibling->p_right; _rotate_left(p_sibling, p_tmp); _xx_assert_(p_tmp == p_p->p_left); _rotate_right(p_p, p_tmp); _set_black(p_p); return NULL; } else { _rotate_right(p_p, p_sibling); return NULL; } } } else if (_is_red(p_sibling)) { // p_node: black, p_p: black, p_sibling: red if (p_node == p_p->p_left) { _rotate_left(p_p, p_sibling); if (p_pp == NIL) { _set_root(p_sibling); } _set_black(p_sibling); _set_red(p_p); p_pp = p_sibling; p_node = p_p->p_left; p_sibling = p_p->p_right; } else { _rotate_right(p_p, p_sibling); if (p_pp == NIL) { _set_root(p_sibling); } _set_black(p_sibling); _set_red(p_p); p_pp = p_sibling; p_node = p_p->p_right; p_sibling = p_p->p_left; } } else { // p_node: black, p_p: black, p_sibling: black if (p_node == p_p->p_left) { if (_is_red(p_sibling->p_left)) { p_tmp = p_sibling->p_left; _rotate_right(p_sibling, p_tmp); _rotate_left(p_p, p_tmp); if (p_pp == NIL) { _set_root(p_tmp); } _set_black(p_tmp); return NULL; } else { _rotate_left(p_p, p_sibling); } } else { if (_is_red(p_sibling->p_right)) { p_tmp = p_sibling->p_right; _rotate_left(p_sibling, p_tmp); _rotate_right(p_p, p_tmp); if (p_pp == NIL) { _set_root(p_tmp); } _set_black(p_tmp); return NULL; } else { _rotate_right(p_p, p_sibling); } } _set_red(p_p); if (p_pp == NIL) { _set_root(p_sibling); return NULL; } p_node = p_sibling; p_p = p_pp; p_pp = p_p->p_parent; _xx_assert_(p_node->p_parent == p_p); _xx_assert_(p_node == p_p->p_left || p_node == p_p->p_right); p_sibling = p_node == p_p->p_left ? p_p->p_right : p_p->p_left; } } } uint32_t RBTree_inorder(PRB_tree_t p_tree, PRB_node_t p_node, value_t *buf) { if (!p_node) p_node = ROOT; if (p_node == NIL) return 0; uint32_t n = RBTree_inorder(p_tree, p_node->p_left, buf); uint32_t i; for (i = 0; i < p_node->cnt; i++) { buf[n++] = p_node->value; } return n + RBTree_inorder(p_tree, p_node->p_right, buf + n); } uint32_t RBTree_size(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node) p_node = ROOT; if (p_node == NIL) return 0; return 1 + RBTree_size(p_tree, p_node->p_left) + RBTree_size(p_tree, p_node->p_right); } uint32_t RBTree_height(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node) p_node = ROOT; if (p_node == NIL) return 0; uint32_t l_h = RBTree_height(p_tree, p_node->p_left); uint32_t r_h = RBTree_height(p_tree, p_node->p_right); return 1 + (l_h > r_h ? l_h : r_h); } uint32_t RBTree_black_height(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node) p_node = ROOT; if (p_node == NIL) return 0; //leaf nodes have black height 0 uint32_t l_h = RBTree_black_height(p_tree, p_node->p_left); _xx_assert_(l_h == RBTree_black_height(p_tree, p_node->p_right)); _xx_assert_(p_node->color == red ? (p_node->p_left->color == black && p_node->p_right->color == black) : 1); return l_h + (p_node->color == black ? 1 : 0); } PRB_node_t RBTree_minimum(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node) p_node = ROOT; if (p_node == NIL) return NULL; while (p_node->p_left != NIL) { p_node = p_node->p_left; } return p_node; } PRB_node_t RBTree_maximum(PRB_tree_t p_tree, PRB_node_t p_node) { if (!p_node) p_node = ROOT; if (p_node == NIL) return NULL; while (p_node->p_right != NIL) { p_node = p_node->p_right; } return p_node; } PRB_node_t RBTree_successor(PRB_tree_t p_tree, PRB_node_t p_node) { if (p_node == NIL || !p_node) return NULL; if (p_node->p_right != NIL) return RBTree_minimum(p_tree, p_node->p_right); PRB_node_t p_p = p_node->p_parent; while (p_p != NIL && p_p->p_right == p_node) { p_node = p_p; p_p = p_p->p_parent; } return p_p == NIL ? NULL : p_p; } PRB_node_t RBTree_predecessor(PRB_tree_t p_tree, PRB_node_t p_node) { if (p_node == NIL || !p_node) return NULL; if (p_node->p_left != NIL) return RBTree_maximum(p_tree, p_node->p_left); PRB_node_t p_p = p_node->p_parent; while (p_p != NIL && p_p->p_left == p_node) { p_node = p_p; p_p = p_p->p_parent; } return p_p == NIL ? NULL : p_p; } PRB_node_t RBTree_search(PRB_tree_t p_tree, PRB_node_t p_node, value_t value) { if (!p_node) p_node = ROOT; if (p_node == NIL) return NULL; while (p_node != NIL && p_node->value != value) { p_node = value < p_node->value ? p_node->p_left : p_node->p_right; } return p_node == NIL ? NULL : p_node; } //<begin print tree> uint32_t digit_wide(uint32_t digit) { uint32_t w = 1; while (digit /= 10) { w++; } return w; } void print_one_digit(uint32_t digit, uint32_t wide, uint32_t x) { uint32_t d_w = digit_wide(digit) + 1; uint32_t gap = wide/2 - d_w/2; uint32_t i; for (i = 0; i < gap; i++) printf(" "); if (x != 0) { printf("%u", digit); printf("%s", x == 1 ? "r" : "b"); } else { printf(" #"); } for (i += d_w; i < wide; i++) printf(" "); return; } void print_void_node(uint32_t wide, uint32_t h) { wide >>= h; uint32_t i; for (i = 0; i < (1<<(h-1)); i++ ) { print_one_digit(0, wide, 0); } } void rbtree_print_one_layer(PRB_tree_t p_tree, PRB_node_t p_node, uint32_t h, uint32_t w) { if (p_node == NIL) return; if (!h) { print_one_digit(p_node->value, w, p_node->color == red ? 1 : 2); return; } if (p_node->p_left == NIL) { print_void_node(w, h); } else { rbtree_print_one_layer(p_tree, p_node->p_left, h-1, w/2); } if (p_node->p_right == NIL) { print_void_node(w, h); } else { rbtree_print_one_layer(p_tree, p_node->p_right, h-1, w/2); } } void RBTree_print(PRB_tree_t p_tree, PRB_node_t p_node, uint32_t h_1) { if (!h_1) return; if (!p_node) p_node = ROOT; if (p_node == NIL) return; uint32_t h = RBTree_height(p_tree, p_node); h = h < h_1 ? h : h_1; uint32_t dw = digit_wide(RBTree_maximum(p_tree, p_node)->value) + 2 + 1; uint32_t l_w = dw * (1<<(h-1)); uint32_t i; for (i = 0; i < h; i++) { rbtree_print_one_layer(p_tree, p_node, i, l_w); printf("\n"); } } //<end print tree> #undef _xx_assert_ #undef NIL #undef ROOT #undef _set_nil #undef _is_red #undef _set_left_child #undef _set_right_child #undef _set_child #undef _ini_insert_node #undef _change_child #undef _set_red #undef _set_black #undef _set_root #undef _reset_nil #undef _swap_node #undef _swap_p #undef _adopt_child #undef _rotate_left #undef _rotate_right
C
//bai tap 3 #include <stdio.h> #include <math.h> int main() { float a, b; printf("Nhap do dai canh thu nhat cua hcn : "); scanf("%f", &a); printf("Nhap do dai canh thu hai cua hcn : "); scanf("%f", &b); printf("\nChu vi cua hcn la : %f\n", (a+b)*2); printf("\nDien tich cua hcn la : %f\n", a*b); return 0; }
C
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2000-2001 Silicon Graphics, Inc. * All Rights Reserved. */ #include <lib/hsm.h> #include <getopt.h> #include <string.h> /*--------------------------------------------------------------------------- Test program used to test the DMAPI function dm_remove_dmattr(). The command line is: remove_dmattr [-s sid] [-u] pathname attr where pathname is the name of a file, attr is the name of the DMAPI attribute, and sid is the session ID whose attributes you are interested in. ----------------------------------------------------------------------------*/ #ifndef linux extern char *sys_errlist[]; #endif extern int optind; extern char *optarg; char *Progname; static void usage(void) { fprintf(stderr, "usage:\t%s [-s sid] [-u] pathname attr\n", Progname); exit(1); } int main( int argc, char **argv) { dm_sessid_t sid = DM_NO_SESSION; char *pathname; dm_attrname_t *attrnamep; int setdtime = 0; void *hanp; size_t hlen; char *name; int opt; Progname = strrchr(argv[0], '/'); if (Progname) { Progname++; } else { Progname = argv[0]; } /* Crack and validate the command line options. */ while ((opt = getopt(argc, argv, "s:u")) != EOF) { switch (opt) { case 's': sid = atol(optarg); break; case 'u': setdtime = 1; break; case '?': usage(); } } if (optind + 2 != argc) usage(); pathname = argv[optind++]; attrnamep = (dm_attrname_t *)argv[optind++]; if (dm_init_service(&name) == -1) { fprintf(stderr, "Can't initialize the DMAPI\n"); exit(1); } if (sid == DM_NO_SESSION) find_test_session(&sid); /* Get the file's handle. */ if (dm_path_to_handle(pathname, &hanp, &hlen)) { fprintf(stderr, "can't get handle for file %s\n", pathname); exit(1); } if (dm_remove_dmattr(sid, hanp, hlen, DM_NO_TOKEN, setdtime, attrnamep)) { fprintf(stderr, "dm_remove_dmattr failed, %s\n", strerror(errno)); exit(1); } dm_handle_free(hanp, hlen); exit(0); }
C
#include "Atoms.h" const int cornerLimit = 2; const int sideLimit = 3; const int otherLimit = 4; struct dim dimensions; struct dim *enter_dim(int x, int y){ dimensions.xDim = x; dimensions.yDim = y; return &dimensions; } struct root *createList(){ struct root *list = malloc(sizeof(struct root)); list->first = NULL; list->length = 0; return list; } struct atom *createAtom(char player, int x, int y, int limit){ struct atom *position = malloc(sizeof(struct atom)); position->player = player; position->x = x; position->y = y; position->limit = limit; position->atoms = 1; return position; } int assignLimit(int x, int y){ int xMax = dimensions.xDim - 1; int yMax = dimensions.yDim - 1; if ((x == 0 && y == 0) || (x == 0 && y == xMax) ||(y == 0 && x == xMax) || (y == yMax && x == xMax)) return cornerLimit; if (x == 0 || y == 0 || x == xMax || y == yMax) return sideLimit; return otherLimit; } struct atom *atomPresent(struct root *list, int x, int y){ struct atom *node = list->first; while (node) { if (node->x == x && node->y == y) return node; node = node->next; } return NULL; } void deleteAtom(struct root *list, struct atom *position){ --(list->length); struct atom *node = list->first; if (node->x == position->x && node->y == position->y) { struct atom *remove = node; list->first=node->next; free(remove); remove = NULL; return; } while (node && node->next) { if (node->next->x == position->x && node->next->y == position->y) { struct atom *remove = node->next; node->next=remove->next; free(remove); remove = NULL; return; } node = node->next; } } bool addAtom(struct root *list, char player, int x, int y, bool chain){ int limit = assignLimit(x, y); struct atom *node = atomPresent(list, x, y); if (node && chain) node->player = player; if (node == NULL) { struct atom *position = createAtom(player, x, y, limit);; ++(list->length); position->next = list->first; list->first = position; } else if (node->player == player){ if (node->atoms+1 < limit) { ++(node->atoms); } else { if (list->length > (dimensions.xDim * dimensions.yDim)) return true; /* This is to stop the chain reaction when grid is filled*/ deleteAtom(list, node); int xInc = x + 1; int xDec = x - 1; int yInc = y + 1; int yDec = y - 1; if (xInc < dimensions.xDim) addAtom(list, player, x+1, y, true); if (xDec > 0) addAtom(list, player, x-1, y, true); if (yInc < dimensions.yDim) addAtom(list, player, x, y+1, true); if (yDec > 0) addAtom(list, player, x, y+1, true); } } return false; } void delete_list(struct root *list){ struct atom *current = list->first; while (current) { struct atom *delete = current; current = current->next; free(delete); } free(list); } void printBoard(struct root *list, struct dim *dim){ int xMax = dim->xDim; int yMax = dim->yDim; int len = xMax * 3 - 1; printf("+"); for (int i=0; i<len; ++i) { printf("-"); } printf("+\n"); for (int i=0; i<yMax; ++i) { for (int j=0; j<xMax; ++j) { struct atom *node = list->first; bool notOccupied = true; while (node) { if (node->y == i && node->x == j) { printf("|%c%d", node->player, node->atoms); notOccupied = false; break; } node=node->next; } if (notOccupied) { printf("| "); } } printf("|\n"); } printf("+"); for (int i=0; i<len; ++i) { printf("-"); } printf("+\n\n"); }
C
#include"Header.h" int main() { int iCnt=0,iLength=0,iRes=0; int *ptr=NULL; printf("Enter No of Elements"); scanf("%d",&iLength); ptr=(int*)malloc(iLength*sizeof(int)); printf("Enter Data"); for(iCnt=0;iCnt<iLength;iCnt++) { scanf("%d",&ptr[iCnt]); } iRes=Prime(ptr,iLength); printf("Largest Prime is %d",iRes); return 0; }
C
#include<stdio.h> int main() { int a,b; printf("Enter The First Number :"); scanf("%d",&a); printf("Enter The Second Number :"); scanf("%d",&b); a=a+b; b=a-b; a=a-b; printf("First Number = %d\nSecond Number = %d",a,b); return 0; }
C
/*#include "syscall.h" #define SIZE 100 int main() { int array[SIZE], i, sum=0; for (i=0; i<SIZE; i++) array[i] = i; for (i=0; i<SIZE; i++) sum += array[i]; system_PrintString("1Total sum: "); system_PrintInt(sum); system_PrintChar('\n'); system_PrintString("Executed instruction count: "); system_PrintInt(system_GetNumInstr()); system_PrintChar('\n'); system_Exit(0); return 0; } */ #include "syscall.h" int main() { system_PrintInt(10); system_PrintString("hello world\n"); system_PrintInt(system_GetNumInstr()); system_PrintString(" instructions.\n"); int *array = (int*)system_ShmAllocate(2*sizeof(int)); system_PrintInt(system_ShmAllocate(2*sizeof(int))); system_PrintString("hello world\n"); system_PrintInt(system_GetPA((unsigned)array)); array[0]=58; array[1]=98; system_PrintString("Executed "); system_PrintInt(array[0]); system_PrintInt(array[1]); return 0; }
C
#include<stdio.h> struct TestCases { char p[100]; int k; int result; } tests[] = { { "1239876", 3, 1 }, //positive number divisible by 3 { "11111", 13, 0 }, //positive number not divisible by 3 { "9999", 5, 1 }, { "-123321", 5, 1 }, //negative number divisible by 3 { "-1221", 21, 1 }, { "-98976698", 10, 0 }, //negative number not divisible by 3 { "99875756", 0, 1 }, //positive number repeating zero number of times { "-7687616", 0, 1 } //negative number repeating zero number of times }; int isDivBy3_1(char *p, int k) //handles only when the sum is less than the max int value { unsigned int i, sum = 0; while (k--) { i = 0; if (p[0] < '0') i = 1; while (p[i] != '\0') sum += p[i++] - '0'; } if (sum % 3 == 0) return 1; return 0; } int isDivBy3_2(char *p,int k) //handles number of any length repeating any number of times { int i, sum = 0; while (k--) { i = 0; if (p[0] < '0') //if number is negative then processing the number from next index value i.e 1 i = 1; while (p[i] != '\0') { sum += p[i++] - '0'; //calculating sum of integers sum %= 3; //decrementing the value of sum } } if (sum % 3) return 0; return 1; } void checkResult(int a, int b) { if (a == b) printf("PASS\n"); else printf("FAIL\n"); } int main() { int i = 0, result; for (i = 0; i < 8; i++) { result = isDivBy3_2(tests[i].p, tests[i].k); checkResult(result, tests[i].result); } getchar(); return 0; }
C
#include <stdio.h> int main(void) { int num1, num2, num3; puts("输入3个整数。"); printf("num1 = "); scanf("%d", &num1); printf("num2 = "); scanf("%d", &num2); printf("num3 = "); scanf("%d", &num3); int min; min = num1; if(num2 < min) min = num2; if(num3 < min) min = num3; printf("三个整数中的最小值为%d。\n", min); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** mysh ** File description: ** Contains functions used to test an exec list's validity */ #include <stddef.h> #include "structures/exec_list.h" #include "structures/token_list.h" #include "functions/str_display.h" static int get_pipes_nbr(token_list_t *list) { int pipes = 0; while (list) { if (list->type == PIPE) { ++pipes; } list = list->next; } return (pipes); } static int check_redirs_nbr(token_list_t *list) { int out_redir = 0; int in_redir = 0; int status = 1; while (status && list) { if (list->type == IN_REDIR || list->type == IN_REDIR_D) ++in_redir; else if (list->type == OUT_REDIR || list->type == OUT_REDIR_D) ++out_redir; list = list->next; } if (out_redir > 1) { status = 0; my_putstr("Ambiguous output redirect.\n", 2); } else if (in_redir > 1) { status = 0; my_putstr("Ambiguous input redirect.\n", 2); } return (status); } static int check_redirs_pos(token_list_t *list) { int pipes_nbr = get_pipes_nbr(list); int status = 1; int pipes = 0; while (status && list) { if (list->type == PIPE) { ++pipes; } if ((list->type == IN_REDIR || list->type == IN_REDIR_D) && pipes) { my_putstr("Ambiguous input redirect.\n", 2); status = 0; } else if ((list->type == OUT_REDIR || list->type == OUT_REDIR_D) && pipes != pipes_nbr) { my_putstr("Ambiguous output redirect.\n", 2); status = 0; } list = list->next; } return (status); } static int check_commands(token_list_t *list) { int has_word = 0; int status = 1; while (status && list) { if (list->type == WORD && !has_word) has_word = 1; if (list->type == PIPE && has_word) has_word = 0; else if (list->type == PIPE && !has_word) status = 0; list = list->next; } if (!has_word) { my_putstr("Invalid null command.\n", 2); status = 0; } return (status); } int check_token_list(token_list_t *list) { int status = 1; status = check_redirs_pos(list); if (status) { status = check_redirs_nbr(list); if (status) { status = check_commands(list); } } return (status); }
C
#include "libft.h" static size_t wrdnum(char const *s, char c) { size_t i; size_t n; i = 0; if (!*s) return (0); n = 1; while (*(s + i) == c) i++; while (*(s + i)) { if (*(s + i) == c && *(s + i - 1) != c) n++; i++; } if (*(s + i - 1) == c) n--; return (n); } static size_t wrdlen(char const *s, char c) { size_t i; i = 0; while (*(s + i)) { if (*(s + i) == c) return (i); i++; } return (i); } void freearr(char **arr, size_t n) { while (n--) free(arr[n]); free(arr); } static void splittwo(char const *s, char **arr, char c) { size_t n; size_t l; n = 0; while (*s) { if ((l = wrdlen(s, c))) { if ((arr[n] = malloc(sizeof(char) * (l + 1)))) { ft_strlcpy(arr[n], s, l + 1); s = s + (l - 1); n++; } else { freearr(arr, n); break ; } } s++; } } char **ft_split(char const *s, char c) { char **arr; size_t n; if (!s) return (NULL); n = wrdnum(s, c); arr = malloc(sizeof(char*) * (n + 1)); if (arr) { arr[n] = NULL; splittwo(s, arr, c); } return (arr); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "msgconf.h" #include "calcs.h" #include "inits.h" #include "loyal.h" #include "traitor.h" // initializes the generals' roles role_t* init_roles(int gen_no,int tra_no) { role_t *roles=(role_t*)malloc(gen_no*sizeof(role_t)); for(int i=0;i<gen_no;i++) roles[i]='L'; for(int i=0;i<tra_no;i++) { int x; while(roles[x=random(0,gen_no-1)]!='L'); roles[x]='T'; } return roles; } // creates a loyal general gen_t create_loyal(int gen_id,mbi_t *mbis,mbo_t mbo,int gen_no,vote_t vote) { gen_t gen=fork(); if(gen<0) { perror("create_loyal: fork"); exit(1); } if(!gen) { play_loyal(gen_id,mbis,mbo,gen_no,vote); exit(1); } return gen; } // creates a traitor general gen_t create_traitor(int gen_id,mbi_t *mbis,mbo_t mbo,int gen_no,role_t *roles,int tra_no) { gen_t gen=fork(); if(gen<0) { perror("create_traitor: fork"); exit(1); } if(!gen) { play_traitor(gen_id,mbis,mbo,gen_no,roles,tra_no); exit(1); } return gen; } // creates the generals gen_t* create_generals(role_t *roles,mb_t *mbs,mbi_t *mbis,int gen_no,int tra_no,vote_t *votes) { gen_t *gens=(gen_t*)malloc(gen_no*sizeof(gen_t)); for(int x=0,i=0;i<gen_no;i++) if(roles[i]=='L') gens[i]=create_loyal(i+1,mbis,mbs[i+1].mbo,gen_no,votes[x++]); else gens[i]=create_traitor(i+1,mbis,mbs[i+1].mbo,gen_no,roles,tra_no); return gens; }
C
#include <stdio.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <errno.h> #include <string.h> #define NUM_THREADS 2 sem_t sem_read, sem_write, sem_ready, sem_count; int g, c; void thread_routine(void *args) { int r, v, id = (long) args; printf("Thread #%d created\n", id); int f1, f2; switch(id) { case 1: f1 = open("fv1.b", O_RDONLY); if (!f1) { perror("Failed in opening fv1.b"); exit(-1); } while (read(f1, &v, sizeof(int))) { printf("[Thread #%d] Value read = %d\n", id, v); fflush(stdout); sem_wait(&sem_write); g = v; sem_post(&sem_read); sem_wait(&sem_ready); printf("[Thread #%d] New value = %d\n", id, g); sem_post(&sem_write); sleep(3); } break; case 2: f2 = open("fv2.b", O_RDONLY); if (!f2) { perror("Failed in opening fv2.b"); exit(-1); } while (read(f2, &v, sizeof(int))) { printf("[Thread #%d] Value read = %d\n", id, v); fflush(stdout); sem_wait(&sem_write); g = v; sem_post(&sem_read); sem_wait(&sem_ready); printf("[Thread #%d] New value = %d\n", id, g); sem_post(&sem_write); sleep(3); } break; } sem_wait(&sem_count); ++c; sem_post(&sem_count); printf("Thread #%d finished\n", id); pthread_exit(NULL); } int main(int argc, char *argv[], char *env[]) { int r; sem_init(&sem_ready, 0, 0); sem_init(&sem_read, 0, 0); sem_init(&sem_write, 0, 1); sem_init(&sem_count, 0, 1); printf("Semaphores initialized\n"); pthread_t t[2]; long i; for (i=0; i<NUM_THREADS; ++i){ pthread_create(&t[i], NULL, (void *) thread_routine, (void*) i+1); } while (1) { printf("Threads that finished: %d\n", c); if (c == NUM_THREADS) break; r = sem_wait(&sem_read); if (r) { perror(strerror(errno)); exit(-1); } g = g*3; r = sem_post(&sem_ready); if (r) { perror(strerror(errno)); exit(-1); } } for (i=0; i<NUM_THREADS; ++i){ pthread_join(t[i], NULL); } }
C
// // Created by 12547 on 2021/9/5. // #include "stdio.h" #include "stddef.h" #include "malloc.h" typedef struct LNode { int data; struct LNode *link; }LNode, *LinkList; /** * 创建 有头结点的单链表 * @param a * @param n * @return */ LinkList CreateListWithHead(const int a[], int n) { LinkList hnode = (LinkList)malloc(sizeof(LNode));//头结点 LinkList node = hnode; for (int i = 0; i < n; ++i) { LinkList tnode = (LinkList)malloc(sizeof(LNode)); tnode->data = a[i]; node->link = tnode; node = node->link; } node->link = NULL; return hnode; } /** * 中心思想就是一个快慢指针,一个快指针先走k-1步 * @param L * @param k * @return */ int find_reciprocal_kth(LinkList L, int k) { LNode *fast = L->link, *slow = L->link; int t = k - 1; while(t > 0 && fast != NULL) { fast = fast->link; t--; } if(fast == NULL) return 0; while(fast->link != NULL) { slow = slow->link; fast = fast->link; } printf("find the number:%d\n", slow->data); return 1; } int main() { int a[8] = {1, 7, 5, 6, 3, 4, 2, 14}; LinkList L; L = CreateListWithHead(a, 8); find_reciprocal_kth(L, 3); }
C
/* Algoritmo narrado. * 1.- Ingresar un numero deseado para realizar la piramide. * 2.- El numero ingresado será el límite, posterior a este límite * la escala comenzará a bajar. * 3.- Imprimir pirámide. * 4.- Retornar a 0. */ #include <stdio.h> int main () { int numero, i, p, q; printf ("Ingrese un numero para la piramide: "); scanf ("%d", &numero); for (i = 1 ; i <= numero ; i++){ for (p = 1; p<=i ; p++){ printf ("%d", p); if (i==p){ for (q = p-1; q > 0; q--){ printf ("%d", q); } } } printf ("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define REP_A 1901 /** * Nom de la fonction : jours_annee * Entrée: * int a: Une année comprise entre 1901 et 2099 * Sortie: * int jours : Le nombre de jours depuis 1901 jusqu'à cette année */ int jours_annee(int a) { return (a - REP_A) * 365.25; } /** * Nom de la fonction : longueur_mois * Entrées: * int a : Une année comprise entre 1901 et 2099 * int m : Le mois * Sortie: * int nombreJours : Le nombre de jour dans le mois */ int longueur_mois(int a, int m) { return m == 2 ? (a % 4? 28 : 29) : 30 + ((m + m / 8) & 1); } /** * Nom de la fonction : jours_mois * Entrées: * short int mois : Le mois * int an : L'année * Sortie: * int nombreJours : Le nombre de jours du début de l'année jusqu'au début * du mois. */ int jours_mois(short int mois, int an) { int nombreJours = 0, m; for(m = mois - 1; m >= 1; --m) nombreJours += longueur_mois(an, m); return nombreJours; } /** * Nom de la fonction : nom_jour * Entrées: * int an : Une année comprise entre 1901 et 2099 * int mois : Le mois * int jour : Le jour * Sortie: * char* : Le nom du jour en français * Description : * Retourne le nom du jour pour une date comprise entre 1-1-1901 et 31-12-2099 */ char* nom_jour(int an, int mois, int jour) { switch((jours_annee(an) + jours_mois(mois, an) + jour - 1) % 7) { case 0: return "Mardi"; case 1: return "Mercredi"; case 2: return "Jeudi"; case 3: return "Vendredi"; case 4: return "Samedi"; case 5: return "Dimanche"; default: return "Lundi"; } } /** * Nom de la fonction : verifie_date * Entrées: * int jour : Le jour * int mois : Le mois * int an : L'année * Sortie: * int valide : 1 si la date est valide et 0 dans l'autre cas * Description: * Vérifie si l'année est comprise entre 1901 et 2099, le mois entre 1 et 12 * et le nombre des jours selon le mois. */ int verifie_date(int j, int m, int a) { if(j < 1 || j > longueur_mois(a, m) || m < 1 || m > 12 || a < 1901 || a > 2099 ) return 0; return 1; } int main() { int j, m, a; printf("Entrez une date (jj/mm/aaaa) : "); scanf("%d/%d/%d", &j, &m, &a); if(verifie_date(j, m, a)) printf("Le %d/%d/%d est un %s\n", j, m, a, nom_jour(a, m, j)); else printf("Date invalide\n"); return 0; }
C
#include <stdio.h> #include <cs50.h> int main(void) //less comfortable { int height; //declare variables for easier reading int line; int spaces; int hashes; do //prompt user for number between 0 and 23 { printf("Height: "); height = get_int(); } while (height < 0 || height > 23); for (line = 0; line < height; line++) //main for loop for number of lines { for (spaces = height - line; spaces > 1; spaces--) //for loop for spaces { printf(" "); } for (hashes = 0; hashes < line + 2; hashes++) //for loop for 1st half of hashes { printf("#"); } printf("\n"); } }
C
#include <sms/intv-dummy-rst.h> #include <sms/console.h> #include <sms/uart.h> #include <stdint.h> /*Interrupt vectors. we want to catch NMI (Pause button)*/ void nmi(){ /*Reset ROM on button press*/ void (*rv)(void) = (void*)0x0000; rv(); } void int1(){ /*Do nothing*/ } uint8_t buff[128]; void main(){ uint8_t i; con_init(); con_put("UART echo test:\n\n"); con_put("Connect an UART transceiver on\n"); con_put("the SMS CONTROL 2 port as\n"); con_put("Shown below (SMS front):\n\n"); con_put(" CONTROL 2 \n"); con_put(" o o o o o \n"); con_put(" o o o o \n"); con_put(" | | `---PC TX (SMS RX)\n"); con_put(" | `-----Ground \n"); con_put(" `-------PC RX (SMS TX)\n"); con_put(" \n"); con_put("Serial port parameters are: \n"); con_put(" 4800bps 8 data bits \n"); con_put(" 1 start bit 1 stop bit \n"); con_put(""); con_put("This program will read 128\n"); con_put("characters then echo them back"); do{ UART_BUFF_GETC(buff, 0); UART_BUFF_GETC(buff, 1); UART_BUFF_GETC(buff, 2); UART_BUFF_GETC(buff, 3); UART_BUFF_GETC(buff, 4); UART_BUFF_GETC(buff, 5); UART_BUFF_GETC(buff, 6); UART_BUFF_GETC(buff, 7); UART_BUFF_GETC(buff, 8); UART_BUFF_GETC(buff, 9); UART_BUFF_GETC(buff, 10); UART_BUFF_GETC(buff, 11); UART_BUFF_GETC(buff, 12); UART_BUFF_GETC(buff, 13); UART_BUFF_GETC(buff, 14); UART_BUFF_GETC(buff, 15); UART_BUFF_GETC(buff, 16); UART_BUFF_GETC(buff, 17); UART_BUFF_GETC(buff, 18); UART_BUFF_GETC(buff, 19); UART_BUFF_GETC(buff, 20); UART_BUFF_GETC(buff, 21); UART_BUFF_GETC(buff, 22); UART_BUFF_GETC(buff, 23); UART_BUFF_GETC(buff, 24); UART_BUFF_GETC(buff, 25); UART_BUFF_GETC(buff, 26); UART_BUFF_GETC(buff, 27); UART_BUFF_GETC(buff, 28); UART_BUFF_GETC(buff, 29); UART_BUFF_GETC(buff, 30); UART_BUFF_GETC(buff, 31); UART_BUFF_GETC(buff, 32); UART_BUFF_GETC(buff, 33); UART_BUFF_GETC(buff, 34); UART_BUFF_GETC(buff, 35); UART_BUFF_GETC(buff, 36); UART_BUFF_GETC(buff, 37); UART_BUFF_GETC(buff, 38); UART_BUFF_GETC(buff, 39); UART_BUFF_GETC(buff, 40); UART_BUFF_GETC(buff, 41); UART_BUFF_GETC(buff, 42); UART_BUFF_GETC(buff, 43); UART_BUFF_GETC(buff, 44); UART_BUFF_GETC(buff, 45); UART_BUFF_GETC(buff, 46); UART_BUFF_GETC(buff, 47); UART_BUFF_GETC(buff, 48); UART_BUFF_GETC(buff, 49); UART_BUFF_GETC(buff, 50); UART_BUFF_GETC(buff, 51); UART_BUFF_GETC(buff, 52); UART_BUFF_GETC(buff, 53); UART_BUFF_GETC(buff, 54); UART_BUFF_GETC(buff, 55); UART_BUFF_GETC(buff, 56); UART_BUFF_GETC(buff, 57); UART_BUFF_GETC(buff, 58); UART_BUFF_GETC(buff, 59); UART_BUFF_GETC(buff, 60); UART_BUFF_GETC(buff, 61); UART_BUFF_GETC(buff, 62); UART_BUFF_GETC(buff, 63); UART_BUFF_GETC(buff, 64); UART_BUFF_GETC(buff, 65); UART_BUFF_GETC(buff, 66); UART_BUFF_GETC(buff, 67); UART_BUFF_GETC(buff, 68); UART_BUFF_GETC(buff, 69); UART_BUFF_GETC(buff, 70); UART_BUFF_GETC(buff, 71); UART_BUFF_GETC(buff, 72); UART_BUFF_GETC(buff, 73); UART_BUFF_GETC(buff, 74); UART_BUFF_GETC(buff, 75); UART_BUFF_GETC(buff, 76); UART_BUFF_GETC(buff, 77); UART_BUFF_GETC(buff, 78); UART_BUFF_GETC(buff, 79); UART_BUFF_GETC(buff, 80); UART_BUFF_GETC(buff, 81); UART_BUFF_GETC(buff, 82); UART_BUFF_GETC(buff, 83); UART_BUFF_GETC(buff, 84); UART_BUFF_GETC(buff, 85); UART_BUFF_GETC(buff, 86); UART_BUFF_GETC(buff, 87); UART_BUFF_GETC(buff, 88); UART_BUFF_GETC(buff, 89); UART_BUFF_GETC(buff, 90); UART_BUFF_GETC(buff, 91); UART_BUFF_GETC(buff, 92); UART_BUFF_GETC(buff, 93); UART_BUFF_GETC(buff, 94); UART_BUFF_GETC(buff, 95); UART_BUFF_GETC(buff, 96); UART_BUFF_GETC(buff, 97); UART_BUFF_GETC(buff, 98); UART_BUFF_GETC(buff, 99); UART_BUFF_GETC(buff, 100); UART_BUFF_GETC(buff, 101); UART_BUFF_GETC(buff, 102); UART_BUFF_GETC(buff, 103); UART_BUFF_GETC(buff, 104); UART_BUFF_GETC(buff, 105); UART_BUFF_GETC(buff, 106); UART_BUFF_GETC(buff, 107); UART_BUFF_GETC(buff, 108); UART_BUFF_GETC(buff, 109); UART_BUFF_GETC(buff, 110); UART_BUFF_GETC(buff, 111); UART_BUFF_GETC(buff, 112); UART_BUFF_GETC(buff, 113); UART_BUFF_GETC(buff, 114); UART_BUFF_GETC(buff, 115); UART_BUFF_GETC(buff, 116); UART_BUFF_GETC(buff, 117); UART_BUFF_GETC(buff, 118); UART_BUFF_GETC(buff, 119); UART_BUFF_GETC(buff, 120); UART_BUFF_GETC(buff, 121); UART_BUFF_GETC(buff, 122); UART_BUFF_GETC(buff, 123); UART_BUFF_GETC(buff, 124); UART_BUFF_GETC(buff, 125); UART_BUFF_GETC(buff, 126); UART_BUFF_GETC(buff, 127); for(i=0; i<128; i++){ uart_putc(buff[i]); buff[i] = 0; } }while(1); }
C
#include <stdio.h> void rec(int n) { printf("rec called with value = %d\n", n); if (n<=1) { return; } rec(n-2); rec(n-3); } int main() { printf("========\n"); rec(1); //1 printf("========\n"); rec(2); //2, 0, -1 printf("========\n"); rec(5); //5, 3, 1, 0, 2, 0, -1 printf("\n"); }
C
/* * Font search/cache functions for HTMLCSS library. * * https://github.com/michaelrsweet/htmlcss * * Copyright © 2019-2021 by Michael R Sweet. * * Licensed under Apache License v2.0. See the file "LICENSE" for more * information. */ /* * Include necessary headers... */ #include "font-private.h" #include "pool-private.h" #include <dirent.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> /* * Structure... */ typedef struct _hc_font_cache_s /* Binary font cache structure */ { char font_url[380], /* Filename */ font_family[128]; /* Family name */ unsigned char font_index, /* Index in font collection */ font_style; /* Style */ unsigned short font_weight; /* Weight */ } _hc_font_cache_t; struct _hc_font_info_s /* Font cache information */ { const char *font_url; /* Font filename/URL */ size_t font_index; /* Font number in collection */ hc_font_t *font; /* Loaded font */ const char *font_family; /* Family name */ hc_font_stretch_t font_stretch; /* Stretch/width (not used) */ hc_font_style_t font_style; /* Style (normal/italic/oblique) */ hc_font_variant_t font_variant; /* Variant (not used) */ hc_font_weight_t font_weight; /* Weight (100 - 900) */ }; /* * Local functions... */ static void hc_add_font(hc_pool_t *pool, hc_font_t *font, const char *url, int delete_it); static int hc_compare_info(_hc_font_info_t *a, _hc_font_info_t *b); static void hc_get_cname(char *cname, size_t cnamesize); static void hc_load_all_fonts(hc_pool_t *pool); static int hc_load_cache(hc_pool_t *pool, const char *cname, struct stat *cinfo); static time_t hc_load_fonts(hc_pool_t *pool, const char *d, int scanonly); static void hc_save_cache(hc_pool_t *pool, const char *cname); static void hc_sort_fonts(hc_pool_t *pool); /* * 'hcFontAddCached()' - Add a font to a memory pool cache. */ void hcFontAddCached(hc_pool_t *pool, /* I - Memory pool for cache */ hc_font_t *font, /* I - Font to add */ const char *url) /* I - URL for font */ { if (!pool || !font) return; hc_add_font(pool, font, url, 0); hc_sort_fonts(pool); } /* * 'hcFontFind()' - Find a font... */ hc_font_t * /* O - Matching font or `NULL` */ hcFontFindCached( hc_pool_t *pool, /* I - Memory pool for cache */ const char *family, /* I - Family name */ hc_font_stretch_t stretch, /* I - Stretching of font */ hc_font_style_t style, /* I - Style of font */ hc_font_variant_t variant, /* I - Variant of font */ hc_font_weight_t weight) /* I - Weight of font */ { size_t i; /* Looping var */ _hc_font_info_t *info, /* Current font info */ *best_info; /* Best match */ int result, /* Result of compare */ score, /* Current score */ best_score; /* Best score */ (void)stretch; (void)variant; if (!pool || !family) return (NULL); /* * Map generic font famlilies to real fonts... * * TODO: Provide config options for generic font families... */ if (!strcasecmp(family, "cursive")) family = "Zapfino"; else if (!strcasecmp(family, "fantasy")) family = "Comic Sans MS"; else if (!strcasecmp(family, "monospace")) family = "Courier New"; else if (!strcasecmp(family, "sans-serif")) #if _WIN32 family = "Arial"; #else family = "Helvetica"; #endif /* _WIN32 */ else if (!strcasecmp(family, "serif")) family = "Times New Roman"; if (weight == HC_FONT_WEIGHT_NORMAL) weight = HC_FONT_WEIGHT_400; else if (weight == HC_FONT_WEIGHT_BOLD) weight = HC_FONT_WEIGHT_700; else if (weight == HC_FONT_WEIGHT_BOLDER) weight = HC_FONT_WEIGHT_900; else if (weight == HC_FONT_WEIGHT_LIGHTER) weight = HC_FONT_WEIGHT_100; if (!pool->fonts_loaded) hc_load_all_fonts(pool); for (i = pool->font_index[tolower(*family & 255)], info = pool->fonts + i, best_info = NULL, best_score = 999999; i < pool->num_fonts; i ++, info ++) { if ((result = strcasecmp(family, info->font_family)) < 0) continue; else if (result > 0) break; if (info->font_weight > weight) score = (int)(info->font_weight - weight); else score = (int)(weight - info->font_weight); if ((info->font_style != HC_FONT_STYLE_NORMAL) != (style != HC_FONT_STYLE_NORMAL)) score ++; if (score < best_score) { best_score = score; best_info = info; if (score == 0) break; } } if (best_info) { if (!best_info->font) { hc_file_t *file = hcFileNewURL(pool, best_info->font_url, NULL); best_info->font = hcFontNew(pool, file, best_info->font_index); hcFileDelete(file); } return (best_info->font); } else return (NULL); } /* * 'hcFontGetCached()' - Get a cached font from a pool. */ hc_font_t * /* O - Font */ hcFontGetCached(hc_pool_t *pool, /* I - Memory pool */ size_t idx) /* I - Font number (0-based) */ { _hc_font_info_t *info; /* Font information */ if (!pool) return (NULL); if (!pool->fonts_loaded) hc_load_all_fonts(pool); if (idx >= pool->num_fonts) return (NULL); info = pool->fonts + idx; if (!info->font) { hc_file_t *file = hcFileNewURL(pool, info->font_url, NULL); /* Font file */ info->font = hcFontNew(pool, file, info->font_index); hcFileDelete(file); } return (info->font); } /* * 'hcFontGetCachedCount()' - Return the number of cached fonts. */ size_t /* O - Number of cached fonts */ hcFontGetCachedCount(hc_pool_t *pool) /* I - Memory pool */ { if (!pool) return (0); if (!pool->fonts_loaded) hc_load_all_fonts(pool); return (pool->num_fonts); } /* * '_hcPoolDeleteFonts()' - Free any cached fonts. */ void _hcPoolDeleteFonts(hc_pool_t *pool) /* I - Memory pool */ { if (pool->fonts) { size_t i; /* Looping var */ _hc_font_info_t *font; /* Current font */ for (i = pool->num_fonts, font = pool->fonts; i > 0; i --, font ++) hcFontDelete(font->font); } free(pool->fonts); pool->fonts = NULL; pool->alloc_fonts = 0; pool->num_fonts = 0; } /* * 'hc_add_font()' - Add a font to the cache, optionally deleting it. */ static void hc_add_font(hc_pool_t *pool, /* I - Memory pool */ hc_font_t *font, /* I - Font */ const char *url, /* I - Filename/URL */ int delete_it) /* I - Delete font after adding? */ { _hc_font_info_t *info; /* Font information */ if (!font->family) return; if (pool->num_fonts >= pool->alloc_fonts) { if ((info = realloc(pool->fonts, (pool->alloc_fonts + 16) * sizeof(_hc_font_info_t))) == NULL) return; pool->fonts = info; pool->alloc_fonts += 16; } info = pool->fonts + pool->num_fonts; pool->num_fonts ++; memset(info, 0, sizeof(_hc_font_info_t)); info->font_url = hcPoolGetString(pool, url); info->font_index = font->idx; info->font_family = font->family; // info->font_stretch = font->font_stretch; info->font_style = font->style; // info->font_variant = font->font_variant; info->font_weight = (hc_font_weight_t)font->weight; _HC_DEBUG("hc_add_font: %s \"%s\" S%d W%d\n", url, info->font_family, info->font_style, info->font_weight); if (delete_it) hcFontDelete(font); else info->font = font; } /* * 'hc_compare_info()' - Compare the information for two fonts. */ static int /* O - Result of comparison */ hc_compare_info(_hc_font_info_t *a, /* I - First font */ _hc_font_info_t *b) /* I - Second font */ { int ret = strcmp(a->font_family, b->font_family); if (!ret) ret = (int)a->font_style - (int)b->font_style; if (!ret) ret = (int)a->font_weight - (int)b->font_weight; return (ret); } /* * 'hc_get_cname()' - Get the name of the font cache file. */ static void hc_get_cname(char *cname, /* I - Cache filename */ size_t cnamesize) /* I - Size of buffer */ { const char *home = getenv("HOME"); /* Home directory */ #ifdef __APPLE__ if (home) { snprintf(cname, cnamesize, "%s/Library/Caches/org.msweet.htmlcss.dat", home); } else { strncpy(cname, "/private/tmp/org.msweet.htmlcss.dat", cnamesize - 1); cname[cnamesize - 1] = '\0'; } #elif _WIN32 if (home) { snprintf(cname, cnamesize, "%s/.htmlcss.dat", home); } else { strncpy(cname, "C:/WINDOWS/TEMP/.htmlcss.dat", cnamesize - 1); cname[cnamesize - 1] = '\0'; } #else if (home) { snprintf(cname, cnamesize, "%s/.htmlcss.dat", home); } else { strncpy(cname, "/tmp/.htmlcss.dat", cnamesize - 1); cname[cnamesize - 1] = '\0'; } #endif /* __APPLE__ */ } /* * 'hc_load_all_fonts()' - Load all fonts available to the user. */ static void hc_load_all_fonts(hc_pool_t *pool) /* I - Memory pool */ { int i, /* Looping var */ num_dirs = 0; /* Number of directories */ const char *dirs[5]; /* Directories */ char dname[1024]; /* Directory filename */ const char *home = getenv("HOME"); /* Home directory */ char cname[1024]; /* Cache filename */ struct stat cinfo; /* Cache file information */ int rescan = 0; /* Rescan fonts? */ /* * Build a list of font directories... */ #ifdef __APPLE__ dirs[num_dirs ++] = "/System/Library/Fonts"; dirs[num_dirs ++] = "/Library/Fonts"; if (home) { snprintf(dname, sizeof(dname), "%s/Library/Fonts", home); dirs[num_dirs ++] = dname; } #elif _WIN32 dirs[num_dirs ++] = "C:/Windows/Fonts"; /* TODO: fix me */ #else dirs[num_dirs ++] = "/usr/X11R6/lib/X11/fonts"; dirs[num_dirs ++] = "/usr/share/fonts"; dirs[num_dirs ++] = "/usr/local/share/fonts"; if (home) { snprintf(dname, sizeof(dname), "%s/.fonts", home); dirs[num_dirs ++] = dname; } #endif /* __APPLE__ */ /* * See if we need to re-scan the font directories... */ hc_get_cname(cname, sizeof(cname)); if (stat(cname, &cinfo)) { rescan = 1; } else { for (i = 0; i < num_dirs; i ++) { if (hc_load_fonts(pool, dirs[i], 1) > cinfo.st_mtime) { rescan = 1; break; } } } /* * Load the list of system fonts... */ if (!rescan && !hc_load_cache(pool, cname, &cinfo)) rescan = 1; if (rescan) { /* * Scan for fonts... */ for (i = 0; i < num_dirs; i ++) hc_load_fonts(pool, dirs[i], 0); /* * Save the cache... */ hc_save_cache(pool, cname); } hc_sort_fonts(pool); pool->fonts_loaded = 1; } /* * 'hc_load_cache()' - Load all fonts from the cache... */ static int /* O - 1 on success, 0 on failure */ hc_load_cache(hc_pool_t *pool, /* I - Memory pool */ const char *cname, /* I - Cache filename */ struct stat *cinfo) /* I - Cache information */ { int cfile; /* Cache file descriptor */ _hc_font_cache_t rec; /* File record */ _hc_font_info_t *font; /* Current font */ size_t i, /* Looping var */ num_fonts; /* Number of fonts */ if (((size_t)cinfo->st_size % sizeof(_hc_font_cache_t)) != 0) { _hcPoolError(pool, 0, "Invalid font cache file '%s'.", cname); return (0); } num_fonts = (size_t)cinfo->st_size / sizeof(_hc_font_cache_t); if (num_fonts == 0) return (0); if ((cfile = open(cname, O_RDONLY | O_EXCL)) < 0) { if (errno != ENOENT) _hcPoolError(pool, 0, "Unable to open font cache file '%s': %s", cname, strerror(errno)); return (0); } if ((pool->fonts = (_hc_font_info_t *)calloc(num_fonts, sizeof(_hc_font_info_t))) == NULL) { _hcPoolError(pool, 0, "Unable to allocate font cache: %s", strerror(errno)); close(cfile); return (0); } pool->alloc_fonts = pool->num_fonts = num_fonts; for (i = 0, font = pool->fonts; i < pool->num_fonts; i ++, font ++) { if (read(cfile, &rec, sizeof(rec)) != sizeof(rec)) { _hcPoolError(pool, 0, "Unable to load font cache from '%s': %s", cname, strerror(errno)); break; } // Ensure cache URL and family are nul-terminated, should the cache file // become corrupted or somebody tries to be "funny"... rec.font_url[sizeof(rec.font_url) - 1] = '\0'; rec.font_family[sizeof(rec.font_family) - 1] = '\0'; font->font_url = hcPoolGetString(pool, rec.font_url); font->font_index = (size_t)rec.font_index; font->font_family = hcPoolGetString(pool, rec.font_family); font->font_style = (hc_font_style_t)rec.font_style; font->font_weight = (hc_font_weight_t)rec.font_weight; } close(cfile); return (1); } /* * 'hc_load_fonts()' - Load fonts in a directory... */ static time_t /* O - Newest mtime */ hc_load_fonts(hc_pool_t *pool, /* I - Memory pool */ const char *d, /* I - Directory to load */ int scanonly) /* I - Just scan directory mtimes? */ { DIR *dir; /* Directory pointer */ struct dirent *dent; /* Directory entry */ char filename[1024], /* Filename */ *ext; /* Extension */ hc_file_t *file; /* File */ hc_font_t *font; /* Font */ struct stat info; /* Information about the current file */ time_t mtime = 0; /* Newest mtime */ if ((dir = opendir(d)) == NULL) return (mtime); while ((dent = readdir(dir)) != NULL) { if (dent->d_name[0] == '.') continue; snprintf(filename, sizeof(filename), "%s/%s", d, dent->d_name); if (lstat(filename, &info)) continue; if (info.st_mtime > mtime) mtime = info.st_mtime; if (S_ISDIR(info.st_mode)) { hc_load_fonts(pool, filename, scanonly); continue; } if (scanonly) continue; if ((ext = strrchr(dent->d_name, '.')) == NULL) continue; if (strcmp(ext, ".otc") && strcmp(ext, ".otf") && strcmp(ext, ".ttc") && strcmp(ext, ".ttf")) continue; file = hcFileNewURL(pool, filename, NULL); if ((font = hcFontNew(pool, file, 0)) != NULL) { if (!font->family || font->family[0] == '.') { /* * Ignore fonts starting with a "." since (on macOS at least) these are * hidden system fonts... */ hcFontDelete(font); } else { size_t num_fonts = hcFontGetNumFonts(font); /* Number of fonts */ hc_add_font(pool, font, filename, 1); if (num_fonts > 1) { size_t i; /* Looping var */ for (i = 1; i < num_fonts; i ++) { hcFileSeek(file, 0); if ((font = hcFontNew(pool, file, i)) != NULL) { if (font->family && font->family[0] != '.') hc_add_font(pool, font, filename, 1); else hcFontDelete(font); } } } } } hcFileDelete(file); } closedir(dir); return (mtime); } /* * 'hc_save_cache()' - Save all fonts to the cache... */ static void hc_save_cache(hc_pool_t *pool, /* I - Memory pool */ const char *cname) /* I - Cache filename */ { int cfile; /* Cache file descriptor */ _hc_font_cache_t rec; /* File record */ size_t i; /* Looping var */ _hc_font_info_t *font; /* Current font */ if ((cfile = open(cname, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, 0666)) < 0) { _hcPoolError(pool, 0, "Unable to create font cache file '%s': %s", cname, strerror(errno)); return; } for (i = 0, font = pool->fonts; i < pool->num_fonts; i ++, font ++) { memset(&rec, 0, sizeof(rec)); strncpy(rec.font_url, font->font_url, sizeof(rec.font_url) - 1); strncpy(rec.font_family, font->font_family, sizeof(rec.font_family) - 1); rec.font_index = (unsigned char)font->font_index; rec.font_style = (unsigned char)font->font_style; rec.font_weight = (unsigned short)font->font_weight; if (write(cfile, &rec, sizeof(rec)) != sizeof(rec)) { _hcPoolError(pool, 0, "Unable to save font cache to '%s': %s", cname, strerror(errno)); break; } } close(cfile); } /* * 'hc_sort_fonts()' - Sort and index the fonts in the cache. */ static void hc_sort_fonts(hc_pool_t *pool) /* I - Memory pool */ { size_t i; /* Looping var */ _hc_font_info_t *info; /* Current font info */ /* * First sort the fonts... */ if (pool->num_fonts > 1) qsort(pool->fonts, pool->num_fonts, sizeof(_hc_font_info_t), (_hc_compare_func_t)hc_compare_info); /* * Then index the fonts based on the initial character... */ for (i = 0; i < 256; i ++) pool->font_index[i] = pool->num_fonts; for (i = 0, info = pool->fonts; i < pool->num_fonts; i ++, info ++) { int ch = tolower(info->font_family[0] & 255); /* Initial character of font, lowercase */ if (i < pool->font_index[ch]) pool->font_index[ch] = i; } }
C
/*************************************** * EECS2031 – Lab3 isPanlindrom * * Author: Tingting, Yang * * Email: [email protected] * * EECS_num: ilove992 * * York Student #: 215120579 * ****************************************/ #include<stdio.h> #include <string.h> #define SIZE 30 char str[SIZE]; int isPalindrom(char []); int main(int argc, char* argv[]) { while (1) { scanf("%s",str); if(strcmp(str,"quit") == 0){break;} int i, len; for (i=0; str[i] != '\0'; i++); len = i; for (i=len-1; str[i] != '\0'; i--) { printf("%c",str[i]); } if( isPalindrom(str) == 1) {printf("\nIs a palindrom\n\n");} else {printf("\nIs not a palindrom\n\n");} } return 0; } int isPalindrom(char arr[]) { /*calculate length of str*/ int i, j, len; for (i=0; arr[i] != '\0'; i++); len = i; for (i=0, j=len-1; arr[i] != '\0'; i++, j-- ) { if (arr[i] != arr[j]) {return 0;} } return 1; }
C
/* @author Praveen Reddy * @date : 2021-10-06 * @desc Creating a Message Queue */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int main(){ int msqid; key_t key; key=ftok(".",'a'); //Passing current directory and proj_id='a' (Least significant 8 bits must be non zero). (Any existing file name can be passed and any integer can be passed). /* same pathname and same proj_id - ftok produces same key*/ msqid=msgget(key,IPC_CREAT|IPC_EXCL|0744); //If the msg queue exists already, msgget fails as IPC_EXCL flag is used if(msqid==-1){ perror("msgget"); exit(EXIT_FAILURE); } printf("key value = %d (Decimal)\n",key); printf("Key value = 0x%0x (Hexa Decimal)\n",key); printf("Message Queue Id = %d\n",msqid); return 0; }
C
#include "material-data.h" #include "matrix.h" #include "drying.h" #include "visco.h" #include <stdlib.h> #include <stdio.h> #define NTERMS 100 int main(int argc, char *argv[]) { double L = 1e-3, /* Length [m] */ t, RH; drydat cond; int npts = 51, /* Number of points to subdivide the thickness of the slab into */ i; /* Loop index */ vector *z, *Xdb, *Eb, *GradEb, *str, *u, *Pc; matrix *output; /* Print out a usage statement if needed */ if(argc != 5) { puts("Usage:"); puts("dry <T> <X0> <aw> <t>"); puts("aw: Final water activity to dry to."); puts("t: Time to output a profile for."); exit(0); } /* Store command line arguments */ cond.T = atof(argv[1]) + 237.15; cond.X0 = atof(argv[2]); RH = atof(argv[3]); t = atof(argv[4]); /* Calculate equilibrium moisture content and average diffusivity */ //Xe = OswinIsotherm(d, RH, T); cond.Xe = RH; cond.D = DiffCh10((cond.Xe+cond.X0)/2, cond.T); cond.L = L; cond.nterms = NTERMS; /* Make a bunch of vectors */ z = CreateVector(npts); Xdb = CreateVector(npts); Pc = CreateVector(npts); Eb = CreateVector(npts); GradEb = CreateVector(npts); str = CreateVector(npts); u = CreateVector(npts); /* Set up the domain by assigning the z value of each point to a slot in * the vector */ for(i=0; i<npts; i++) setvalV(z, i, L/npts * i); for(i=0; i<npts; i++) { /* Moisture content */ setvalV(Xdb, i, CrankEquationFx(valV(z, i), t, cond)); /* Binding energy */ setvalV(Eb, i, Esurf(valV(Xdb, i), cond.T)); /* Binding energy gradient */ setvalV(GradEb, i, GradEsurf(valV(z, i), t, cond)); /* Capillary Pressure */ setvalV(Pc, i, PoreP(valV(z, i), t, cond)); /* Strain */ setvalV(str, i, strainpc(valV(z, i), t, cond, &GradEsurf, &CreepZhu)); } /* Find the displacement at all points */ u = displacementV(str, L); PrintVector(Pc); /* Smash together the desired vectors and print the resulting matrix */ output = CatColVector(7, z, Xdb, Pc, Eb, GradEb, str, u); mtxprntfilehdr(output, "out.csv","x [m],Xdb [kg/kg db],Pc [Pa],Eb [J/m^3],GradEb [Pa/m^3],strain,u [m]\n"); return 0; }
C
#define USER_NAME_LEN 33 #define INTRO_LEN 1025 struct User{ char name[USER_NAME_LEN]; unsigned int age; char gender[7]; char introduction[INTRO_LEN]; };
C
#ifndef _CONSOLE_H #define _CONSOLE_H #include "type.h" typedef enum real_color { rc_black = 0, rc_blue = 1, rc_green = 2, rc_cyan = 3, rc_red = 4, rc_magenta = 5, rc_brown = 6, rc_light_grey = 7, rc_dark_grey = 8, rc_light_blue = 9, rc_light_green = 10, rc_light_cyan = 11, rc_light_red = 12, rc_light_magenta = 13, rc_light_brown = 14, // yellow rc_white = 15 } real_color_t; void console_clear(void); void console_putc_color(char c, real_color_t back, real_color_t fore); void console_write(char *cstr); void console_write_color(char *cstr, real_color_t back, real_color_t fore); void console_write_hex(uint32_t n, real_color_t back, real_color_t fore); void console_write_dec(uint32_t n, real_color_t back, real_color_t fore); #endif
C
// // Created by fff on 3/5/16. // #include "string.h" #include "stdio.h" #include "stdlib.h" #include "base64_util.h" #define MAX 0xFF /* global base64 original code table */ static char sta_code_table[64] = { 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',// 0 ~ 9 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',// 10 ~ 19 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',// 20 ~ 29 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',// 30 ~ 39 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',// 40 ~ 49 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',// 50 ~ 59 '8', '9', '+', '/' // 60 ~ 63 }; /* static function header */ static char find_pos(char ch); /** * find the index of the ch in the code table * @param ch */ char find_pos(char ch) { char * pt = (char *) strrchr(sta_code_table, ch); // find the last position in the code table return (char)(pt - sta_code_table); } /** * encode to base64 * @param src * @param des */ int base64_encode(char * src, char * des) { int prepare = 0; int ret_len = 0; int temp = 0; int tmp = 0; char changed[4]; int des_p = 0; int slen = (int) strlen(src); ret_len = slen / 3; //every 3 bytes is a unit temp = slen % 3; if(temp > 0) ret_len += 1; ret_len = ret_len * 4 + 1; memset(des, '\0', ret_len); while (tmp < slen) { temp = 0; prepare = 0; memset(changed, '\0', 4); while (temp < 3) { if(temp >= slen) break; prepare = ((prepare << 8) | (src[tmp] & 0xFF)); tmp++; temp++; } prepare = (prepare << ((3 - temp) * 8)); for(int i = 0; i < 4; i++) { if(temp < i) changed[i] = 0x40; else changed[i] = (char) ((prepare >> ((3 - i) * 6)) & 0x3F); des[des_p++] = sta_code_table[(int)changed[i]]; } } des[des_p] = '\0';//rear end return 0; } /** * decode to string * @param src * @param des */ int base64_decode(char * src, char * des) { int slen = (int) strlen(src); int ret_len = (slen / 4) * 3; int equal_count = 0; int tmp = 0; int temp = 0; char need[3]; int prepare = 0; for(int i = slen -1; i>= slen - 3; i--) if(src[i] == '=') equal_count += 1; switch (equal_count) { case 0: ret_len += 4; break; case 1: ret_len += 4; break; case 2: ret_len += 3; break; case 3: ret_len += 2; break; } memset(des, '\0', ret_len); int wlen = slen - equal_count; int des_pt = 0; while (tmp < wlen) { temp = 0; prepare = 0; memset(need, '\0', 3); while (temp < 4) { if(tmp >= wlen) break; prepare = (prepare << 6) | (find_pos(src[tmp])); temp++; tmp++; } prepare = prepare << ((4 - temp) * 6); for(int i = 0; i < 3; i++) { if(temp == i) break; des[des_pt++] = (char) ((prepare >> ((2 - i) * 8)) & 0xFF); } } des[des_pt] = '\0';//rear end return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> /*Ler 3 valores inteiros (considere que sero informados 3 valores distintos) e escrever a soma dos dois maiores;*/ main(){ int maior1=0, maior2=0, i, num[100]; for(i=1; i<=3; i++){ printf("numero: "); scanf("%d", &num[i]); if(num[i] > maior1){ maior2 = maior1; maior1 = num[i]; } else if(num[i] > maior2){ maior2 = num[i]; } } printf("Soma de %d e %d : %d", maior1, maior2, (maior1+maior2)); getchar(); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include <windows.h> void judg_prime(int num) { int n = 0; if (num <= 1) printf("%d\n", num); for (n = 2; n <= num - 1; n++) { if (num%n == 0) { printf("%d\n", num); return; } else { printf("%d\n", num); return; } } } int main() { int num = 0; printf("Ҫжϵ"); scanf("%d", &num); judg_prime(num); system("pause"); return 0; }
C
#include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <arpa/inet.h> #include "pcap.h" #include "services.h" #include "parse.h" static int ipv4_parse(pcap_record_t *prec, const char *pktdata, int pktlen); static int ipv6_parse(pcap_record_t *prec, const char *pktdata, int pktlen); static int udp_parse(pcap_record_t *prec, const char *pktdata, int pktlen); static int tcp_parse(pcap_record_t *prec, const char *pktdata, int pktlen); int parse_record(pcap_record_t *prec, const char *pktdata, int pktlen) { // number, time, framelen, caplen have been set uint16_t eth_type; /* type field of ethernet header */ char *ptr = (char *)pktdata; int k; /* initializing ... */ prec->protocol[0] = '\0'; prec->info[0] = '\0'; prec->v4_cast = UNICAST; /* initialized unicast */ prec->tcp_info.valid = 0; /* the least significant bit of the most significant byte of * the destination mac address is set when the address is a * multicase address. * broadcase address(ff:ff:ff:ff:ff:ff) is special case */ if (ptr[0] & 0x01 == 1) { for (k = 0; k < 6 && ptr[0] == 0xff; k++) ; if (k < 6) prec->v4_cast = MULTICAST; else prec->v4_cast = BROADCAST; } eth_type = ntohs( *(uint16_t *)(ptr + 12) ); //printf("eth_type = %d\n", eth_type); switch (eth_type) { case 0x0800: /* IPv4 */ strcat(prec->protocol, "IPv4"); ipv4_parse(prec, pktdata + 14, pktlen - 14); break; case 0x86dd: /* IPv6 */ strcat(prec->protocol, "IPv6"); ipv6_parse(prec, pktdata + 14, pktlen - 14); break; case 0x0806: /* ARP */ prec->version = -1; /* not ip packet */ strcat(prec->protocol, "ARP"); break; case 0x8035: /* RARP */ prec->version = -1; /* not ip packet */ strcat(prec->protocol, "RARP"); break; default: prec->version = -1; /* not ip packet */ break; } return 0; } static int ipv4_parse(pcap_record_t *prec, const char *pktdata, int pktlen) { char *ptr = (char *)pktdata; int protocol; int hsize; /* header size (byte) */ if (pktlen < 20) { ERR_LOG("size of IPv4 packet is less than 20"); strcat(prec->info, "Packet size limit during capture."); return -1; } hsize = *(uint8_t *)ptr & 0x0f; hsize *= 4; prec->version = 4; /* ipv4 */ prec->pktsize = ntohs( *(uint16_t *)(ptr + 2) ); protocol = *(uint8_t *)(ptr + 9); /* TCP, UDP, ICMP, IGMP ... */ prec->src_ip[0] = *(uint32_t *)(ptr + 12); prec->dst_ip[0] = *(uint32_t *)(ptr + 16); switch (protocol) { case 1: /* ICMP */ strcat(prec->protocol, ":ICMP"); break; case 2: /* IGMP */ strcat(prec->protocol, ":IGMP"); break; case 6: /* TCP */ strcat(prec->protocol, ":TCP"); tcp_parse(prec, pktdata + hsize, pktlen - hsize); break; case 8: /* EGP */ strcat(prec->protocol, ":EGP"); break; case 9: /* IGP */ strcat(prec->protocol, ":IGP"); break; case 17: /* UDP */ strcat(prec->protocol, ":UDP"); udp_parse(prec, pktdata + hsize, pktlen - hsize); break; case 41: /* IPv6 tunnel */ strcat(prec->protocol, ":IPv6"); break; case 89: /* OSPF */ strcat(prec->protocol, ":OSPF"); break; default: break; } return 0; } static int ipv6_parse(pcap_record_t *prec, const char *pktdata, int pktlen) { char *ptr = (char *)pktdata; int protocol; int hsize; prec->version = 6; prec->pktsize = ntohs( *(uint16_t *)(ptr + 4) ) + 40; /* payload length + basic header (40 bytes) */ protocol = *(uint8_t *)(ptr + 6); hsize = 40; memcpy( prec->src_ip, ptr + 8, 16 ); memcpy( prec->dst_ip, ptr + 24, 16 ); switch (protocol) { case 6: /* TCP */ strcat(prec->protocol, ":TCP"); tcp_parse(prec, pktdata + hsize, pktlen - hsize); break; case 17: /* UDP */ strcat(prec->protocol, ":UDP"); udp_parse(prec, pktdata + hsize, pktlen - hsize); break; default: break; } return 0; } static int udp_parse(pcap_record_t *prec, const char *pktdata, int pktlen) { char *ptr = (char *)pktdata; int k; if (pktlen < 4) { ERR_LOG("size of UDP packet is less than 8"); strcat(prec->info, "[Packet size limit during capture]"); return -1; } prec->src_port = ntohs( *(uint16_t *)ptr ); prec->dst_port = ntohs( *(uint16_t *)(ptr + 2) ); if ( (k = index_of_service(prec->src_port)) != -1 || (k = index_of_service(prec->dst_port)) != -1 ) { strcat(prec->protocol, ":"); strcat(prec->protocol, services[k].name); } sprintf(prec->info, "%u > %u", prec->src_port, prec->dst_port); return 0; } static int tcp_parse(pcap_record_t *prec, const char *pktdata, int pktlen) { char *ptr = (char *)pktdata; int k; uint32_t seq, ackseq; uint8_t urg, ack, psh, rst, syn, fin; uint8_t flags; uint16_t winsize; char buf[80]; if (pktlen < 4) { ERR_LOG("size of TCP packet is less than 4"); strcat(prec->info, "[Packet size limit during capture]"); return -1; } prec->src_port = ntohs( *(uint16_t *)ptr ); prec->dst_port = ntohs( *(uint16_t *)(ptr + 2) ); if ( (k = index_of_service(prec->src_port)) != -1 || (k = index_of_service(prec->dst_port)) != -1 ) { strcat(prec->protocol, ":"); strcat(prec->protocol, services[k].name); } sprintf(prec->info, "%u > %u", prec->src_port, prec->dst_port); if (pktlen < 16) { //ERR_LOG("size of TCP Packet is less than 16"); fprintf(stderr, "%d pktlen = %d\n", prec->number, pktlen); strcat(prec->info, "[Packet size limit during capture]"); return -1; } prec->tcp_info.valid = 1; prec->tcp_info.seq_no = ntohl( *(uint32_t *)(ptr + 4) ); prec->tcp_info.ack_no = ntohl( *(uint32_t *)(ptr + 8) ); flags = *(uint8_t *)(ptr + 13); prec->tcp_info.fin = flags & 0x01; prec->tcp_info.syn = (flags >> 1) & 0x01; prec->tcp_info.ack = (flags >> 4) & 0x01; winsize = ntohs( *(uint16_t *)(ptr + 14) ); strcat(prec->info, " ["); if ( flags & 0x10 ) { strcat(prec->info, " ACK"); } if ( flags & 0x08 ) { strcat(prec->info, " PSH"); } if ( flags & 0x04 ) { strcat(prec->info, " RST"); } if ( flags & 0x02 ) { strcat(prec->info, " SYN"); } if ( flags & 0x01 ) { strcat(prec->info, " FIN"); } strcat(prec->info, "] "); sprintf(buf, "Seq=%u Ack=%u Win=%hu", prec->tcp_info.seq_no, prec->tcp_info.ack_no, winsize); strcat(prec->info, buf); return 0; } static void ipv6addr2string(uint8_t *addr, char *ipstring) { uint16_t temp[8]; int i, j; int cnt, maxcnt, idx; char *ptr; memcpy(temp, addr, 16); for (i = 0; i < 8; i++) temp[i] = ntohs(temp[i]); maxcnt = cnt = 0; idx = -1; for (i = 0; i < 8; i++) { if (temp[i] == 0) cnt++; else { if (cnt > maxcnt) { maxcnt = cnt; idx = i - cnt; } cnt = 0; } } if (idx == -1) { if (cnt > 0) { /* all zeros */ ipstring[0] = ':'; ipstring[1] = ':'; ipstring[2] = '\0'; } else { /* all non-zero */ sprintf(ipstring, "%hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx", temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7] ); } } else { ipstring[0] = '\0'; ptr = ipstring; if (idx == 0) { *ptr++ = ':'; *ptr = '\0'; } else { for (i = 0; i < idx; i++) { j = sprintf(ptr, "%hx:", temp[i]); ptr += j; } } i = idx + maxcnt; if (i == 8) { *ptr++ = ':'; *ptr = '\0'; } else { for ( ; i < 8; i++) { j = sprintf(ptr, ":%hx", temp[i]); ptr += j; } } } } void write_to_file_csv(FILE *fp, pcap_record_t *prec) { char srcip[40]; char dstip[40]; char *ptr; int i, j; if (prec->version == 4) { ptr = (char *)(prec->src_ip); sprintf(srcip, "%hhu.%hhu.%hhu.%hhu", *(uint8_t*)ptr, *(uint8_t*)(ptr+1), *(uint8_t*)(ptr+2), *(uint8_t*)(ptr+3) ); ptr = (char *)(prec->dst_ip); sprintf(dstip, "%hhu.%hhu.%hhu.%hhu", *(uint8_t*)ptr, *(uint8_t*)(ptr+1), *(uint8_t*)(ptr+2), *(uint8_t*)(ptr+3) ); } else if (prec->version == 6) { ipv6addr2string( (uint8_t *)(prec->src_ip), srcip ); ipv6addr2string( (uint8_t *)(prec->dst_ip), dstip ); } else { /* empty string */ srcip[0] = '\0'; dstip[0] = '\0'; } /* (No., Time, Source IP, Source Port, Destination IP, Destination Port, Protocol, Length, Info) */ fprintf( fp, "%d,%u.%06u,%s,%d,%s,%d,%s,%d,%s\n", prec->number, prec->ts_sec, prec->ts_usec, srcip, prec->src_port, dstip, prec->dst_port, prec->protocol, prec->framelen, prec->info ); } void usage(char *progname) { printf("Usage: %s <pcap_file_path> <result_file_path>\n\n", progname); }
C
#include <stdio.h> void practice() { int *ptr; ptr = (int *) malloc( sizeof( int) ); printf("Value of ptr: [%d]\n", ptr); printf("Address of ptr: [%d]\n", &ptr); free(ptr); // release the memory } int main (int argc, char *argv []) { practice(); return 0; }
C
//prob 1:love ,life and universe #include <stdio.h> int main() { int pos=-1,i; int a[1250]; while(1) { scanf("%d",&a[++pos]); if(a[pos]==42) break; } for(i=0;i<=pos;i++) printf("%d\n",a[i]); return 0; }
C
#pragma once struct Rotator { public: /** Rotation around the right axis (around Y axis), Looking up and down (0=Straight Ahead, +Up, -Down) */ float Pitch; /** Rotation around the up axis (around Z axis), Running in circles 0=East, +North, -South. */ float Yaw; /** Rotation around the forward axis (around X axis), Tilting your head, 0=Straight, +Clockwise, -CCW. */ float Roll; public: /** A rotator of zero degrees on each axis. */ static const Rotator ZeroRotator; public: /** * Default constructor (no initialization). */ __forceinline Rotator() : Pitch(0.0f) , Yaw(0.0f) , Roll(0.0f) {} /** * Constructor * * @param InF Value to set all components to. */ explicit __forceinline Rotator(float InF); /** * Constructor. * * @param InPitch Pitch in degrees. * @param InYaw Yaw in degrees. * @param InRoll Roll in degrees. */ __forceinline Rotator(float InPitch, float InYaw, float InRoll); __forceinline Rotator operator+=(const Rotator& InRotator); /** * Convert a rotation into a unit vector facing in its direction. * * @return Rotation as a unit direction vector. */ struct Vector ToVector() const; }; __forceinline Rotator::Rotator(float InF) : Pitch(InF) , Yaw(InF) , Roll(InF) { } __forceinline Rotator::Rotator(float InPitch, float InYaw, float InRoll) : Pitch(InPitch) , Yaw(InYaw) , Roll(InRoll) { } __forceinline Rotator Rotator::operator+=(const Rotator& InRotator) { Pitch += InRotator.Pitch; Yaw += InRotator.Yaw; Roll += InRotator.Roll; return *this; }
C
#include "types.h" #include "stat.h" #include "fcntl.h" #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { char *os; os = s; while((*s++ = *t++) != 0) ; return os; } int strcmp(const char *p, const char *q) { while(*p && *p == *q) p++, q++; return (uchar)*p - (uchar)*q; } uint strlen(char *s) { int n; for(n = 0; s[n]; n++) ; return n; } int strnlen(const char *s, uint size) { int n; for (n = 0; size > 0 && *s != '\0'; s++, size--) n++; return n; } void* memset(void *dst, int c, uint n) { stosb(dst, c, n); return dst; } char* strchr(const char *s, char c) { for(; *s; s++) if(*s == c) return (char*)s; return 0; } char* gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; return buf; } int stat(char *n, struct stat *st) { int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; r = fstat(fd, st); close(fd); return r; } int atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') n = n*10 + *s++ - '0'; return n; } void* memmove(void *vdst, void *vsrc, int n) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) *dst++ = *src++; return vdst; } char* strcat(char *dst, const char *src) { char *ptr = dst + strlen(dst); while (*src) *ptr++ = *src++; *ptr = '\0'; return dst; } // inline function to swap two numbers static inline void swap(char *x, char *y) { char t = *x; *x = *y; *y = t; } // function to reverse buffer[i..j] static char* reverse(char *buffer, int i, int j) { while (i < j) swap(&buffer[i++], &buffer[j--]); return buffer; } // Iterative function to implement itoa() function in C char* itoa(int value, char* buffer, int base) { // invalid input if (base < 2 || base > 32) return buffer; // consider absolute value of number int n = value; if (n < 0) n *= (-1); int i = 0; while (n) { int r = n % base; if (r >= 10) buffer[i++] = 65 + (r - 10); else buffer[i++] = 48 + r; n = n / base; } // if number is 0 if (i == 0) buffer[i++] = '0'; // If base is 10 and value is negative, the resulting string // is preceded with a minus sign (-) // With any other base, value is always considered unsigned if (value < 0 && base == 10) buffer[i++] = '-'; buffer[i] = '\0'; // null terminate string // reverse the string and return it return reverse(buffer, 0, i - 1); }
C
#include "context.h" #include "stdio.h" #include "stdlib.h" #include "variable.h" #include "macros.h" #include "clause.h" #include "assignment_level.h" // Forward declarations ------------------------------------------------------- void mergeSort(size_t *arr, size_t l, size_t r, arraymap_t* variables); static int context_eval_clause(context_t* this, clause_t* clause); static void context_add_clause_to_unsat(context_t* this, clause_t* clause); static void context_add_false_clause(context_t* this, clause_t* clause); static void context_remove_clause_from_unsat(context_t* this, clause_t* clause); // Constructor ---------------------------------------------------------------- context_t* context_create() { context_t* ret = malloc(sizeof(context_t)); ret->formula = arraylist_create(); ret->conflicts = linkedlist_create(); ret->variables = arraymap_create(); ret->unsat = linkedlist_create(); ret->false_clauses = linkedlist_create(); ret->assignment_history = linkedlist_create(); ret->sorted_indices = NULL; ret->numVariables = 0; ret->unit_clauses = linkedlist_create(); return ret; } // Update state for variables within the clause; unsat(True/Negated)LiteralCounts // will change for every literal within static void context_update_clause_literal_purity_counts(context_t* this, clause_t* clause, int counter) { arrayList_t* literals = clause->literals; for (size_t j = 0; j < arraylist_size(literals); j++) { literal_t* a_literal = (literal_t*) arraylist_get(literals, j); size_t variable_index = abs(*a_literal); variable_t* a_variable = (variable_t*) arraymap_get(this->variables, variable_index); if (*a_literal > 0) { variable_set_unsat_true_literal_count(a_variable, a_variable->unsatTrueLiteralCount + counter); } else if (*a_literal < 0) { variable_set_unsat_negated_literal_count(a_variable, a_variable->unsatNegatedLiteralCount + counter); } } } // context_add_clause --------------------------------------------------------- static void context_add_clause_setup_dependencies(context_t* this, clause_t* new_clause) { // Link participating clauses in the variables arraymap_t* variables_map = this->variables; // arraymap<size_t, variable_t*> arrayList_t* clause_literals = new_clause->literals; // arraylist<literal_t*> for (unsigned i = 0; i < arraylist_size(clause_literals); i++) { literal_t* a_literal = (literal_t*) arraylist_get(clause_literals, i); size_t variable_index = abs(*a_literal); if (!arraymap_get(variables_map, variable_index)) { arraymap_put(variables_map, variable_index, variable_create()); } variable_t* a_variable_struct = (variable_t*) arraymap_get(variables_map, variable_index); variable_insert_clause(a_variable_struct, new_clause); } // Try to evaluate the clause int clause_eval = context_eval_clause(this, new_clause); // Add to unsat if necessary if (clause_eval == 0) { context_add_clause_to_unsat(this, new_clause); } // Add to false if necessary if (clause_eval == -1) { context_add_false_clause(this, new_clause); } // Update purity counts context_update_clause_literal_purity_counts(this, new_clause, 1); } void context_add_clause(context_t* this, clause_t* new_clause) { // Add to the formula arrayList_t* formula = this->formula; // arraylist<clause_t*> arraylist_insert(formula, new_clause); context_add_clause_setup_dependencies(this, new_clause); } void context_add_conflict_clause(context_t* this, clause_t* new_clause) { // Add to conflicts linkedlist_t* conflicts = this->conflicts; // linkedlist<clause_t*> linkedlist_add_last(conflicts, new_clause); context_add_clause_setup_dependencies(this, new_clause); } bool context_remove_first_conflict_clause(context_t* this) { linkedlist_t* conflicts = this->conflicts; // linkedlist<clause_t*> if (linkedlist_size(conflicts) == 0) { return false; } linkedlist_node_t* first_node = conflicts->head->next; clause_t* removal_clause = (clause_t*) first_node->value; // Remove from unsat if (removal_clause->participating_unsat) { context_remove_clause_from_unsat(this, removal_clause); } // Remove from false if (removal_clause->participating_false_clauses) { linkedlist_remove_node(this->false_clauses, removal_clause->participating_false_clauses); removal_clause->participating_false_clauses = NULL; } // Remove from unit clauses if (removal_clause->participating_unit_clause) { linkedlist_remove_node(this->unit_clauses, removal_clause->participating_unit_clause); removal_clause->participating_unit_clause = NULL; } // Remove links from referenced variables arraymap_t* variables_map = this->variables; // arraymap<size_t, variable_t*> linkedlist_t* variables_removal_nodes = removal_clause->variables_removal_nodes; // linkedlist<linkedlist_node<clause_t*>> arrayList_t* clause_literals = removal_clause->literals; // arraylist<literal_t*> linkedlist_node_t* curr = variables_removal_nodes->head->next; for (unsigned i = 0; i < arraylist_size(clause_literals); i++) { literal_t* a_literal = (literal_t*) arraylist_get(clause_literals, i); size_t variable_index = abs(*a_literal); variable_t* a_variable_struct = (variable_t*) arraymap_get(variables_map, variable_index); // Get the corresponding removal node for the variable linkedlist_node_t* next_removal = curr->value; // Remove from the variables linkedlist_remove_node(a_variable_struct->participatingClauses, next_removal); curr = curr->next; } // Remove from linkedlist linkedlist_remove_node(conflicts, first_node); // Free the clause clause_destroy(removal_clause, NULL); return true; } // context_set_variables ------------------------------------------------------ // Copies all the keys from variable (arraymap<literal, variable_t> into aux static void context_populate_sorted_indices(size_t key, void *UNUSED(value), void *aux) { // Local static variable to keep track of the index. // Doing it this way so that I don't need to make a struct to store it in aux. static size_t index = 0; size_t* aList = aux; aList[index++] = key; } // Finalizes the variables, and sorts them in decreasing order of the number of // clauses they participate in // After this call, no additional variables should be added to the context. // It is legal to add new clauses (typically conflict clauses) but they must not // contain any new variable void context_finalize_variables(context_t* this, size_t numVariables) { this->numVariables = numVariables; size_t* sortedIndices = calloc(sizeof(size_t), numVariables); arraymap_foreach_pair(this->variables, &context_populate_sorted_indices, sortedIndices); // Sorts the array based on the number of clauses in which each variable appears in // Descending order. mergeSort(sortedIndices, 0, numVariables-1, this->variables); this->sorted_indices = sortedIndices; } void context_print_formula(context_t* this) { arrayList_t* formula = this->formula; size_t num_clauses = arraylist_size(formula); for (size_t i = 0; i < num_clauses; i++) { arraylist_print_all(((clause_t*) arraylist_get(formula, i))->literals); } } static void context_destroy_variables(size_t UNUSED(key), void* value, void* UNUSED(aux)) { variable_t* var = (variable_t*) value; variable_destroy(var); } static void assignment_history_destroyer_func(linkedlist_node_t* node, void* UNUSED(aux)) { assignment_level_t* value = node->value; assignment_level_destroy(value); } void context_destroy(context_t* this) { arraymap_destroy(this->variables, &context_destroy_variables, NULL); arraylist_destroy(this->formula, &clause_destroy, NULL); // Destroy the assignment_history linkedlist_t* assignment_history = this->assignment_history; // linkedlist<assignment_level_t*> linkedlist_destroy(assignment_history, assignment_history_destroyer_func, NULL); linkedlist_destroy(this->false_clauses, NULL, NULL); linkedlist_destroy(this->unsat, NULL, NULL); for (linkedlist_node_t* curr = this->conflicts->head->next; curr != this->conflicts->tail; curr = curr->next) { clause_t* a_clause = curr->value; clause_destroy(a_clause, NULL); } linkedlist_destroy(this->conflicts, NULL, NULL); linkedlist_destroy(this->unit_clauses, NULL, NULL); free(this->sorted_indices); free(this); } // context_assign_variable_value ---------------------------------------------- // Evaluates a single clause // // Return: // -1 The clause is False // 0 The clause is unknown // +1 The clause is True static int context_eval_clause(context_t* this, clause_t* clause) { arraymap_t* variables = this->variables; int unassigned_literals = 0; for (size_t i = 0; i < arraylist_size(clause->literals); i++) { literal_t* literal = (literal_t*) clause->literals->array[i]; variable_t* variable = (variable_t*) arraymap_get(variables, abs(*literal)); int currAssignment = variable->currentAssignment; int literal_eval = *literal * currAssignment; if (literal_eval < 0) { // Got a false literal // do nothing } else if (literal_eval == 0) { // Got an unassigned literal // Increment number of unassigned literals in this clause clause->an_unassigned_literal = literal; unassigned_literals++; } else { // Got a positive literal // The clause is true immediately if (clause->participating_unit_clause) { linkedlist_remove_node(this->unit_clauses, clause->participating_unit_clause); clause->participating_unit_clause = NULL; } return 1; } } // Update the unit clause: add to the linked list, or remove from it if (unassigned_literals == 1) { if (!clause->participating_unit_clause) { linkedlist_node_t* new_node = linkedlist_add_last(this->unit_clauses, clause); clause->participating_unit_clause = new_node; } } if (unassigned_literals != 1) { if (clause->participating_unit_clause) { linkedlist_remove_node(this->unit_clauses, clause->participating_unit_clause); clause->participating_unit_clause = NULL; } } if (unassigned_literals > 0) { // There were no positive literals, but some of them don't have an assignment return 0; } else { // Everything in this clause has an assignment, but there were no positive literals return -1; } } static void context_add_clause_to_unsat(context_t* this, clause_t* clause) { // Check if the clause is already in there if (clause->participating_unsat) { LOG_DEBUG("context_add_clause_to_unsat: attempting to add a clause to unsat list, but the clause's participating unsat field is not NULL, so it's probably already in the unsat list. Aborting...\n"); LOG_DEBUG("The Clause that was being added is:\n"); clause_print(clause); abort(); } linkedlist_t* unsat = this->unsat; // linkedlist<clause_t*> linkedlist_node_t* unsat_node = linkedlist_add_last(unsat, clause); clause->participating_unsat = unsat_node; } static void context_remove_clause_from_unsat(context_t* this, clause_t* clause) { LOG_DEBUG("context_remove_clause_from_unsat: removing following clause\n"); clause_print(clause); if (!clause->participating_unsat) { LOG_DEBUG("this clause was already removed\n"); return; } context_update_clause_literal_purity_counts(this, clause, -1); linkedlist_remove_node(this->unsat, clause->participating_unsat); clause->participating_unsat = NULL; } static void context_add_false_clause(context_t* this, clause_t* clause) { LOG_DEBUG("\nAdding false clause:\n"); clause_print(clause); linkedlist_node_t* false_clause_node = linkedlist_add_last(this->false_clauses, clause); if (clause->participating_false_clauses) { LOG_FATAL("This clause already participates in false\n"); } clause->participating_false_clauses = false_clause_node; } // Assigns a value to a variable // Updates the variables map, unsat and false clauses lists and links void context_assign_variable_value(context_t* this, size_t variable_index, bool new_value) { variable_t* variable = (variable_t*) arraymap_get(this->variables, variable_index); // Initially variables are self-deduced (arbitrary decision) unless a call // to add_deduced_assignment is made linkedlist_add_last(variable->deduced_from, (void*) variable_index); variable_set_value(variable, new_value); linkedlist_t* participatingClauses = variable->participatingClauses; for (linkedlist_node_t* curr = participatingClauses->head->next; curr != participatingClauses->tail; curr = curr->next) { clause_t* clause = curr->value; int eval = context_eval_clause(this, clause); if (eval > 0) { context_remove_clause_from_unsat(this, clause); } else if (eval < 0) { context_remove_clause_from_unsat(this, clause); context_add_false_clause(this, clause); } } } // context_unassign_variable -------------------------------------------------- void context_unassign_variable(context_t* this, size_t variable_index) { // update assignment value to 0 in the variable map arraymap_t* variables = this->variables; // {unsigned -> variable_t*} variable_t* the_variable = (variable_t*) arraymap_get(variables, variable_index); linkedlist_destroy(the_variable->deduced_from, NULL, NULL); the_variable->deduced_from = linkedlist_create(); // Reset the deduced_from field variable_set_raw_value(the_variable, 0); // 0 is the undefined value // get the participating clauses of the variable linkedlist_t* participating_clauses = the_variable->participatingClauses; // arraylist<clause_t*> for (linkedlist_node_t* curr = participating_clauses->head->next; curr != participating_clauses->tail; curr = curr->next) { clause_t* a_clause = curr->value; // if participating_false_clauses is not NULL, remove the clause from the false_clauses // because if it's in the false clauses, the clause is currently false, but removing // an assignment will make it undefined linkedlist_node_t* participating_false_clause_node = a_clause->participating_false_clauses; if (participating_false_clause_node) { LOG_DEBUG("\nRemoving false clause:\n"); clause_print(participating_false_clause_node->value); linkedlist_remove_node(this->false_clauses, participating_false_clause_node); a_clause->participating_false_clauses = NULL; } // if participating_unsat is NULL, add this clause to the unsat // because this means the clause was well-defined (either T or F), but now // undoing a variable assignment makes it undefined again linkedlist_node_t* participating_unsat = a_clause->participating_unsat; int clause_eval = context_eval_clause(this, a_clause); if (!participating_unsat && (clause_eval == 0)) { context_add_clause_to_unsat(this, a_clause); context_update_clause_literal_purity_counts(this, a_clause, 1); } } } // context_run_bcp ------------------------------------------------------------ static void add_deduced_assignment(context_t* this, int new_assignment, clause_t* current_clause) { // Get current assignment level linkedlist_t* assignment_history = this->assignment_history; // linkedlist<assignment_level_t*> linkedlist_node_t* last_assignment_node = assignment_history->tail->prev; if (!last_assignment_node || (last_assignment_node == assignment_history->head)) { LOG_FATAL("add_deduced_assignment: Could not find a valid assignment node to operate on\n"); } assignment_level_t* the_assignment_level = (assignment_level_t*) last_assignment_node->value; // Add to the assignment level's deduced assignments assignment_level_add_deduced_assignment(the_assignment_level, new_assignment); // Get the primary assignment of the current level and set as variable's deduction parent unsigned current_var_index = abs(new_assignment); arraymap_t* variables_map = this->variables; // arraymap<size_t, variable_t*> variable_t* current_var_struct = arraymap_get(variables_map, current_var_index); // Add the deduced_from links if (!current_clause) { // If current clause is NULL, then the variable is self-deduced and does not depend // on other deductions linkedlist_add_last(current_var_struct->deduced_from, (void*) (unsigned long) abs(the_assignment_level->assignment)); } else { // If clauses are not null, then the assignment is deduced from the other variables // in the clause arrayList_t* current_clause_literals = current_clause->literals; // arraylist<literal_t*> for (unsigned i = 0; i < arraylist_size(current_clause_literals); i++) { literal_t* a_lit_ptr = arraylist_get(current_clause_literals, i); size_t a_var_idx = abs(*a_lit_ptr); if (abs(new_assignment) != abs(a_var_idx)) { linkedlist_add_last(current_var_struct->deduced_from, (void*) a_var_idx); } } } } // Returns true if BCP has made some progress // Returns false if BCP could not find any singleton-clause to work on static bool context_run_bcp_once(context_t* this) { // get unsatisfied clauses linkedlist_t* unit_unsat = this->unit_clauses; // linkedlist<clause_t*> if (linkedlist_size(unit_unsat) == 0) { return false; } clause_t* a_clause = (clause_t*) unit_unsat->head->next->value; // Found a variable on which to do BCP literal_t* literal_ptr = a_clause->an_unassigned_literal; literal_t literal_value = *literal_ptr; // Get variable index size_t variable_index = abs(literal_value); bool new_assignment; if (literal_value > 0) { // Assign true new_assignment = true; } else { // Assign false new_assignment = false; } // Make the assignment and update the assignment history LOG_DEBUG("BCP deciding to assign %lu to be %d\n", variable_index, new_assignment); context_assign_variable_value(this, variable_index, new_assignment); add_deduced_assignment(this, literal_value, a_clause); return true; } // Returns an evaluation value of the formula int context_run_bcp(context_t* this, unsigned* iterations) { while (true) { int formula_value = context_evaluate_formula(this); LOG_DEBUG("context_run_bcp: Formula is currently true/false? %d\n", formula_value); if (formula_value == 0) { bool res = context_run_bcp_once(this); if (!res) { // BCP did not make any progress, return an evaluation return context_evaluate_formula(this); } // Otherwise, continue looping *iterations += 1; } else { // We already know if formula is true or false, return return formula_value; } } } // Returns true if PLP has made some progress // Returns false if PLP could not find any pure literals to work on static bool context_run_plp_once(context_t* this) { arraymap_t* variables = this->variables; for (size_t i = 0; i < arraylist_size(variables->arraylist); i++) { void* value = arraylist_get(variables->arraylist, i); if (!value) { continue; } variable_t* variable = (variable_t*) value; if (variable->currentAssignment) { // Variable is assigned, nothing to do. continue; } int var_purity = variable_get_purity(variable); if (var_purity != 0) { if (var_purity > 0) { // Decide that the variable must be set to true, PLP makes progress context_assign_variable_value(this, i, true); add_deduced_assignment(this, (int) i, NULL); } else { // Decide that the variable must be set to false, PLP makes progress context_assign_variable_value(this, i, false); add_deduced_assignment(this, -(int) i, NULL); } return true; } } // No pure literals found, PLP makes no progress return false; } // Returns an evaluation value of the formula int context_run_plp(context_t* this) { while(true) { int formula_value = context_evaluate_formula(this); LOG_DEBUG("context_run_plp: Formula is currently true/false? %d\n", formula_value); if (formula_value == 0) { bool res = context_run_plp_once(this); if (!res) { // PLP made no progress, return an evaluation return context_evaluate_formula(this); } // Otherwise, continue looping } else { // We already know formula result, return return formula_value; } } } // context_print_current_state ------------------------------------------------ void context_print_current_state_variable_printer(size_t key, void* value, void* UNUSED(aux)) { if (ENABLE_DEBUG) { variable_t* the_variable = (variable_t*) value; LOG_DEBUG("\t%lu:\t%d\n", key, the_variable->currentAssignment); } } // clause_list is a linkedlist_t<clause_t*> void context_print_current_state_print_clause_list(linkedlist_t* clause_list) { if (ENABLE_DEBUG) { size_t curr_index = 0; for (linkedlist_node_t* curr = clause_list->head->next; curr != clause_list->tail; curr = curr->next) { clause_t* elem = (clause_t*) curr->value; arrayList_t* clause_literals = elem->literals; LOG_DEBUG("Clause %lu: ", curr_index); for (size_t j = 0; j < arraylist_size(clause_literals); j++) { literal_t* a_literal = (literal_t*) arraylist_get(clause_literals, j); LOG_DEBUG("%d\t", *a_literal); } LOG_DEBUG("\n"); curr_index++; } } } void context_print_current_state(context_t* this) { if (ENABLE_DEBUG) { // Clauses of the formula LOG_DEBUG("\nFormula clauses:\n"); arrayList_t* formula = this->formula; for (size_t i = 0; i < arraylist_size(formula); i++) { clause_t* elem = (clause_t*) arraylist_get(formula, i); // Print the literals LOG_DEBUG("Clause %lu = ", i); arrayList_t* clause_literals = elem->literals; for (size_t j = 0; j < arraylist_size(clause_literals); j++) { literal_t* a_literal = (literal_t*) arraylist_get(clause_literals, j); LOG_DEBUG("%d\t", *a_literal); } LOG_DEBUG("\n"); } // Variables map LOG_DEBUG("\nVariable map:\n"); arraymap_t* variables = this->variables; if (!variables) { LOG_DEBUG("is NULL\n"); } else { arraymap_foreach_pair(variables, context_print_current_state_variable_printer, NULL); } // Unsatisfied clauses LOG_DEBUG("\nUnsat clauses:\n"); context_print_current_state_print_clause_list(this->unsat); // False clauses LOG_DEBUG("\nFalse clauses:\n"); context_print_current_state_print_clause_list(this->false_clauses); LOG_DEBUG("\nSorted indices:\n"); for(size_t i = 0; i < arraylist_size(this->variables->arraylist) - 1; i++) { LOG_DEBUG("Elem %ld -> literal %ld\n", i, this->sorted_indices[i]); } LOG_DEBUG("\n"); } } void context_print_result_variables(const context_t* ctx) { arrayList_t* variableArray = ctx->variables->arraylist; const size_t listSize = arraylist_size(variableArray); for(size_t i = 0; i < listSize; i++) { variable_t* var = (variable_t*) arraylist_get(variableArray, i); if(!var) { continue; } // Since this variable is assigned to 0 we could assign it to either -1 or 1 // let's just assign it to 1 int assignment = !var->currentAssignment ? 1 : var->currentAssignment; printf("%d", assignment * (int) i); if(i != (listSize - 1)) { printf(" "); } } printf("\n"); } // context_evaluate_formula --------------------------------------------------- // Returns: // -1 False // 0 Unknown // +1 True int context_evaluate_formula(context_t* this) { // Check false_clauses list linkedlist_t* false_clauses = this->false_clauses; // linkedlist<clause_t*> if (linkedlist_size(false_clauses) > 0) { return -1; } // Check unsat list linkedlist_t* unsat = this->unsat; // linkedlist<clause_t*> if (linkedlist_size(unsat) == 0) { return 1; } // Otherwise we don't know enough about the formula yet return 0; } // context_apply_new_decision_level ----------------------------------------------------- // The decision step can make a variable decision assignment. // We create a new decision history level // Does NOT actually assign the new variable void context_apply_new_decision_level(context_t* this, size_t variable_index, bool new_value) { // Update the assignment history with a new node int assignment_value = new_value ? variable_index : -variable_index; linkedlist_t* assignment_history = this->assignment_history; // linkedlist<assignment_level_t*> assignment_level_t* new_level = assignment_level_create(linkedlist_size(assignment_history), assignment_value); linkedlist_add_last(assignment_history, new_level); } // context_get_last_assignment_level ------------------------------------------ assignment_level_t* context_get_last_assignment_level(context_t* this) { // Get the assignment history linkedlist_t* assignment_history = this->assignment_history; // linkedlist<assignment_level_t*> // Return null if it's empty if (linkedlist_size(assignment_history) == 0) { return NULL; } // Get last element linkedlist_node_t* assignment_history_last_node = assignment_history->tail->prev; assignment_level_t* last_assignment_level = (assignment_level_t*) assignment_history_last_node->value; return last_assignment_level; } // context_remove_last_assignment_level --------------------------------------- // Removes the last assignment level // Does not free the assignment_level assignment_level_t* context_remove_last_assignment_level(context_t* this) { linkedlist_t* assignment_history = this->assignment_history; // linkedlist<assignment_level_t*> assignment_level_t* last_assignment_level = (assignment_level_t*) linkedlist_remove_last(assignment_history); return last_assignment_level; } // context_get_first_variable_index ------------------------------------------- // Returns the first variable index in the mapping // Returns 0 if variable map contains nothing size_t context_get_first_variable_index(context_t* this) { // The sorted_indices array is full of 0s if empty, so if there is no first variable, 0 will be returned. return this->sorted_indices[0]; } // context_get_next_variable_index -------------------------------------------- // Maybe improvement: store the last index and then start from there, // if that yields nothing start from 0? static size_t context_find_next_sorted_index(context_t* this) { static size_t previousIndex = 0; // Store the index of the last variable we decided and start from there for(size_t i = previousIndex; i < this->numVariables; i++) { const size_t key = this->sorted_indices[i]; const variable_t* next_variable_data = (variable_t*) arraymap_get(this->variables, key); // Somehow the key points to an invalid variable (?) if(!next_variable_data) { LOG_FATAL("%s:%lu: key %lu pointed to a NULL variable!\n", __FILE__, __LINE__, key); break; } if(!next_variable_data->currentAssignment) { previousIndex = i; return key; } } // We couldn't find anything starting from the previous index, so we just start from 0 for(size_t i = 0; i < previousIndex; i++) { const size_t key = this->sorted_indices[i]; const variable_t* next_variable_data = (variable_t*) arraymap_get(this->variables, key); // Somehow the key points to an invalid variable (?) if(!next_variable_data) { LOG_FATAL("%s:%lu: key %lu pointed to a NULL variable!\n", __FILE__, __LINE__, key); break; } if(!next_variable_data->currentAssignment) { previousIndex = i; return key; } } // Nothing is left to be assigned return 0; } size_t context_get_next_unassigned_variable(context_t* this) { return context_find_next_sorted_index(this); } static void merge(size_t* arr, size_t l, size_t m, size_t r, arraymap_t* variables) { size_t i, j, k; const size_t n1 = m - l + 1; // How big is the left part of the array? const size_t n2 = r - m; // and the right? size_t *L = malloc(n1 * sizeof(size_t)), *R = malloc(sizeof(size_t)*n2); // TEMP /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; while (i < n1 && j < n2) { // -1 is needed because of find_next_entry finding the next entry and not the closest one const arraymap_pair_t v1 = arraymap_find_next_entry(variables, L[i]-1); const arraymap_pair_t v2 = arraymap_find_next_entry(variables, R[j]-1); // The unchecked cast is possible because of sorted_indexes being built from variable, // therefore if a literal is there it must exist const size_t length1 = linkedlist_size(((variable_t*)v1.v)->participatingClauses); const size_t length2 = linkedlist_size(((variable_t*)v2.v)->participatingClauses); // Descending if (length1 >= length2) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } // Same for R while (j < n2) { arr[k] = R[j]; j++; k++; } free(L); free(R); } void mergeSort(size_t *arr, size_t l, size_t r, arraymap_t* variables) { if (l < r) { size_t m = l+(r-l)/2; mergeSort(arr, l, m, variables); mergeSort(arr, m+1, r, variables); merge(arr, l, m, r, variables); } } // context_get_clauses_count -------------------------------------------------- unsigned context_get_conflicts_count(context_t* this) { return linkedlist_size(this->conflicts); } // context_get_first_false_clause --------------------------------------------- clause_t* context_get_first_false_clause(context_t* this) { linkedlist_t* false_clauses = this->false_clauses; // linkedlist<clause_t*> if (linkedlist_size(false_clauses) == 0) { LOG_DEBUG("context_get_first_false_clause: False clauses list is empty\n"); abort(); } return (clause_t*) false_clauses->head->next->value; } // context_get_primary_assignment_of ------------------------------------------ // acc is linkedlist_t<int> is the result accumulator void context_get_primary_assignment_of(context_t* this, unsigned query_variable_index, linkedlist_t* acc) { arraymap_t* variables = this->variables; // arraymap<size_t, variable_t*> variable_t* query_variable = arraymap_get(variables, query_variable_index); if (!query_variable) { LOG_DEBUG("context_get_primary_assignment_of: Could not find variable %u from variables map\n", query_variable_index); abort(); } linkedlist_t* deduction_parent_variables = query_variable->deduced_from; // linkedlist<size_t> if (linkedlist_size(deduction_parent_variables) == 0) { LOG_DEBUG("context_get_primary_assignment_of: The deduced_from of variable %u is length 0. This should never happen because even if the variable is an arbitrary assignment it should be deduced from itself.\n", query_variable_index); abort(); } // For each of the parent links, add to the result if it's a primary assignment, otherwise // go up the tree recursively for (linkedlist_node_t* curr = deduction_parent_variables->head->next; curr != deduction_parent_variables->tail; curr = curr->next) { size_t a_parent_idx = (size_t) curr->value; variable_t* parent_variable = arraymap_get(variables, a_parent_idx); int parent_value = parent_variable->currentAssignment; if (parent_value == 0) { LOG_DEBUG("context_get_primary_assignment_of: The deduction parent is currently unassigned. But a parent of a deducted variable must have an assignment in order to be the parent. Query variable = [%u], Parent variable = [%lu]\n", query_variable_index, a_parent_idx); abort(); } // If the parent index is the same as the query variable, we have found a root assignment and // we add it to the accumulator if (a_parent_idx == query_variable_index) { int result = parent_value > 0 ? a_parent_idx : -a_parent_idx; linkedlist_add_last(acc, (void*) (long) result); return; } else { // Otherwise we recursively call and find parents context_get_primary_assignment_of(this, a_parent_idx, acc); return; } } } // context_initialize_variable ------------------------------------------------ void context_initialize_variable(context_t* this, size_t var_index) { arraymap_t* variables_map = this->variables; // arraymap<size_t, variable_t*> if (!arraymap_get(variables_map, var_index)) { arraymap_put(variables_map, var_index, variable_create()); } }
C
/** * \file * i2c driver * \author * Nguyen Van Hai <[email protected]> */ #include "i2c.h" /* --EV5 */ #define I2C_EVENT_MASTER_MODE_SELECT ((uint32_t)0x00030001) /* BUSY, MSL and SB flag */ /* --EV6 */ #define I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED ((uint32_t)0x00070082) /* BUSY, MSL, ADDR, TXE and TRA flags */ #define I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED ((uint32_t)0x00030002) /* BUSY, MSL and ADDR flags */ /* --EV9 */ #define I2C_EVENT_MASTER_MODE_ADDRESS10 ((uint32_t)0x00030008) /* BUSY, MSL and ADD10 flags */ /* Master RECEIVER mode -----------------------------*/ /* --EV7 */ #define I2C_EVENT_MASTER_BYTE_RECEIVED ((uint32_t)0x00030040) /* BUSY, MSL and RXNE flags */ /* Master TRANSMITTER mode --------------------------*/ /* --EV8 */ #define I2C_EVENT_MASTER_BYTE_TRANSMITTING ((uint32_t)0x00070080) /* TRA, BUSY, MSL, TXE flags */ /* --EV8_2 */ #define I2C_EVENT_MASTER_BYTE_TRANSMITTED ((uint32_t)0x00070084) /* TRA, BUSY, MSL, TXE and BTF flags */ #define FLAG_Mask ((uint32_t)0x00FFFFFF) void I2C_Init(uint32_t pclk1) { uint32_t result; /* Clear frequency FREQ[5:0] bits */ I2C1->CR2 &= ~I2C_CR2_FREQ; /* Set frequency bits depending on pclk1 value */ I2C1->CR2 |= (uint16_t)(pclk1 / 1000000); /* Disable the selected I2C peripheral to configure TRISE */ I2C1->CR1 &= ~I2C_CR1_PE; /* Clear F/S, DUTY and CCR[11:0] bits */ I2C1->TRISE = (pclk1 / 1000000) + 1; /* Configure speed in standard mode 100kHz*/ result = (uint16_t)(pclk1 / 100000 / 2); I2C1->CCR = result; /* Enable the selected I2C peripheral */ I2C1->CR1 |= I2C_CR1_PE; /* Clear ACK, SMBTYPE and SMBUS bits */ I2C1->CR1 |= (uint16_t)(I2C_CR1_ACK); /* I2C1 Enable */ I2C1->CR1 = I2C_CR1_PE; } uint32_t I2C_CheckStatus(uint32_t event) { uint32_t temp; temp = I2C1->SR2; temp <<= 16; temp |= I2C1->SR1; temp &= FLAG_Mask; if((temp & event) == event) return 0; else return 1; } uint8_t I2C_ReadByte(uint8_t slaveAddr,uint8_t dataAddr) { uint32_t I2C_timeOut = 10000000; uint8_t res; /* Disable the acknowledgement */ I2C1->CR1 &= ~I2C_CR1_ACK; /* Generate a START condition */ I2C1->CR1 |= I2C_CR1_START; /* Test on I2C1 EV5 and clear it */ while ((I2C1->SR1&0x0001) != 0x0001) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Send slave address for write */ I2C1->DR = slaveAddr & 0xfe; /* Test on I2C1 EV6 and clear it */ while ((I2C1->SR1 &0x0002) != 0x0002) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Clear ADDR flag by reading SR2 register */ res = I2C1->SR2; /*Send data*/ I2C1->DR = dataAddr; /* Test on I2C1 EV8 and clear it */ while ((I2C1->SR1 & 0x00004) != 0x000004); { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Generate a START condition */ I2C1->CR1 |= I2C_CR1_START; /* Test on I2C1 EV5 and clear it */ while ((I2C1->SR1&0x0001) != 0x0001) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Send slave address for write */ I2C1->DR = slaveAddr | I2C_OAR1_ADD0; /* Test on I2C1 EV6 and clear it */ while ((I2C1->SR1&0x0002) != 0x0002) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } I2C1->CR1 &= ~I2C_CR1_ACK; res = I2C1->SR2; /* Send I2C1 STOP Condition */ I2C1->CR1 |= I2C_CR1_STOP; /* Wait until a data is received in DR register (RXNE = 1) EV7 */ while ((I2C1->SR1 & 0x00040) != 0x000040); { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } res = (uint8_t)I2C1->DR; /* Make sure that the STOP bit is cleared by Hardware before CR1 write access */ while ((I2C1->CR1&0x200) == 0x200); /* Enable Acknowledgement to be ready for another reception */ I2C1->CR1 |= I2C_CR1_ACK; return res; } uint8_t I2C_SendByte(uint8_t addr,uint8_t data) { uint32_t I2C_timeOut = 10000000,temp; /* Disable the acknowledgement */ I2C1->CR1 &= ~I2C_CR1_ACK; /* Generate a START condition */ I2C1->CR1 |= I2C_CR1_START; /* Test on I2C1 EV5 and clear it */ while ((I2C1->SR1&0x0001) != 0x0001) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } I2C1->DR = addr & 0xfe; /* Send slave address for write */ /* Test on I2C1 EV6 and clear it */ while ((I2C1->SR1 &0x0002) != 0x0002) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Clear ADDR flag by reading SR2 register */ temp = I2C1->SR2; I2C1->DR = data; /* EV8_2: Wait until BTF is set before programming the STOP */ while ((I2C1->SR1 & 0x00004) != 0x000004) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Send I2C1 STOP Condition */ I2C1->CR1 |= I2C_CR1_STOP; /* Make sure that the STOP bit is cleared by Hardware */ while ((I2C1->CR1&0x200) == 0x200) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } return 0; } // uint8_t I2C_SendData(uint8_t addr,uint8_t *data,uint32_t len) // { // uint32_t I2C_timeOut = 0x3ffff,i; // /* Disable the acknowledgement */ // I2C1->CR1 &= ~I2C_CR1_ACK; // /* Generate a START condition */ // I2C1->CR1 |= I2C_CR1_START; // /* Test on I2C1 EV5 and clear it */ // while(I2C_CheckStatus(I2C_EVENT_MASTER_MODE_SELECT)) // { // //if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} // } // I2C1->DR = addr & 0xfe; /* Send slave address for write */ // /* Test on I2C1 EV6 and clear it */ // while(I2C_CheckStatus(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) // { // //if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} // } // for(i = 0;i < len; i++) // { // /*Send data*/ // I2C1->DR = data[i]; // /* Test on I2C1 EV8 and clear it */ // while(I2C_CheckStatus(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) // { // //if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} // } // } // /* EV8_2: Wait until BTF is set before programming the STOP */ // while ((I2C1->SR1 & 0x00004) != 0x000004); // /* Send I2C1 STOP Condition */ // I2C1->CR1 |= I2C_CR1_STOP; // /* Make sure that the STOP bit is cleared by Hardware */ // while ((I2C1->CR1&0x200) == 0x200); // return 0; // } uint8_t I2C_SendData(uint8_t addr,uint8_t *data,uint32_t len) { uint32_t I2C_timeOut = 10000000,temp; /* Disable the acknowledgement */ I2C1->CR1 &= ~I2C_CR1_ACK; /* Generate a START condition */ I2C1->CR1 |= I2C_CR1_START; /* Test on I2C1 EV5 and clear it */ while ((I2C1->SR1&0x0001) != 0x0001) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } I2C1->DR = addr & 0xfe; /* Send slave address for write */ /* Test on I2C1 EV6 and clear it */ while ((I2C1->SR1 &0x0002) != 0x0002) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Clear ADDR flag by reading SR2 register */ temp = I2C1->SR2; I2C1->DR = *data; data++; len--; while(len--) { /* Test on I2C1 EV8 and clear it */ while ((I2C1->SR1 & 0x00004) != 0x000004); { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /*Send data*/ I2C1->DR = *data; data++; } /* EV8_2: Wait until BTF is set before programming the STOP */ while ((I2C1->SR1 & 0x00004) != 0x000004) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Send I2C1 STOP Condition */ I2C1->CR1 |= I2C_CR1_STOP; /* Make sure that the STOP bit is cleared by Hardware */ while ((I2C1->CR1&0x200) == 0x200) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } return 0; } uint8_t I2C_CheckSlaveStatus(uint8_t addr) { uint32_t I2C_timeOut = 10000000; I2C1->SR1 = (uint16_t)~(I2C_SR1_AF & FLAG_Mask); /* Disable the acknowledgement */ I2C1->CR1 &= ~I2C_CR1_ACK; /* Generate a START condition */ I2C1->CR1 |= I2C_CR1_START; /* Test on I2C1 EV5 and clear it */ while(I2C_CheckStatus(I2C_EVENT_MASTER_MODE_SELECT)) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Send slave address for write */ I2C1->DR = addr & 0xfe; /* Test on I2C1 EV6 and clear it */ while(I2C_CheckStatus(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) { if(I2C_timeOut-- == 0){I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} } /* Check Acknowledge failure*/ if(I2C1->SR1 & I2C_SR1_AF) {I2C1->CR1 |= I2C_CR1_STOP; return 0xff;} /*Acknowledge failure*/ /* Send I2C1 STOP Condition */ I2C1->CR1 |= I2C_CR1_STOP; return 0; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <time.h> //Project 1 #define SEATNUM 250 #define TEL 8 #define SEATLOW 1 #define SEATHIGH 5 #define T_LOW 5 #define T_HIGH 10 #define CARDSUCCESS 90 #define SEATCOST 20 #define BILLION 1000000000L; //Project 2 #define SEAT 10 #define ZONE_A 5 #define ZONE_B 10 #define ZONE_C 10 #define A_SUCCESS 20 #define B_SUCCESS 40 #define C_SUCCESS 40 #define A_SEATCOST 30 #define B_SEATCOST 25 #define C_SEATCOST 20 #define CASH 4 #define T_CASH_LOW 2 #define T_CASH_HIGH 4 int customers; unsigned int seed; int *seatArray; int chance = 0; int balance = 0; int id_transaction = 0; double waitingTime = 0; double waitingTimeCash = 0; int currentTelInUse = 0; int currentCashInUse = 0; double assistanceTime = 0; pthread_mutex_t TelCounter; pthread_mutex_t ticketFinder; pthread_mutex_t addToBalance; pthread_mutex_t PrintMutex; pthread_mutex_t timeMutex; pthread_cond_t thresholdCond; //Project 2 pthread_mutex_t CashCounter; pthread_mutex_t timeCash; pthread_cond_t thresholdCondCash; //RANDOM ZONE GENERATOR //Returns 1 for Zone A, 2 for Zone B and 3 for Zone C int rndZoneGen(){ int prob = rand()%100; printf("Chance for the zone..%d %%\n", prob); if(prob >= 60){ return 3; }else if(prob >=20){ return 2; }else{ return 1; } } //RANDOM GENERATOR with limits int rndGen(int low,int high){ int result ; result= ( (rand() % (high+1-low) ) + low); return result; } //Checks if there are available tickets, returns -1 if not. int _isFull(int tickets, int rndZone){ int count = SEATNUM + 1; if(rndZone == 1){ for(int i = 199; i<199 + SEAT*ZONE_A; i++){ if(seatArray[i] == 0){ count = i; break; } } }else if(rndZone == 2){ for(int i = 99; i<99 + SEAT*ZONE_B; i++){ if(seatArray[i] == 0){ count = i; break; } } }else if(rndZone == 3){ for(int i = 0; i<SEAT*ZONE_C; i++){ if(seatArray[i] == 0){ count = i; break; } } } //Returns -1 if not enough tickets available, otherwise //Returns a position of the array if(rndZone == 1){ if((count + tickets) <= 199+SEAT*ZONE_A){ return count; }else{ return -1; } }else if(rndZone == 2){ if((count + tickets) <= 99+SEAT*ZONE_B){ return count; }else{ return -1; } }else if(rndZone == 3){ if((count + tickets) <= SEAT*ZONE_C){ return count; }else{ return -1; } } } //MAIN FUNCTION void *customerServe(void *threadId) { //SEED srand(seed); struct timespec start, stop; struct timespec start2, stop2; struct timespec start3, stop3; int rc; /* MUTEX 0 for time start*/ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 1 for employee available counter*/ rc = pthread_mutex_lock(&TelCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } while(currentTelInUse>=TEL){ printf("Currently waiting for the first available Telephonist, please wait, %d ---\n", currentTelInUse); rc= pthread_cond_wait(&thresholdCond ,&TelCounter); if(rc!=0){ printf("ERROR: return code from pthread_cond_wait() is %d\n", rc); pthread_exit(&rc); } printf("An available telephonist is found for customer\n"); } currentTelInUse++; rc = pthread_mutex_unlock(&TelCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 1.2 for time end */ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } waitingTime += ( stop.tv_sec - start.tv_sec ) + ( stop.tv_nsec - start.tv_nsec ) / BILLION; rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 2 time of the whole call start */ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &start2) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } int rndSeats= rndGen(SEATLOW,SEATHIGH); //Number of seats int rndZone= rndZoneGen(); //Zone A = 1, Zone B = 2, Zone C = 3 int rndSec= rndGen(T_LOW,T_HIGH); //Seconds to process the request int rndSecCach = rndGen(T_CASH_LOW,T_CASH_LOW); //Secons to process payment /* MUTEX 3 check availability of tickets*/ rc = pthread_mutex_lock(&ticketFinder); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } id_transaction++; int count = _isFull(rndSeats, rndZone); if(count != -1){ /* MUTEX 4 waiting time cashier start*/ rc = pthread_mutex_lock(&timeCash); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &start3) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } rc = pthread_mutex_unlock(&timeCash); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 5 cash counter */ rc = pthread_mutex_lock(&CashCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } while(currentCashInUse >= CASH){ printf("Currently waiting for the first available Cachier, please wait, %d\n", currentCashInUse); rc= pthread_cond_wait(&thresholdCondCash ,&CashCounter); if(rc!=0){ printf("ERROR: return code from pthread_cond_wait() is %d\n", rc); pthread_exit(&rc); } printf("An available telephonist is found for customer\n"); } currentCashInUse++; rc = pthread_mutex_unlock(&CashCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 4.1 waiting time cashier end */ rc = pthread_mutex_lock(&timeCash); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &stop3) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } waitingTimeCash += rndSecCach + ( stop3.tv_sec - start3.tv_sec ) + ( stop3.tv_nsec - start3.tv_nsec ) / BILLION; rc = pthread_mutex_unlock(&timeCash); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } //PAYMENT chance = rand()% 100; printf("Chance for the payment.. %d %%\n", chance); if (chance >= CARDSUCCESS){ printf("Your payment failed! Sorry for the inconvenience.."); /* MUTEX 6 calculate total time passed if payment is failed */ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &stop2) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } assistanceTime += waitingTimeCash + waitingTime + rndSec + ( stop.tv_sec - start.tv_sec ) + ( stop.tv_nsec - start.tv_nsec ) / BILLION; rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } currentTelInUse--; currentCashInUse--; rc = pthread_mutex_unlock(&ticketFinder); pthread_exit(&rc); } for(int i = count; i< count + rndSeats; i++){ seatArray[i] = id_transaction; } //currentTelInUse--; //here //IF NO AVAILABLE SEATS } else if(count == -1){ printf("All seats are reserved, thank you %d customer!:)\n", id_transaction); /* MUTEX 7 calculate total time passed if no available seats */ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &stop2) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } assistanceTime += waitingTimeCash + waitingTime + rndSec + ( stop2.tv_sec - start2.tv_sec ) + ( stop2.tv_nsec - start2.tv_nsec ) / BILLION; rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } currentTelInUse--; //here rc = pthread_mutex_unlock(&ticketFinder); pthread_exit(&rc); } rc = pthread_mutex_unlock(&ticketFinder); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX cash counter wake up */ rc = pthread_mutex_lock(&CashCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if ( currentCashInUse < CASH){ pthread_cond_signal(&thresholdCondCash); } currentCashInUse--; rc = pthread_mutex_unlock(&CashCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 8 for balance */ rc = pthread_mutex_lock(&addToBalance); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if(rndZone == 1){ balance+=rndSeats*A_SEATCOST; }else if(rndZone == 2){ balance+=rndSeats*B_SEATCOST; }else if(rndZone == 3){ balance+=rndSeats*C_SEATCOST; } rc = pthread_mutex_unlock(&addToBalance); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 9 for prints */ rc = pthread_mutex_lock(&PrintMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } //PRINTS IF THERE WERE AVAILABLE SEATS if( count!=-1 ){ printf("Your Transaction id is :%d\n", id_transaction); printf("Your seats are succesfully reserved. We shall now process to payment\n"); printf("Total cost of the transaction is: %d€\n", rndSeats*SEATCOST); printf("Your Seats reserved are: "); for(int i = count; i< count + rndSeats; i++){ printf(" %d ", i ); } printf("\n"); } rc = pthread_mutex_unlock(&PrintMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 10 employee counter and wake up condition */ rc = pthread_mutex_lock(&TelCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if ( currentTelInUse < TEL){ pthread_cond_signal(&thresholdCond); } currentTelInUse--; rc = pthread_mutex_unlock(&TelCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } /* MUTEX 11 total time passed end */ rc = pthread_mutex_lock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_lock() is %d\n", rc); pthread_exit(&rc); } if( clock_gettime( CLOCK_REALTIME, &stop2) == -1 ) { perror( "clock gettime" ); exit( EXIT_FAILURE ); } assistanceTime += waitingTimeCash + waitingTime + rndSec + ( stop2.tv_sec - start2.tv_sec ) + ( stop2.tv_nsec - start2.tv_nsec ) / BILLION; rc = pthread_mutex_unlock(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_unlock() is %d\n", rc); pthread_exit(&rc); } pthread_exit(threadId); } //MAIN int main(int argc, char *argv[]) { int rc; //Checks if user gave the correct input if (argc != 3) { printf("ERROR: the program should take two arguments, the number of customers to create and the seed number!\n"); exit(0); } customers = atoi(argv[1]); seed = atoi(argv[2]); //Checks if the value is a positive number, otherwise end program if (customers < 0) { printf("ERROR: the number of customers to run should be a positive number. Current number given %d.\n", customers); exit(-1); } if (seed < 0) { printf("ERROR: the number of seed to run should be a positive number. Current number given %d.\n", 8); exit(-1); } printf("Main: We will create %d threads for each customer.\n", customers); seatArray = (int *)malloc(sizeof(int) * SEATNUM); //elegxos an apetyxe i malloc if (seatArray == NULL) { printf("ERROR: Calloc failed not enough memory!\n"); return -1; } //ARRAY INITIALIZATION, //All elements are 0, all seats are empty for(int i = 0; i < SEATNUM; i++) { seatArray[i]=0; } //CREATE MUTEX rc = pthread_mutex_init(&TelCounter, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&addToBalance, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&ticketFinder, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&PrintMutex, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&timeMutex, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&CashCounter, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&timeCash, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc= pthread_cond_init(&thresholdCond, NULL); if (rc!=0){ printf("ERROR: return code from pthread_cond_init() is %d\n", rc); exit(-1); } rc= pthread_cond_init(&thresholdCondCash, NULL); if (rc!=0){ printf("ERROR: return code from pthread_cond_init() is %d\n", rc); exit(-1); } pthread_t *threads = malloc(sizeof(pthread_t) * customers); int threadIds[customers]; if (threads == NULL) { printf("ERROR: Failed to allocate threads , not enough memory!\n"); return -1; } for (int i = 0; i < customers; i++) { threadIds[i] = i + 1; rc = pthread_create(&threads[i], NULL, customerServe, &threadIds[i]); if (rc != 0) { printf("ERROR: return code from pthread_create() is %d\n", rc); exit(-1); } } void *status; for (int i = 0; i < customers; i++) { rc = pthread_join(threads[i], &status); if (rc != 0) { printf("ERROR: return code from pthread_join() is %d\n", rc); exit(-1); } } //PRINT SEATS for (int i = 0; i < SEATNUM; i++) { if( seatArray[i] != 0){ if(i>199 && i<=249){ printf("Zone A / Seat %d / Costumer %d\n", i+1, *(seatArray + i)); }else if(i>99 && i<=199){ printf("Zone B / Seat %d / Costumer %d\n", i+1, *(seatArray + i)); }else if(i>=0 && i<=99){ printf("Zone C / Seat %d / Costumer %d\n", i+1, *(seatArray + i)); } } } //PRINT INFO printf("\n"); printf("The balance is: %d euros\n",balance); printf("Total transactions: %d\n",id_transaction); printf("Total waiting Time until reaching an employee: %f\n",waitingTime/customers/100); printf("Total waiting Time until reaching the cashier: %f\n",waitingTimeCash/customers/100); printf("Total waiting Time until reaching the end: %f\n",assistanceTime/customers/100); //DESTROY MUTEX rc = pthread_mutex_destroy(&TelCounter); if (rc != 0) { printf("ERROR: return code from pthread_mutex_destroy() is %d\n", rc); exit(-1); } rc = pthread_mutex_destroy(&addToBalance); if (rc != 0) { printf("ERROR: return code from pthread_mutex_destroy() is %d\n", rc); exit(-1); } rc = pthread_mutex_destroy(&ticketFinder); if (rc != 0) { printf("ERROR: return code from pthread_mutex_destroy() is %d\n", rc); exit(-1); } rc = pthread_mutex_destroy(&PrintMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_destroy() is %d\n", rc); exit(-1); } rc = pthread_mutex_destroy(&timeMutex); if (rc != 0) { printf("ERROR: return code from pthread_mutex_destroy() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&CashCounter, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_mutex_init(&timeCash, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } rc = pthread_cond_destroy(&thresholdCond); if (rc != 0) { printf("ERROR: return code from pthread_cond_destroy() is %d\n", rc); exit(-1); } rc = pthread_cond_destroy(&thresholdCondCash); if (rc != 0) { printf("ERROR: return code from pthread_cond_destroy() is %d\n", rc); exit(-1); } //DELETE MEMORY free(threads); free(seatArray); return 1; }
C
/*Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right.*/ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node* insert( struct node* root, int data ) { //if empty if(root == NULL) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return node; } else { struct node* cur; if(data <= root->data) { cur = insert(root->left, data); root->left = cur; } else { cur = insert(root->right, data); root->right = cur; } return root; } } //The height of a tree, or depth of a tree, is the maximum level of your children int getHeight(struct node* root) { int hl, hr; if (!root) return 0; //tree height empty hl = getHeight(root->left); hr = getHeight(root->right); if (hl<hr) return (hr+1); else return (hl+1); } void level(struct node *root,int h){ if(!root) return ; if(h==1) //then print the elements printf("%d ", root->data); //visits the children of the left with height less than h level(root->left,h-1); //then visits the children of the right with height less than h level(root->right,h-1); //returns to main function } void levelOrder( struct node *root) { //First step: calculates the height of the tree int n=getHeight(root); // travels nodes from height = 1 (i=1) for(int i=1;i<=n;i++){ level(root,i); } } int main() { struct node* root = NULL; int t; int data; scanf("%d", &t); while(t-- > 0) { scanf("%d", &data); root = insert(root, data); } levelOrder(root); return 0; }
C
/* strlen: return length of string s */ int strlen(char *s) { int n; for (n = 0; *s != '\0'; s++) n++; return n; }
C
#include "common.h" int main(int argc,char *argv[]) { int sock_listen,sock_control,port,pid; if(argc!=2) { printf("usage:./ftpserv port\n"); exit(0); } port=atoi(argv[1]); if((sock_listen=socket_create(port))<0) { perror("error creating socket\n"); exit(1); } while(1) { if((sock_control=socket_accept(sock_listen))<0) { perror("error accept\n"); break; } if((pid=fork())<0) { perror("fork child process error\n"); } else if(pid==0) { close(sock_listen); handle_process(sock_control); close(sock_control); exit(0); } } close(sock_listen); return 0; } void handle_process(int sock_control) { int sock_data; char cmd[5]; char argv[512]; send_response(sock_control,220); while(1) { int usr_cmd=ftpserv_recv_cmd(sock_control,cmd,argv); if(usr_cmd<0||usr_cmd==221) { break; } if(usr_cmd==200) { if(sock_data=ftpserv_start_data_conn(sock_control)<0) { close(sock_control); exit(0); } if(cmd=="list") { ftpserv_list(sock_data,sock_control); } if(cmd=="get"){ ftpserv_get(sock_data,argv); } } } int send_response(int sock_control,int c) { int code=htons(c); if(write(sock_control,code,sizeof(code))<0) { perror("error in send response.\n"); return -1; } return 0; } int ftpserv_recv_cmd(int sock_control,char *cmd,char *argv) { int rc=200; char buff[512]; memset(cmd,0,5); memset(argv,0,512); memset(buff,0,512); if(recv_data(sock_control,buff,sizeof(buff))<0) { perror("receive data from client error.\n"); return -1; } strncpy(cmd,buff,4); char *tmp = buff + 5; strcpy(argv, tmp); if(strcmp(cmd,"quit")==0) { rc=221; } else if(strcmp(cmd,"get")==0||strcmp(cmd,"list")==0) { rc=200; } else { //invalid command rc=500; } send_response(sock_control,rc); return rc; } int ftpserv_start_data_conn(int sock_control) { int sock_data_cnne; struct sockaddr_in sockaddr; socklen_t len=sizeof(sockaddr); if((sock_data_cnne=connect(sock_control,(struct sockaddr*)&sockaddr,len))<0) { perror("connect error!\n"); return -1; } return sock_data_cnne; } int ftpserv_list(int sock_data,int sock_control) { DIR *filedir=NULL; char buff[512]; struct dirent* entry; bzero(buff,512); if((filedir=opendir(FILEPATH))==NULL) { perror("open directory failed\n"); return -1; } while((entry=readdir(filedie))!=NULL) { if(sprintf(buff,entry->d_name,512)<0) { perror("sprintf error!\n"); return -1; } if(write(sock_data,buff,512)<0) { perror("write error.\n"); return -1; } } closedir(filedir); return 0; } int ftpserv_get(int sock_data,char *filename) { char src[]=FILEPATH; strcat(src,filename); char *pfile=src; FILE *file; char buff[1024]; int file_len=0; bzero(buff,1024); if((file=fopen(pfile,"r+"))==NULL) { perror("open file failed.\n"); return -1; } while((file_len=fread(buff,sizeof(char),sizeof(buff),file))>0) { if(write(sock_data,buff,file_len)<0) { fputs("send file failed\n",stdout); return 0; } } return 0; }
C
#define vec_binop(_name, _op) \ int _name ## _slow (sil_State *S, int t1, int t2) { \ int dx=1, dy=1; \ int n = 1; \ const double *x, *y; \ double xval, yval; \ if(t1 == 5 || t1 == 6 || t1 == 7) { \ dx = 0; \ xval = sil_todouble(S, 1); \ x = &xval; \ } else if(t1 == 16) { \ const vector *a = (vector *)sil_topointer(S, 1); \ n = a->n; \ x = a->x; \ } else { \ return sil_err(S, "Invalid 1st arg"); \ } \ if(t2 == 5 || t2 == 6 || t2 == 7) { \ dy = 0; \ yval = sil_todouble(S, 2); \ y = &yval; \ } else if(t2 == 16) { \ const vector *b = (vector *)sil_topointer(S, 2); \ n = b->n; /* we know both are not vectors */ \ y = b->x; \ } else { \ return sil_err(S, "Invalid 2nd arg"); \ } \ vector *c = (vector *)malloc(sizeof(vector)+8*n); \ c->n = n; \ int i; \ for(i=0; i<n; i++) { \ c->x[i] = (*x) _op (*y); \ x += dx; y += dy; \ } \ sil_settop(S, 0); \ sil_pushvector(S, c); \ return 0; \ } \ int _name (sil_State *S) { \ int t1 = sil_type(S, 1); \ int t2 = sil_type(S, 2); \ if(t1 != 16 || t2 != 16) { /* slow version */ \ return _name ## _slow(S, t1, t2); \ } \ const vector *a = (vector *)sil_topointer(S, 1); \ const vector *b = (vector *)sil_topointer(S, 2); \ if(a == NULL || b == NULL) \ return sil_err(S, "Invalid arguments"); \ if(a->n != b->n) \ return sil_err(S, "Sizes of vectors don't match: %d vs %d", a->n,b->n);\ vector *c = (vector *)malloc(sizeof(vector)+8*a->n); \ c->n = a->n; \ int i; \ for(i=0; i<a->n; i++) { \ c->x[i] = a->x[i] _op b->x[i]; \ } \ sil_settop(S, 0); \ sil_pushvector(S, c); \ return 0; \ } // create add, mul, and sub functions vec_binop(add, +); vec_binop(mul, *); vec_binop(sub, -); vec_binop(divide, /); // simple vector creation routines int zeros(sil_State *S) { if(sil_type(S, 1) != 6) return sil_err(S, "zeros requires int argument"); int i, n = sil_tointeger(S, 1); vector *v = (vector *)calloc((sizeof(vector) + 8*n)/4, 4); v->n = n; sil_settop(S, 0); sil_pushvector(S, v); return 0; } int range(sil_State *S) { if(sil_type(S, 1) != 6 || sil_type(S, 2) != 6) return sil_err(S, "range requires 2 int args"); int i = sil_tointeger(S, 1); int j = sil_tointeger(S, 2); int n = 0, m = i <= j ? j - i : i - j; if(m > 10000000) { return sil_err(S, "range exceeds 10M elements"); } vector *v = (vector *)malloc(sizeof(vector)+8*m); v->n = m; if(i <= j) { for(; i<j; i++,n++) { v->x[n] = i; } } else { for(; i>j; i--,n++) { v->x[n] = i; } } sil_settop(S, 0); sil_pushvector(S, v); return 0; } // [Float] -> Vector int fromList(sil_State *S) { int i, n = sil_llen(S, 1); vector *v = (vector *)malloc(sizeof(vector)+8*n); v->n = n; for(i=0; i<n; i++) { sil_behead(S, 1); v->x[i] = sil_todouble(S, 2); sil_remove(S, 2); } sil_settop(S, 0); sil_pushvector(S, v); return 0; } // Vector -> [Float] int toList(sil_State *S) { int i; const vector *v = (vector *)sil_topointer(S, 1); if(v == NULL) { return sil_err(S, "Invalid argument"); } for(i=0; i<v->n; i++) { sil_pushdouble(S, v->x[i]); } sil_setcons(S, v->n); sil_remove(S, 1); // clear vector return 0; } // Vector -> Int -> Float int elem(sil_State *S) { int i; const vector *v = (vector *)sil_topointer(S, 1); if(v == NULL) { return sil_err(S, "Invalid argument"); } i = sil_tointeger(S, 2); sil_remove(S, 2); if(i < 0) i += v->n; if(i < 0 || i >= v->n) { return sil_err(S, "Invalid index"); } sil_pushdouble(S, v->x[i]); sil_remove(S, 1); return 0; } // Int -> Float -> ST(Vector, Float) int setElem(sil_State *S) { size_t len; // Always assume len is wrong! vector *v = (vector *)sil_getST(S, &len); if(v == NULL) { return sil_err(S, "Can't update - no vector present"); } int i = sil_tointeger(S, 1); if(i < 0) i += v->n; if(i < 0 || i >= v->n) { return sil_err(S, "Invalid index"); } double prev = v->x[i]; v->x[i] = sil_todouble(S, 2); sil_settop(S, 0); sil_pushdouble(S, prev); return 0; } // updateElem = fun Int i, (fun Float x -> Float) -> ST(Vector, Float) int updateElem(sil_State *S) { size_t len; // Always assume len is wrong! vector *v = (vector *)sil_getST(S, &len); if(v == NULL) { return sil_err(S, "Can't update - no vector present"); } int i = sil_tointeger(S, 1); if(i < 0) i += v->n; if(i < 0 || i >= v->n) { return sil_err(S, "Invalid index"); } sil_pushdouble(S, v->x[i]); sil_call(S, 2); v->x[i] = sil_todouble(S, 2); sil_settop(S, 0); sil_pushdouble(S, v->x[i]); return 0; } // (Int -> Float) -> Int -> Vector int fromFunction(sil_State *S) { int i, n = sil_tointeger(S, 2); if(n < 0 || n > 10000000) { return sil_err(S, "invalid length"); } vector *v = (vector *)malloc(sizeof(vector)+8*n); v->n = n; sil_remove(S, 2); for(i=0; i<n; i++) { sil_pushvalue(S, 1); // copy function sil_pushinteger(S, i); // push arg sil_call(S, 2); v->x[i] = sil_todouble(S, 2); sil_remove(S, 2); // clear result } sil_remove(S, 1); // remove function sil_pushvector(S, v); return 0; }