language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> void main() { int a=5; int b=++a; int x=a+b; //int x=a+(++a); printf("a=%d\n",a); printf("x=%d",x); }
C
/************************************************************************* > File Name: server_udp.c > Author: Arwen > Mail:[email protected] > Created Time: Tue 24 Feb 2015 02:44:12 PM CST ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<unistd.h> #include<fcntl.h> #include<sys/stat.h> #include<arpa/inet.h> #define ser_IP "192.168.1.124" #define ser_PORT 1234 int main(int argc, char *argv[]) { int fd_listen = socket(AF_INET, SOCK_DGRAM, 0); if(fd_listen == -1) { perror("socket!\n"); close(fd_listen); exit(1); } struct sockaddr_in my_addr; memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(ser_PORT); my_addr.sin_addr.s_addr = inet_addr(ser_IP); if(-1 == bind(fd_listen, (struct sockaddr*)&my_addr, sizeof(my_addr))) { perror("bind\n"); close(fd_listen); exit(1); } char buf[512] = {0}; while(1) { struct sockaddr_in clientaddr; memset(&clientaddr, 0, sizeof(clientaddr)); socklen_t clientaddr_len = sizeof(clientaddr); if(-1 == recvfrom(fd_listen, buf, sizeof(buf),0,(struct sockaddr*)&clientaddr,&clientaddr_len)) { perror("recvfrom\n"); close(fd_listen); exit(1); } printf("receive from %s %d,the message is :%s\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port),buf); sendto(fd_listen, "success", 10, 0, (struct sockaddr*)&clientaddr, sizeof(struct sockaddr) ); } close(fd_listen); return 0; }
C
#include "../includes/common.h" ElfW(Addr) GetSymAddr(const char *name, Elf_t *target) { ElfW(Sym) *symtab; char *SymStrTable; int i, j, symcount; for (i = 0; i < target->ehdr->e_shnum; i++) if (target->shdr[i].sh_type == SHT_SYMTAB || target->shdr[i].sh_type == SHT_DYNSYM) { SymStrTable = (char *)&target->mem[target->shdr[target->shdr[i].sh_link].sh_offset]; symtab = (ElfW(Sym) *)&target->mem[target->shdr[i].sh_offset]; for (j = 0; j < target->shdr[i].sh_size / sizeof(ElfW(Sym)); j++, symtab++) { if(strcmp(&SymStrTable[symtab->st_name], name) == 0) return (symtab->st_value); } } return 0; } char * get_symbol_name(Elf_t *target, ElfW(Addr) addr) { ElfW(Sym) *symtab; char *SymStrTable; int i, j, symcount; for (i = 0; i < target->ehdr->e_shnum; i++) { if (target->shdr[i].sh_type == SHT_SYMTAB || target->shdr[i].sh_type == SHT_DYNSYM) { SymStrTable = (char *)&target->mem[target->shdr[target->shdr[i].sh_link].sh_offset]; symtab = (ElfW(Sym) *)&target->mem[target->shdr[i].sh_offset]; for (j = 0; j < target->shdr[i].sh_size / sizeof(ElfW(Sym)); j++, symtab++) { if (symtab->st_value == addr) return (char *)&SymStrTable[symtab->st_name]; } } } return NULL; } uint32_t GetSymSize(const char *name, Elf_t *target) { ElfW(Sym) *symtab; char *SymStrTable; int i, j, symcount; for (i = 0; i < target->ehdr->e_shnum; i++) if (target->shdr[i].sh_type == SHT_SYMTAB || target->shdr[i].sh_type == SHT_DYNSYM) { SymStrTable = (char *)&target->mem[target->shdr[target->shdr[i].sh_link].sh_offset]; symtab = (ElfW(Sym) *)&target->mem[target->shdr[i].sh_offset]; for (j = 0; j < target->shdr[i].sh_size / sizeof(ElfW(Sym)); j++, symtab++) { if(strcmp(&SymStrTable[symtab->st_name], name) == 0) return (symtab->st_size); } } return 0; } int section_exists(Elf_t *target, const char *name) { char *StringTable = target->StringTable; ElfW(Shdr) *shdr = target->shdr; ElfW(Ehdr) *ehdr = target->ehdr; int i; for (i = 0; i < ehdr->e_shnum; i++) if (!strcmp(&StringTable[shdr[i].sh_name], name)) return 1; return 0; } /* * XXX move ELF functions int libs/elf.c or something. */ char * get_section_name(Elf_t *target, ElfW(Addr) addr) { char *StringTable = target->StringTable; ElfW(Shdr) *shdr = target->shdr; int i; for (i = 0; i < target->ehdr->e_shnum; i++) if (shdr[i].sh_addr == addr) return (char *)&StringTable[shdr[i].sh_name]; return NULL; } int load_live_kcore(Elf_t *elf) { ElfW(Ehdr) *ehdr; ElfW(Phdr) *phdr; uint8_t *tmp; int fd, i, j; ssize_t b; loff_t real_text_offset, real_vm_offset; unsigned long text_base = get_text_base(); if (text_base == 0) text_base = GetSymAddr("_text", elf); if ((fd = open("/proc/kcore", O_RDONLY)) < 0) { perror("open"); exit(-1); } elf->mem = malloc(4096); b = read(fd, elf->mem, sizeof(ElfW(Ehdr))); ehdr = (ElfW(Ehdr) *)elf->mem; /* * Get phdr table */ lseek(fd, ehdr->e_phoff, SEEK_SET); b = read(fd, &elf->mem[ehdr->e_phoff], sizeof(ElfW(Phdr)) * ehdr->e_phnum); assert_read(b); phdr = (ElfW(Phdr) *)(elf->mem + ehdr->e_phoff); for (j = 0, i = 0; i < ehdr->e_phnum; i++) { switch(phdr[i].p_type) { case PT_LOAD: #ifdef __x86_64__ if (phdr[i].p_vaddr == text_base) { #else if ((phdr[i].p_vaddr & ~0x0fffffff) == 0xc0000000) { #endif elf->textSiz = phdr[i].p_memsz; elf->textOff = ehdr->e_phoff + sizeof(ElfW(Phdr)) * ehdr->e_phnum; elf->textVaddr = phdr[i].p_vaddr; real_text_offset = phdr[i].p_offset; j++; } #ifdef __x86_64__ if (phdr[i].p_vaddr == 0xffff880000100000) { elf->kmSiz = phdr[i].p_memsz; elf->kmOff = phdr[i].p_offset; elf->kmVaddr = phdr[i].p_vaddr; j++; } #endif #ifdef __x86_64__ if (phdr[i].p_vaddr == 0xffff880100000000) { #else if ((phdr[i].p_vaddr & ~0x00ffffff) == 0xf8000000) { #endif elf->vmSiz = phdr[i].p_memsz; elf->vmOff = phdr[i].p_offset; real_vm_offset = phdr[i].p_offset; elf->vmVaddr = phdr[i].p_vaddr; j++; } break; case PT_NOTE: break; } } tmp = alloca(4096); memcpy(tmp, elf->mem, sizeof(ElfW(Ehdr)) + sizeof(ElfW(Phdr)) * ehdr->e_phnum); elf->mem = mmap(NULL, elf->textSiz + 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); assert_mmap(elf->mem); memcpy(elf->mem, tmp, sizeof(ElfW(Ehdr)) + sizeof(ElfW(Phdr)) * ehdr->e_phnum); lseek(fd, real_text_offset, SEEK_SET); b = read(fd, &elf->mem[elf->textOff], elf->textSiz); assert_read(b); close(fd); elf->ehdr = ehdr; elf->phdr = phdr; elf->e_type = ehdr->e_type; return 0; } int load_elf_image(const char *path, Elf_t *elf) { int fd; struct stat st; uint8_t *mem; int i, j, use_phdrs = 0; ElfW(Phdr) *phdr; ElfW(Ehdr) *ehdr; loff_t real_text_offset, real_vm_offset; unsigned long text_base = get_text_base(); if (text_base == 0) text_base = GetSymAddr("_text", elf); elf->path = strdup(path); if ((fd = open(path, O_RDONLY)) < 0) { perror("open"); return -1; } if (fstat(fd, &st) < 0) { perror("fstat"); return -1; } elf->mem = mem = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (mem == MAP_FAILED ) { perror("mmap"); return -1; } elf->ehdr = (ElfW(Ehdr) *)mem; elf->phdr = (ElfW(Phdr) *)(mem + elf->ehdr->e_phoff); elf->shdr = (ElfW(Shdr) *)(mem + elf->ehdr->e_shoff); phdr = elf->phdr; ehdr = elf->ehdr; if (elf->ehdr->e_shstrndx == SHN_UNDEF || elf->ehdr->e_shnum == 0 || elf->ehdr->e_shoff == 0) use_phdrs++; if (use_phdrs) goto parse_phdr; elf->StringTable = (char *)&elf->mem[elf->shdr[elf->ehdr->e_shstrndx].sh_offset]; for (i = 0; i < elf->ehdr->e_shnum; i++) { if (!strcmp(&elf->StringTable[elf->shdr[i].sh_name], ".text") || !strcmp(&elf->StringTable[elf->shdr[i].sh_name], ".kernel")) { elf->textOff = elf->shdr[i].sh_offset; break; } } goto done; parse_phdr: for (j = 0, i = 0; i < elf->ehdr->e_phnum; i++) { switch(phdr[i].p_type) { case PT_LOAD: #ifdef __x86_64__ if (phdr[i].p_vaddr == text_base) { #else if ((phdr[i].p_vaddr & ~0x0fffffff) == 0xc0000000) { #endif elf->textSiz = phdr[i].p_memsz; elf->textOff = ehdr->e_phoff + sizeof(ElfW(Phdr)) * ehdr->e_phnum; elf->textVaddr = phdr[i].p_vaddr; real_text_offset = phdr[i].p_offset; j++; } #ifdef __x86_64__ if (phdr[i].p_vaddr == 0xffff880000100000) { elf->kmSiz = phdr[i].p_memsz; elf->kmOff = phdr[i].p_offset; elf->kmVaddr = phdr[i].p_vaddr; j++; } #endif #ifdef __x86_64__ if (phdr[i].p_vaddr == 0xffff880100000000) { #else if ((phdr[i].p_vaddr & ~0x00ffffff) == 0xf8000000) { #endif elf->vmSiz = phdr[i].p_memsz; elf->vmOff = phdr[i].p_offset; real_vm_offset = phdr[i].p_offset; elf->vmVaddr = phdr[i].p_vaddr; j++; } break; case PT_NOTE: break; } } done: elf->fd = fd; elf->st = st; elf->e_type = elf->ehdr->e_type; return 0; }
C
#include <stdio.h> void main(){ int x=0,y=10; for(x=0;y<20;x++,y++){ x=x+y; x++; printf("sum of x,y = %d\n",x); } printf("sum of x,y = %d\n",x); }
C
#include <stdio.h> float celsiusToFahr(float celsius); int main(){ float fahr, celsius; for(celsius = 0; celsius <= 300; celsius = celsius + 20) { fahr = celsiusToFahr(celsius); printf("%6.1f\t%6.1f\n", celsius, fahr); } } float celsiusToFahr(float celsius) { return celsius * 9.0/5.0 + 32.0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <errno.h> #ifndef N #define N 16 #endif // #define COUNT_OPERATIONS // #define PRINT_RESULT extern void *permute0_func(void *arg); extern void permute0(int a[], int n, int conflictMap[N][N]); extern void permute(int a[], int j, int n, int conflictMap[N][N]); int permute_count = 0; long rotate_count = 0; int solution_count = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t done = PTHREAD_COND_INITIALIZER; struct permute_data { int a[N]; int n; int conflictMap[N][N]; int mt; }; extern void permute0_mt(int a[], int n, int conflictMap[N][N]); extern pthread_t permute_mt(int a[], int n, int conflictMap[N][N]); extern void *permute_func(void *arg); int main(int argc, char** argv) { int i, a[N], j, err; struct permute_data data; pthread_t thread; struct timespec ts; data.n = N; for (i=0;i<N;i++) data.a[i] = i; memset(data.conflictMap, 0, sizeof(data.conflictMap)); if (argc > 1 && strcmp(argv[1],"-mt") == 0) data.mt = 1; else data.mt = 0; pthread_create(&thread, 0, permute0_func, &data); clock_gettime(CLOCK_REALTIME, &ts); for (;;) { ts.tv_sec++; pthread_mutex_lock(&lock); err = pthread_cond_timedwait(&done, &lock, &ts); pthread_mutex_unlock(&lock); if (err != ETIMEDOUT) break; printf("%-6.2f%%\n", solution_count/14772512.0*100); } pthread_join(thread, 0); printf("Count: %d\n", solution_count); #ifdef COUNT_OPERATIONS printf("permute: %d\n", permute_count); printf("rotate: %ld\n", rotate_count); #endif } void print_result(int a[], int n) { int i; printf("%d> ", solution_count); for (i=0;i<n;i++) printf("%d ", a[i]+1); printf("\n"); } void *permute0_func(void *arg) { struct permute_data *data = (struct permute_data *)arg; if (data->mt) permute0_mt(data->a, data->n, data->conflictMap); else permute0(data->a, data->n, data->conflictMap); pthread_mutex_lock(&lock); pthread_cond_broadcast(&done); pthread_mutex_unlock(&lock); return 0; } void permute0(int a[], int n, int conflictMap[N][N]) { int i, t; #ifdef COUNT_OPERATIONS permute_count++; #endif permute(a, 1, n, conflictMap); for (i=1;i<n;i++) { #ifdef COUNT_OPERATIONS rotate_count++; #endif t = a[0]; a[0] = a[i]; a[i] = t; permute(a, 1, n, conflictMap); } } void permute0_mt(int a[], int n, int conflictMap[N][N]) { int i, t; pthread_t threads[N-1]; #ifdef COUNT_OPERATIONS permute_count++; #endif threads[0] = permute_mt(a, n, conflictMap); for (i=1;i<n;i++) { #ifdef COUNT_OPERATIONS rotate_count++; #endif t = a[0]; a[0] = a[i]; a[i] = t; if (i != n-1) threads[i] = permute_mt(a, n, conflictMap); else permute(a, 1, n, conflictMap); } for (i=0;i<n-1;i++) pthread_join(threads[i], 0); } pthread_t permute_mt(int a[], int n, int conflictMap[N-1][N]) { int i, j, err; pthread_t thread; struct permute_data *data = (struct permute_data*)malloc(sizeof(struct permute_data)); data->n = n; for (i = 0; i < n; i++) data->a[i] = a[i]; memset(data->conflictMap, 0, sizeof(data->conflictMap)); err = pthread_create(&thread, 0, permute_func, data); if (err < 0) { printf("pthread_create error\n"); } return thread; } void *permute_func(void *arg) { struct permute_data *data = (struct permute_data *)arg; permute(data->a, 1, data->n, data->conflictMap); return 0; } void permute(int a[], int j, int n, int conflictMap[N][N]) { int j1 = j-1; #ifdef COUNT_OPERATIONS permute_count++; #endif if (j == n - 1) { if (conflictMap[j1][a[j]] == 0 && a[j] != a[j1]+1 && a[j] != a[j1]-1) { pthread_mutex_lock(&lock); solution_count++; #ifdef PRINT_RESULT print_result(a, n); #endif pthread_mutex_unlock(&lock); } } else { int i,t; for (i=j;i<n;i++) {int k=a[j1]-i+j1; if (k>=0) conflictMap[i-1][k]++; k=a[j1]+i-j1; if (k < n) conflictMap[i-1][k]++;} if (conflictMap[j1][a[j]]==0) permute(a, j+1, n, conflictMap); for (i=j+1;i<n;i++) { #ifdef COUNT_OPERATIONS rotate_count++; #endif t = a[j]; a[j] = a[i]; a[i] = t; if (conflictMap[j1][a[j]]==0) permute(a, j+1, n, conflictMap); } t = a[j]; for (i=j;i<n-1;i++) a[i] = a[i+1]; a[n-1] = t; for (i=j;i<n;i++) {int k=a[j1]-i+j1; if (k>=0) conflictMap[i-1][k]--; k=a[j1]+i-j1; if (k < n) conflictMap[i-1][k]--;} } }
C
#include<stdio.h> #include<stdlib.h> void main() { int *ptr,i; ptr=(int *)calloc(5,sizeof(int)); if(ptr==NULL) { printf("bellek yetersiz\n"); } for(i=0; i<5; i++) { printf("ptr[%d]=%d\n",i,ptr[i]); } printf("\n"); ptr=(int *)realloc(ptr,sizeof(int)*10); if(ptr==NULL) { printf("bellek yetersiz\n"); exit(0); } for(i=0; i<10; i++) printf("ptr[%d]=%d\n",i,ptr[i]); system("pause"); }
C
#include <cmath> #include <vector> #include <math.h> #include<iostream> #include<fstream> #include "nr3.h" #include "ludcmp.h" #include "svd.h" #include "gaussj.h" using namespace std; void hw1(){ cout<< setprecision(8); //Problem 1 VecDoub x(2); x[0] = 1; x[1] = -1; std::cout<<x[0]<<std::endl; //instantiate x VecDoub b(2); b[0] = 0.1869169; b[1] = 0.2155734; std::cout<<b[1]<<std::endl; //instantiate b MatDoub a(2,2); a[0][0]=0.7073725; a[0][1]=0.5204556; a[1][0]=0.8158208; a[1][1]=0.6002474; std::cout<<a[0][1]<<std::endl; //instantiate A VecDoub x1(2); x1[0] = 0.9999999; x1[1] = -1.0000001; VecDoub x2(2); x2[0] = 0.4073666; x2[1] = -0.1945277; //part a VecDoub r1(2); r1[0] = b[0]-(a[0][0]*x1[0]+a[0][1]*x1[1]); r1[1] = b[1]-(a[1][0]*x1[0]+a[1][1]*x1[1]); double r1norm=sqrt(pow(r1[0],2)+pow(r1[1],2)); std::cout<<r1norm<<std::endl; ofstream myfile; myfile.open("phys4480hw1_1.txt"); myfile << "1a.\n"; myfile << "r1=" << r1norm <<'\n'; //calculate residual for x1 and print to file VecDoub r2(2); r2[0] = b[0]-(a[0][0]*x2[0]+a[0][1]*x2[1]); r2[1] = b[1]-(a[1][0]*x2[0]+a[1][1]*x2[1]); double r2norm=sqrt(pow(r2[0],2)+pow(r2[1],2)); std::cout<<r2norm<<std::endl; myfile << "r2=" << r2norm << '\n'; //calculate residual for x2 and print to file //part b VecDoub xlu(2); LUdcmp alu(a); alu.solve(b,xlu); //sove for x with lu decomp double errorlu=sqrt(pow(xlu[0]-x[0],2)+pow(xlu[1]-x[1],2)); //calculate error=xlu-x VecDoub rlu(2); rlu[0] = b[0]-(a[0][0]*xlu[0]+a[0][1]*xlu[1]); rlu[1] = b[1]-(a[1][0]*xlu[0]+a[1][1]*xlu[1]); double rlunorm=sqrt(pow(rlu[0],2)+pow(rlu[1],2)); //calculate residual for xlu std::cout<<xlu[0]+xlu[1]<<std::endl; myfile << "1b.\n" << "xlu=" << xlu[0] << ", " << xlu[1] << "\n" << "LU decomp error=" << errorlu << "\n"; myfile << "residual for LU Decomp=" << rlunorm << '\n'; //part c SVD asvd(a); double conda=1/asvd.inv_condition(); myfile << "1c.\n" << "Cond(a)=" << conda << '\n'; //calculate and print condition number of A //Problem 2 int i,j; MatDoub A1600(1600,1600); ifstream inputA("A.txt"); for (i = 0; i < 1600; i++) { for (j = 0; j < 1600; j++) { inputA >> A1600[j][i]; } } inputA.close(); std::cout<<A1600[0][1]<<std::endl; VecDoub b1600(1600); ifstream inputb("b.txt"); for (i = 0; i < 1600; i++) { inputb >> b1600[i]; } inputb.close(); std::cout<<b1600[0]<<std::endl; VecDoub c1600(1600); ifstream inputc("c.txt"); for (i = 0; i < 1600; i++) { inputc >> c1600[i]; } inputb.close(); //part a MatDoub Ainv = A1600; gaussj(Ainv); std::cout<<Ainv[0][1]<<std::endl; VecDoub x1600(1600); for (i = 0; i < 1600; i++) { for (j = 0; j < 1600; j++) { x1600[i]+=A1600[i][j]*b1600[j]; } } double r = 0; for (j=0; j<1600; j++){ r+=abs(x1600[j]-c1600[j]); } myfile << "2a.\n" << "r=" << r << '\n'; //compute error //part b VecDoub xlu1600(1600); LUdcmp Alu1600(A1600); Alu1600.solve(b1600,xlu1600); //sove for x with lu decomp double rlu1600 = 0; for (j=0; j<1600; j++){ rlu1600+=abs(xlu1600[j]-c1600[j]); } myfile << "2b.\n" << "r=" << rlu1600 << '\n'; //compute error //part c std::cout<<xlu1600[0]<<std::endl; Alu1600.mprove(b1600,xlu1600); std::cout<<xlu1600[0]<<std::endl; //use iterative improvement to improve solution to x double rimprove = 0; for (j=0; j<1600; j++){ rimprove+=abs(xlu1600[j]-c1600[j]); } myfile << "2c.\n" << "r=" << rimprove << '\n'; //compute error //part d SVD A1600svd(A1600); double condA1600=1/A1600svd.inv_condition(); myfile << "2d.\n" << "Cond(A)=" << condA1600 << '\n'; //calculate and print condition number of A myfile.close(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //#pragma warning(disable : 4996) typedef struct { char name[20]; int weight; int price; int star; } Product; int addProduct(Product* p); //product를 추가하는 함수 void readProduct(Product p); //각 한 개의 product를 출력하는 함수 void listProduct(Product* m[], int count); //주어진 lsit의 product를 출력하는 함수 int selectDataNo(Product* p[], int count); //menu 목록 수행 중, 확인이 필요한 경우 사용하는 함수 int updateProduct(Product* p); //list에 product를 추가하는 함수 int deleteProduct(Product* p); //list에 입력된 product를 삭제하는 함수 void saveData(Product* p[], int count); int loadData(Product* p[]); void searchName(Product* p[], int count); int selectMenu();
C
/* * ocs.c * * Created on: Oct 29, 2009 * Author: petergoodman * Version: $Id$ */ #include "successors.h" static player_t which_player; static int top = 0; static int bottom = BOARD_LENGTH - 1; static int right = BOARD_LENGTH - 1; static int left = 0; /** * Compare the importance ratings of two empty cells by the weight + player * rating + chip rating. */ static int compare_cell(const void *a, const void *b) { board_cell_t *bb = (*(board_cell_t **) b); board_cell_t *aa = (*(board_cell_t **) a); return (bb->rating[0] + bb->rating[which_player] + bb->chip_rating) - (aa->rating[0] + aa->rating[which_player] + aa->chip_rating); } /** * Compare the importance ratings of two empty cells by the weight + chip * rating. */ static int compare_cell_ratings(const void *a, const void *b) { board_cell_t *bb = (*(board_cell_t **) b); board_cell_t *aa = (*(board_cell_t **) a); return (bb->rating[0] + bb->chip_rating) - (aa->rating[0] + aa->chip_rating); } /** * Add a bounding to the successors. */ void bound_successors(board_t *board) { int i; int j; const int max_bound = BOUND_BOX_EXTEND; board_cell_t *cell; top = BOARD_LENGTH; right = 0; bottom = 0; left = BOARD_LENGTH; /* get the bounding box */ for(cell = &(board->cells[0][0]), i = 0; i < BOARD_LENGTH; ++i) { for(j = 0; j < BOARD_LENGTH; ++j, ++cell) { if(NO_PLAYER != cell->player_id) { top = MIN(i, top); right = MAX(j, right); bottom = MAX(i, bottom); left = MIN(i, left); } } } /* extend the bounding box by BOUND_BOX_EXTEND cells on each side */ top = MAX(0, top - max_bound); right = MIN(BOARD_LENGTH - 1, right + max_bound); bottom = MIN(BOARD_LENGTH - 1, bottom + max_bound); left = MAX(0, left - max_bound); } /** * Fill an ordered cell sequence with the most import MAX_SUCCESSORS_TO_SEARCH * cells in the board. * * This function also returns the average of all importance ratings. */ void gen_successors(board_t *board, ordered_cell_seq_t *seq, const player_t player_id) { int i; int j; int len = 0; board_cell_t **each = &(seq->cells[0]); board_cell_t *cell; /* get pointers to all empty cells within the extended bounded box. */ for(cell = &(board->cells[0][0]), i = 0; i < BOARD_LENGTH; ++i) { for(j = 0; j < BOARD_LENGTH; ++j, ++cell) { if(NO_PLAYER == cell->player_id && i <= bottom && i >= top && j <= right && j >= left) { *(each++) = cell; ++len; } } } /* sort the cell pointers according to the cell importance rating */ which_player = player_id; qsort( &(seq->cells[0]), (size_t) len, sizeof(board_cell_t *), (NO_PLAYER == player_id) ? &compare_cell_ratings : &compare_cell ); seq->len = len; seq->cells[len] = NULL; /* add in the trailing null */ }
C
int solution(int A, int B, int K) { // write your code in C99 (gcc 6.2.0) int i; int divisible = 0; for(i=A; i<B+1; i++){ if(i%K == 0) divisible++; } return divisible; } // https://app.codility.com/demo/results/trainingFJYN4Y-RJN/ int solution(int A, int B, int K) { // write your code in C99 (gcc 6.2.0) int i; int divisible = 0; if(B<K){ if(A == 0) return 1; else return 0; } for(i=A; i<B+1; i++){ if(i==0) divisible++; else if(i<K) continue; if(i%K == 0) divisible++; } return divisible; }
C
#include <stdlib.h> #include <string.h> #include "out/liblokatt/filter-lexer.h" #include "filter.h" #include "lokatt.h" #include "stack.h" struct lokatt_filter { unsigned int event_bitmask; struct token *tokens; size_t token_count; struct token **rpn; size_t rpn_count; }; /* Replace any pair of chars '\x' with 'x'. */ static void unescape(char *str) { char *end = str + strlen(str); while (str < end) { if (*str == '\\') { char *p = str; while (p < end) { *p = *(p + 1); p++; } end--; } str++; } } #define is_key(type) \ ((type) == TOKEN_KEY_PID || (type) == TOKEN_KEY_TID || \ (type) == TOKEN_KEY_SEC || (type) == TOKEN_KEY_NSEC || \ (type) == TOKEN_KEY_LEVEL || (type) == TOKEN_KEY_TAG || \ (type) == TOKEN_KEY_TEXT) #define is_value(type) \ ((type) == TOKEN_VALUE_INT || (type) == TOKEN_VALUE_STRING) #define is_logical_operator(type) \ ((type) == TOKEN_OP_AND || (type) == TOKEN_OP_OR) #define is_operator(type) \ ((type) == TOKEN_OP_EQ || (type) == TOKEN_OP_NE || \ (type) == TOKEN_OP_LT || (type) == TOKEN_OP_LE || \ (type) == TOKEN_OP_GT || (type) == TOKEN_OP_GE || \ (type) == TOKEN_OP_MATCH || (type) == TOKEN_OP_NMATCH || \ is_logical_operator(type)) #define precedence_is_le(type1, type2) \ ((type1) / 10 <= (type2) / 10) int filter_tokenize(const char *input, struct token **out, size_t *out_size) { yyscan_t scanner; YY_BUFFER_STATE handle; int pos = 1; struct stack stack; *out_size = 0; stack_init(&stack, sizeof(struct token)); yylex_init(&scanner); handle = yy_scan_string(input, scanner); for (;;) { int status; status = yylex(scanner); if (status == 0) goto success; if (status < 0) goto failure; if (status == TOKEN_WHITESPACE) { /* do nothing */ } else if (status == TOKEN_VALUE_INT) { struct token *t; t = stack_push(&stack); t->type = TOKEN_VALUE_INT; t->value_int = atoi(yyget_text(scanner)); } else if (status == TOKEN_VALUE_STRING) { struct token *t; char *text; text = strdup(yyget_text(scanner)); /* remove trailing quote ... */ text[strlen(text) - 1] = '\0'; unescape(text + 1); t = stack_push(&stack); t->type = TOKEN_VALUE_STRING; strbuf_init(&t->value_string, strlen(text)); /* ... and don't add leading quote */ strbuf_addstr(&t->value_string, text + 1); free(text); } else { struct token *t; t = stack_push(&stack); t->type = status; } pos += yyget_leng(scanner); if (status != TOKEN_WHITESPACE) *out_size += 1; } success: yy_delete_buffer(handle, scanner); yylex_destroy(scanner); *out = (struct token *)stack.data; return 0; failure: yy_delete_buffer(handle, scanner); yylex_destroy(scanner); free(stack.data); *out = NULL; *out_size = 0; return pos; } void filter_free_tokens(struct token *tokens, size_t size) { size_t i; for (i = 0; i < size; i++) { struct token *t = &tokens[i]; if (t->type == TOKEN_VALUE_STRING) strbuf_destroy(&t->value_string); } free(tokens); } static int shunting_yard(const struct token *tokens, size_t token_count, struct stack *out) { size_t i; struct stack stack; int retval = 0; stack_init(&stack, sizeof(struct token *)); for (i = 0; i < token_count; i++) { const struct token *t = &tokens[i]; if (is_operator(t->type)) { const struct token **p; while (stack.current_size > 0) { const struct token **q; q = stack_top(&stack); if (precedence_is_le(t->type, (*q)->type)) { stack_pop(&stack); p = stack_push(out); *p = *q; } else { break; } } p = stack_push(&stack); *p = t; } else if (t->type == TOKEN_OP_LPAREN) { const struct token **p; p = stack_push(&stack); *p = t; } else if (t->type == TOKEN_OP_RPAREN) { int done = 0; while (stack.current_size > 0) { const struct token **p; const struct token **q; q = stack_top(&stack); stack_pop(&stack); if ((*q)->type == TOKEN_OP_LPAREN) { done = 1; break; } p = stack_push(out); *p = *q; } if (!done) { retval = -1; goto bail; } } else { const struct token **p; p = stack_push(out); *p = t; } } while (stack.current_size > 0) { const struct token **p; const struct token **q; p = stack_top(&stack); if ((*p)->type == TOKEN_OP_LPAREN) { retval = -1; goto bail; } stack_pop(&stack); q = stack_push(out); *q = *p; } bail: stack_destroy(&stack); return retval; } int filter_tokens_as_rpn(const struct token *tokens, size_t token_count, struct token ***out, size_t *out_size) { int retval = 0; struct stack rpn; stack_init(&rpn, sizeof(struct token *)); retval = shunting_yard(tokens, token_count, &rpn); if (retval == 0) { *out = (struct token **)rpn.data; *out_size = rpn.current_size; } else { stack_destroy(&rpn); *out = NULL; *out_size = 0; } return retval; } struct lokatt_filter *lokatt_create_filter(unsigned int event_bitmask, const char *spec) { static struct lokatt_message dummy_msg = { .pid = 0, .tid = 0, .sec = 0, .nsec = 0, .level = LEVEL_ASSERT, .tag = "", .text = "", }; struct lokatt_filter *f = calloc(1, sizeof(*f)); if (spec) { if (filter_tokenize(spec, &f->tokens, &f->token_count)) goto bail; if (filter_tokens_as_rpn(f->tokens, f->token_count, &f->rpn, &f->rpn_count)) goto bail; /* check for syntax error, eg "tag == tag" */ if (filter_match_message(f, &dummy_msg) == -1) goto bail; } f->event_bitmask = event_bitmask; return f; bail: lokatt_destroy_filter(f); return NULL; } void lokatt_destroy_filter(struct lokatt_filter *f) { free(f->rpn); filter_free_tokens(f->tokens, f->token_count); free(f); } static int get_int(const struct token *t, const struct lokatt_message *msg, int32_t *out) { switch (t->type) { case TOKEN_KEY_PID: *out = msg->pid; return 0; case TOKEN_KEY_TID: *out = msg->tid; return 0; case TOKEN_KEY_SEC: *out = msg->sec; return 0; case TOKEN_KEY_NSEC: *out = msg->nsec; return 0; case TOKEN_KEY_LEVEL: *out = msg->level; return 0; default: return -1; } } static int get_string(const struct token *t, const struct lokatt_message *msg, const char **out) { switch (t->type) { case TOKEN_KEY_TAG: *out = msg->tag ? msg->tag : ""; return 0; case TOKEN_KEY_TEXT: *out = msg->text ? msg->text : ""; return 0; default: return -1; } } static int evaluate_eq(const struct token *left, const struct token *right, const struct lokatt_message *msg, int *out) { if (!is_key(left->type)) return -1; if (!is_value(right->type)) return -1; if (right->type == TOKEN_VALUE_INT) { int32_t value; if (get_int(left, msg, &value)) return -1; *out = value == right->value_int; return 0; } else { const char *str; if (get_string(left, msg, &str)) return -1; *out = !strcmp(str, right->value_string.buf); return 0; } } static int evaluate_lt(const struct token *left, const struct token *right, const struct lokatt_message *msg, int *out) { int32_t value; if (!is_key(left->type)) return -1; if (right->type != TOKEN_VALUE_INT) return -1; if (get_int(left, msg, &value)) return -1; *out = value < right->value_int; return 0; } /* * Return value: * - '0': match * - '> 0': no match * - '< 0': internal error */ int filter_match_message(const struct lokatt_filter *f, const struct lokatt_message *msg) { static const struct token TRUE = { .type = TOKEN_TRUE, }; static const struct token FALSE = { .type = TOKEN_FALSE, }; struct stack stack; const struct token *t; const struct token **p; int retval = -1; stack_init(&stack, sizeof(struct token *)); for (size_t i = 0; i < f->rpn_count; i++) { t = f->rpn[i]; if (is_operator(t->type)) { struct token **left, **right; int a, b; if (stack.current_size < 2) goto bail; right = stack_top(&stack); stack_pop(&stack); left = stack_top(&stack); stack_pop(&stack); switch (t->type) { case TOKEN_OP_EQ: if (evaluate_eq(*left, *right, msg, &a)) goto bail; t = a ? &TRUE : &FALSE; break; case TOKEN_OP_NE: if (evaluate_eq(*left, *right, msg, &a)) goto bail; t = !a ? &TRUE : &FALSE; break; case TOKEN_OP_LT: if (evaluate_lt(*left, *right, msg, &a)) goto bail; t = a ? &TRUE : &FALSE; break; case TOKEN_OP_LE: if (evaluate_lt(*left, *right, msg, &a)) goto bail; if (evaluate_eq(*left, *right, msg, &b)) goto bail; t = a || b ? &TRUE : &FALSE; break; case TOKEN_OP_GT: if (evaluate_lt(*left, *right, msg, &a)) goto bail; if (evaluate_eq(*left, *right, msg, &b)) goto bail; t = !a && !b ? &TRUE : &FALSE; break; case TOKEN_OP_GE: if (evaluate_lt(*left, *right, msg, &a)) goto bail; t = !a ? &TRUE : &FALSE; break; case TOKEN_OP_AND: if (*right != &TRUE && *right != &FALSE) goto bail; if (*left != &TRUE && *left != &FALSE) goto bail; a = *left == &TRUE; b = *right == &TRUE; t = a && b ? &TRUE : &FALSE; break; case TOKEN_OP_OR: if (*right != &TRUE && *right != &FALSE) goto bail; if (*left != &TRUE && *left != &FALSE) goto bail; a = *left == &TRUE; b = *right == &TRUE; t = a || b ? &TRUE : &FALSE; break; default: goto bail; } } p = stack_push(&stack); *p = t; } if (stack.current_size != 1) goto bail; p = stack_top(&stack); if (*p == &TRUE) retval = 0; else if (*p == &FALSE) retval = 1; bail: stack_destroy(&stack); return retval; } int lokatt_filter_match(const struct lokatt_filter *f, const struct lokatt_event *event) { if (!(f->event_bitmask & event->type)) return 0; if ((event->type & EVENT_LOGCAT_MESSAGE) && f->token_count) return filter_match_message(f, &event->msg) == 0; return 1; }
C
/****************************************************************************** * This code is part of the NetDsn project by A. Frangioni, C. Gentile, * E. Grande and A. Pacifici * * This program produces a randomly-generated .par file to be fed to netgen. * * Claudio Gentile, May 28, 2009 * ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> void wait( int seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC; while( clock() < endwait ) {} } int main(int argc , char** argv) { if( argc < 6 ) { printf("Usage is: ./pargen m rho k cf cq s\n"); return( 1 ); } int n, m, seed, rho_par, i, k; double rho, sum; int MAXVAL; FILE *fin, *fout ; double *weight, *weight2; char filename[ 100 ]; time_t seconds; m = atoi( argv[ 1 ] ); rho_par = atoi(argv[ 2 ] ); if( rho_par == 1 ) rho = 0.25; else if( rho_par == 2 ) rho = 0.5; else if( rho_par == 3 ) rho = 0.75; else { printf( "Error in parameter 'rho' of pargen.\n" ); exit( 1 ); } double temp = ( 1.0 + sqrt( 1.0 + ( 8.0 * m ) / rho ) ) / 2; n = floor( temp ); wait( 2 ); seconds = time( NULL ); srand( seconds ); sprintf( filename , "netgen-%s-%s-%s-%s-%s-%s.par" , argv[1] , argv[2] , argv[3] , argv[4] , argv[5] , argv[6] ); fout = fopen(filename,"w"); // seme per netgen // attesa per generare numeri correttamente fprintf( fout , "%d\n", rand() ); // numero istanza fprintf( fout , "1 " ); // numero nodi fprintf( fout , "%d ", n ); // source and sink nodes int max_nodes = 0.1 * n; int num = rand() % max_nodes + 1; fprintf( fout , "%d ", num ); num = rand() % max_nodes + 1; fprintf( fout , "%d ", num ); // numero archi fprintf( fout , "%d ", m ); // min_cost e max_cost, ovvero il minimo e massimo b_ij fprintf( fout , "1 " ); //min cost = 1 num = rand() % 99 + 10; fprintf( fout , "%d " , num ); // total supply num = rand() % 900 + 100; fprintf( fout , "%d " , num ); // dati per il transshipment (costanti) fprintf( fout , "0 0 0 100 " ); // capacità u_min e u_max (ricorda che num = total supply in quedto punto) int num1 = 0.05 * num; int num2 = 0.05 * num; int num3 = rand() % num2 + num1; fprintf( fout , "%d " , num3 ); num1 = 0.2 * num; num2 = 0.4 * num - num1; num3 = rand() % num2 + num1; if( argv[ 6 ] == "s" ) num3 = num3 * 0.7; fprintf( fout , "%d " , num3 ); fclose( fout ); return( 0 ); }
C
#include <stdbool.h> #include <stdint.h> #include <stdlib.h> /* my god PNG is stupid. */ #define PNG_USER_MEM_SUPPORTED 1 #include <png.h> bool writepng(const char* filename, const uint16_t* buf, uint32_t width, uint32_t height) { png_structp png=NULL; png_infop info=NULL; FILE* fp = fopen(filename, "w+b"); if(!fp) { perror("err"); return false; } png = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL, NULL, NULL, NULL); if(png == NULL) { fclose(fp); return false; } info = png_create_info_struct(png); if(info == NULL) { fclose(fp); png_destroy_write_struct(&png, (png_infopp)NULL); return false; } /* png error handling *nonsense* */ if(setjmp(png_jmpbuf(png))) { fclose(fp); png_destroy_write_struct(&png, &info); return false; } png_init_io(png, fp); png_set_IHDR(png, info, width, height, 16, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png, info); for(uint32_t y=0; y < height; ++y) { png_write_row(png, (png_bytep) (buf + y*width)); } png_write_end(png, NULL); fclose(fp); png_destroy_write_struct(&png, &info); return true; } bool readpng(const char* filename, uint8_t** buf, uint32_t* width, uint32_t* height) { FILE* fp = fopen(filename, "rb"); if(!fp) { perror("opening file"); return false; } const size_t header_bytes = 7; uint8_t header[header_bytes]; if(fread(header, 1, header_bytes, fp) != header_bytes) { perror("reading header"); fclose(fp); return false; } if(png_sig_cmp(header, 0, header_bytes) != 0) { fprintf(stderr, "'%s' is not a png file.\n", filename); fclose(fp); return false; } png_structp png = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ); if(!png) { fprintf(stderr, "could not create read struct.\n"); fclose(fp); return false; } png_infop info = png_create_info_struct(png); if(!info) { fprintf(stderr, "could not create info struct.\n"); png_destroy_read_struct(&png, NULL, NULL); fclose(fp); return false; } png_infop endinfo = png_create_info_struct(png); if(!endinfo) { fprintf(stderr, "could not create info struct.\n"); png_destroy_read_struct(&png, &info, NULL); fclose(fp); return false; } if(setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &info, &endinfo); fclose(fp); return false; } png_init_io(png, fp); png_set_sig_bytes(png, header_bytes); png_read_info(png, info); png_uint_32 w, h; int depth, ctype; png_get_IHDR(png, info, &w, &h, &depth, &ctype, NULL, NULL, NULL); if(ctype != PNG_COLOR_TYPE_GRAY) { fprintf(stderr, "this function only handles grayscale images\n"); png_destroy_read_struct(&png, &info, &endinfo); fclose(fp); } uint8_t bgcolor=0; if(png_get_valid(png, info, PNG_INFO_bKGD)) { png_color_16p bg; png_get_bKGD(png, info, &bg); if(ctype == PNG_COLOR_TYPE_GRAY && depth == 8) { bgcolor = bg->gray; } } *width = (uint32_t) w; *height = (uint32_t) h; if(depth < 8) { /* if the depth is less than 8 bits, have libpng expand it. */ png_set_expand(png); } else if(depth == 16) { /* likewise, if it's 16 bit, have libpng quantize it. Probably not the * best idea, but... eh. It'll work for now. */ fprintf(stderr, "[WARNING] quantizing 16bit -> 8bit\n"); png_set_strip_16(png); } png_read_update_info(png, info); png_uint_32 rowbytes; rowbytes = png_get_rowbytes(png, info); if(rowbytes != w) { fprintf(stderr, "Rowbytes and width not equal..\n"); png_destroy_read_struct(&png, &info, &endinfo); fclose(fp); return false; } /* allocate buffer and fill it with the background color. */ *buf = malloc(sizeof(uint8_t) * w * h); memset(*buf, (int)bgcolor, rowbytes*h); if(((unsigned)(png_get_channels(png, info))) != 1) { fprintf(stderr, "too many channels, this should be grayscale!\n"); free(*buf); png_destroy_read_struct(&png, &info, &endinfo); fclose(fp); return false; } /* setup PNGs stupid row pointers (it can't read into one large array) */ png_bytep* row_pointers = calloc(h, sizeof(png_bytep)); for(png_uint_32 i=0; i < h; ++i) { row_pointers[i] = (png_bytep)((*buf) + i * rowbytes); } png_read_image(png, row_pointers); png_read_end(png, NULL); free(row_pointers); png_destroy_read_struct(&png, &info, &endinfo); fclose(fp); return true; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> strEnd (char *str, char *t) { char *p; p = str + strlen(str) - strlen(t); /* p aponta para o final da string str - tamanho de t */ while (*t){ if (*p != *t) return 0; p++; t++; } return 1; } int main(int argc, char** argv) { char str1[40] = "teste"; char str2[40] = "teste"; strEnd(&str1, &str2); printf("String: %s\n", str1); }
C
#include <stdio.h> #define num 100 int main() { int i; printf("Hello world!\n"); for (i = num; i > 0; i--) { printf("%i ", i); } printf("\n"); printf("START"); return 0; }
C
/* Copyright (c) 1986 AT&T */ /* All Rights Reserved */ /* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T */ /* The copyright notice above does not evidence any */ /* actual or intended publication of such source code. */ /* This module is created for NLS on Sep.03.86 */ #ident "@(#)wschr.c 1.6 93/12/01 SMI" /* from JAE2.0 1.0 */ /* * Return the ptr in sp at which the character c appears; * Null if not found. */ #include <stdlib.h> #include <wchar.h> #pragma weak wcschr = _wcschr #pragma weak wschr = _wschr #ifndef WNULL #define WNULL (wchar_t *)0 #endif wchar_t * _wcschr(const wchar_t *sp, wchar_t c) { do { if (*sp == c) return ((wchar_t *)sp); /* found c in sp */ } while (*sp++); return (WNULL); /* c not found */ } wchar_t * _wschr(const wchar_t *sp, wchar_t c) { return (wcschr(sp, c)); }
C
#include "gba.h" #include "player.h" #include "sprites_id.h" #include <stdlib.h> #include <stdbool.h> #define MASK_NUM_MAX 20 #define MASK_PADDING 16 typedef struct { int id; int xPos; int yPos; bool collected; } Mask; typedef struct { Mask freeMasks[MASK_NUM_MAX]; int length; } Masks; void InitMasks(Masks *masks) { masks->length = 0; } void addMask(Masks *m) { Mask *newMask = &m->freeMasks[m->length]; newMask->id = MASK_INITIAL_ID + m->length; newMask->xPos = ((rand() % 224) + 1); //minimum x pos is 0, max is 224 newMask->yPos = ((rand() % 144) + 1); //minimum y pos is 0. max is 145 newMask->collected = false; m->length++; } void maskCollisionWithPlayer(Masks *m) { int i; for (i = 0; i < m->length; i++) { Mask *currentMask = &m->freeMasks[i]; // check for horizontal collision if ((PLAYER_XPOS >= currentMask->xPos && PLAYER_XPOS <= currentMask->xPos + MASK_PADDING) || (PLAYER_XPOS + PLAYER_PADDING >= currentMask->xPos && PLAYER_XPOS + PLAYER_PADDING <= currentMask->xPos + MASK_PADDING)) { // check for vertical collision if ((PLAYER_YPOS >= currentMask->yPos && PLAYER_YPOS <= currentMask->yPos + MASK_PADDING) || (PLAYER_YPOS + PLAYER_PADDING >= currentMask->yPos && PLAYER_YPOS + PLAYER_PADDING <= currentMask->yPos + MASK_PADDING)) { if (!currentMask->collected) { PLAYER_COLLECTED_MASKS++; currentMask->collected = true; } } } } }
C
#include <stdio.h> #include "ev/reduce.h" #include "measure/measure.h" #include "consts.h" #define BACKTRACKING_MAXIMUM (20) uint32_t backtrack_count = 0; bool reduce_eviction_set_rec(node *sentinel, uint32_t length, uintptr_t evictee); bool reduce_eviction_set(node *sentinel, uint32_t length, uintptr_t evictee) { backtrack_count = 0; return reduce_eviction_set_rec(sentinel, length, evictee); } bool reduce_eviction_set_rec(node *sentinel, uint32_t length, uintptr_t evictee) { if (length == CACHE_ASSOCIATIVITY) return true; #define N (CACHE_ASSOCIATIVITY + 1) uint32_t advance_ceil = (length + N - 1) / N; uint32_t advance_floor = length / N; uint32_t advance = advance_ceil; node *chain_start; node *chain_end = sentinel; for (uint32_t i = 0; i < N; i++) { if (i == (length % N)) advance = advance_floor; if (advance == 0) continue; chain_start = chain_end->next; chain_end = node_advance(chain_start, advance - 1); node *link_point = chain_start->prev; node_unlink_chain(chain_start, chain_end); // TODO: allow specifying a different probe function. if (rdtsc_measure_metadata.probe(sentinel->next, evictee)) { #ifdef REDUCE_DBG printf("Going in with %d at idx %d\n", length - advance, i); #endif if (reduce_eviction_set_rec(sentinel, length - advance, evictee)) return true; if (backtrack_count >= BACKTRACKING_MAXIMUM) { return false; } } #ifdef REDUCE_DBG else { printf("Not going in..\n"); } #endif node_link_chain(link_point, chain_start, chain_end); } backtrack_count++; #ifdef REDUCE_DBG printf("backtracking... %d\n", backtrack_count); if (backtrack_count == BACKTRACKING_MAXIMUM) { printf("Reached max with size %d\n", length); } #endif return false; }
C
#define _XOPEN_SOURCE 700 // required for barriers to work #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <semaphore.h> int main(void) { pid_t childp; childp = fork(); int status; if (childp==0) { sleep(1); printf("Child process\n"); exit(0); } else { waitpid(childp, &status, 0); printf("Parent Process\n"); } }
C
#include<stdio.h> void del(char s[],int n) { int i; for(i=n;s[i+1]!='\0';i++) { s[i]=s[i+1]; } s[i]='\0'; } int main() { char a[200]; scanf("%s",a); int i,j; for(i=0;a[i]!='\0';i++) { for(j=i;a[j+1]!='\0';j++) { if(a[i]==a[j+1]) { del(a,j+1); j--; } } } printf("%s\n",a); return 0; }
C
#include <string.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> char str1[7] = "aabbcc"; int main (void) { char nig [] = "bullet to back" ; printf ("first %s\n", nig); memset (nig, '*', 6); printf ("second %s\n", nig); unsigned char src[7]= "123456"; unsigned char dst[10]= ""; memcpy (dst, src, 6); printf ("dst: %s\n",dst); const char src2[50] = "http://www.tutorialspoint.com"; char dest[50]; strcpy(dest,"Heloooo!!"); printf("Before memcpy dest = %s\n", dest); memcpy(dest, src2, strlen(src2)+1); printf("After memcpy dest = %s\n", dest); char str6 [11]="0123456789"; //Определение длины строки и вывод результата на консоль printf ("Длина строки «%s» - %ld символов\n", str6, strlen (str6) ); /* printf( "The string: %s\n", str1 ); memcpy( str1 + 2, str1, 2 ); printf( "New string: %s\n", str1 ); strcpy_s( str1, sizeof(str1), "aabbcc" ); // reset string printf( "The string: %s\n", str1 ); memmove( str1 + 2, str1, 4 ); printf( "New string: %s\n", str1 );*/ char * src1 = "This is the source string"; char dest1[70]; char *ptr; ptr = memccpy(dest1,src1,'g',strlen(src1)); if(ptr)//? { *ptr = '\0'; printf("Был найден символ %s\n",dest1); } else printf("Символ не найден\n"); unsigned char src31[15] = "1234567890" ; char *sym; printf ("src old: %s\n",src31); sym = memchr (src31, '4', 10); if (sym != NULL) sym[0]='!'; printf ("src new memchr: %s\n",src31); // Исходная строка char str5 [11]= "0123456789"; // Переменная, в которую будет помещен указатель на дубликат строки char *istr1; // Дублирование строки istr1 = strdup (str5); // Вывод дубликата на консоль printf ("Дубликат: %s\n", istr1); // Очищаем память, выделенную под дубликат free (istr1); // Массив источник данных char src32[1024]="первая строка\0вторая строка"; // Массив приемник данных char dst32[1024]=""; // Копируем строку из массива src в массив dst. Обратите внимание, //что скопируется только строка «первая строка\0». strcpy (dst32, src32); // Вывод массива src на консоль printf ("src: %s %s\n",src32, &src32[14]); // Вывод массива dst на консоль printf ("dst: %s %s\n",dst32, &dst32[14]); char str11[15]; char str21[15]; int ret; memcpy(str11, "abcdef", 6); memcpy(str21, "ABCDEF", 6); ret = memcmp(str11, str21, 5); if(ret > 0) { printf("str2 is less than str1\n"); } else if(ret < 0) { printf("str1 is less than str2"); } else { printf("str1 is equal to str2"); } char strn [11]= "0123456789"; char *istrn; istrn = strdup (strn); printf ("Дубликат: %s\n", istrn); free (istrn); char app[1024]="вторая строка"; char bst[1024]="первая строка"; strcat (bst, app); printf ("bst: %s\n",bst); char strq [11]="0123456789"; // Код искомого символа int ch = '6'; // Указатель на искомую переменную в строке, // по которой осуществляется поиск. char *ach; // Ищем символ ‘6’ ach=strchr (strq,ch); if (ach==NULL) printf ("Символ в строке не найден\n"); else printf ("Искомый символ в строке на позиции # %ld\n",ach-strq+1); // Массив со строкой для поиска char str111 [11]="0123456789"; // Набор символов, которые должны входить в искомый сегмент char str222 [10]="345"; // Переменная, в которую будет занесен адрес первой найденной строки char *istr111; //Поиск строки istr1 = strstr (str111,str222); //Вывод результата поиска на консоль if ( istr1 == NULL) printf ("Строка не найдена\n"); else printf ("Искомая строка начинается с символа %ld\n",istr1-str111+1); char strw1[1024]="12345"; char strw2[1024]="12305"; // Сравниваем две строки if (strcmp (strw1, strw2)==0) puts ("Строки идентичны"); else puts ("Строки отличаются"); char *Stre = "652.23brrt"; //Строка для преобразования int Num=0; //Переменная для записи результата //Преобразование строки в число типа int Num = atoi (Stre); //Вывод результата преобразования printf ("%d\n",Num); char str211 [11]="0123456789"; //Определение длины строки и вывод результата на консоль printf ("Длина строки «%s» - %ld символов\n", str211, strlen (str211) ); char a; a = 'Q'; printf("\nResult when uppercase alphabet is passed: %d", isalpha(a)); a = 'q'; printf("\nResult when lowercase alphabet is passed: %d", isalpha(a)); a='+'; printf("\nResult when non-alphabetic character is passed: %d\n", isalpha(a)); char v = 'C'; if(isascii(v)) printf("%c - is ascii\n",v); else printf("%c - isn't ascii\n",v); return 0; }
C
#include<stdio.h> int main() { int n,k,minimum,i; scanf("%d%d",&n,&k); int arr[n]; { for(i=0;i<n;i++) { scanf("%d",&arr[i]); } minimum=arr[0]; for(i=0;i<n;i++) { if(arr[i]<minimum) { minimum=arr[i]; } } printf("d",arr[k]); return 0; }
C
#ifndef buffer_h #define buffer_h #include <stdint.h> #include <stdbool.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef struct buffer_t buffer_t; //typedef buffer_t* buf_handle_t; // typedef uint8_t (*available)(buf_handle_t); /* Types */ //typedef unsigned int size_t; struct buffer_t { uint8_t* buffer; size_t read_index; // head of array -> start reading from here. size_t fill_index; // next available byte to write to // uint8_t size; size_t capacity; // bool full; }; /** * To be called from the FifteenDotFour::available member function; determine * the number of bytes available in the buffer to be read. This is done by * calculating the space between the write pointer ahead of the read pointer. * * @param buf Pass by pointer; address f buffer struct * @return Number of bytes available in the buffer */ size_t buffer_get_size(buffer_t* buf); /** * Initialize and fill a default buffer structure along with statically * allocate the space for the buffer array (RX154_MAX_BUFF_SIZE), fill * memory with zeroes. Set read and write pointers to index 0. * * @return pointer to the buffer structure */ bool buffer_init(buffer_t* buf, size_t capacity); /** * Clear the data that is in the buffer array by filling the space with all 0's * Reset the read and write pointers. * * @param buf Pass by pointer; address of buffer struct */ void buffer_flush(buffer_t* buf); /** * Free the buffer array. Never call on embedded systems for contiguous memory. * * @param buf Pass by pointer; address of buffer struct */ void buffer_free(buffer_t* buf); /** * Return the first value at the read index w/out popping and incrementing * read index * @param buf Pass by pointer; address of buffer struct * @return Front of buffer */ uint8_t buffer_peek(buffer_t* buf); /** * Pop one byte off the top of the buffer queue if there are bytes available * Move over the read pointer by one byte (one index) * Return -1 if no bytes available and none read. * * @param buf Pass by pointer; address of buffer struct * @return Byte value copied into rx_buffer */ int16_t buffer_read(buffer_t* src_buf); /** * Pop a specificed amount of bytes off the top of the buffer queue of available. * Move the read pointer over by the amount of bytes poped. * Return -1 if no bytes were available and none read. * * @param buf_handle_buf Pass by pointer; address of buffer struct * @return Number of read bytes; copied into dest_buf */ uint8_t buffer_read_multiple(uint8_t* dest_buf, buffer_t* src_buf, size_t r_size); /* Read one byte if available */ /** * Write a single byte to the destination buffer; checking if there is enough * space inside of the buffer first and then copying over the single byte. * * @param dest_buf Destination buffer struct * @param write_byte Byte to be written * @return Number of bytes written to tx_buffer (1/0) */ size_t buffer_write(buffer_t* dest_buf, const uint8_t write_byte); /** * Take bytes from source buffer and copy to destination buffer. Handles transfer * of data from MAC layer to APP. * * @param src_buf Pass by pointer * @param dest_buf Pass by pointer * @param w_size Length of data * @return Number of bytes written to tx_buffer */ size_t buffer_write_multiple(buffer_t* dest_buf, const uint8_t* src_arr, size_t w_size); /** * For app layer testing and debugging. Print the buffer array. Implemented * to minmic the output of printing an array for visualization in python. * * @param buf Buffer to print from */ void buffer_print(buffer_t* buf); /** * For app layer testing and debugging. Call buffer_print and display other * buffer_t structure data. * * @param buf Buffer to display data for */ void print_buffer_stats(buffer_t* buf); #ifdef __cplusplus } #endif #endif
C
/* ** my_is_prime.c for in /home/menich_a/rendu/Piscine-C-lib ** ** Made by menich_a ** Login <[email protected]> ** ** Started on Tue Oct 8 13:46:55 2013 menich_a ** Last update Tue Oct 8 14:04:00 2013 menich_a */ int my_is_prime(int nb) { int i; i = 2; if (nb <= 0 || nb == 1) { return (0); } while (i < nb) { if (nb % i == 0) { return (0); } i = i + 1; } return (1); }
C
/* phase5.c Students: Veronica Reeves Thai Pham University of Arizona Computer Science 452 Summary: implement a virtual memory (VM) system that supports demand paging. The USLOSS MMU is used to configure a region of virtual memory whose contents are process-specific. Using the USLOSS MMU to implement the virtual memory system. The basic idea is to use the MMU to implement a single-level page table, so that each process will have its own page able for the VM region and will therefore have its own view of what the VM region contains. */ #include <usloss.h> #include <usyscall.h> #include <assert.h> #include <phase1.h> #include <phase2.h> #include <phase3.h> #include <phase4.h> #include <phase5.h> #include <libuser.h> #include <providedPrototypes.h> #include <vm.h> #include <string.h> int r; static int Pager(char *buf); void printPageTable(int pid); extern void mbox_create(USLOSS_Sysargs *args_ptr); extern void mbox_release(USLOSS_Sysargs *args_ptr); extern void mbox_send(USLOSS_Sysargs *args_ptr); extern void mbox_receive(USLOSS_Sysargs *args_ptr); extern void mbox_condsend(USLOSS_Sysargs *args_ptr); extern void mbox_condreceive(USLOSS_Sysargs *args_ptr); Process processes[MAXPROC]; FTEptr frameTable; DTEptr diskTable; int pagerPID[MAXPAGERS]; // pager pids int clockhand, clockhandMbox; void* vmRegion = NULL; // adress of the beginning of the VM FaultMsg faults[MAXPROC]; /* Note that a process can have only * one fault at a time, so we can * allocate the messages statically * and index them by pid. */ int faultMbox; VmStats vmStats; static void FaultHandler(int type, void * offset); static void vmInit(USLOSS_Sysargs *sysargs); void *vmInitReal(int mappings, int pages, int frames, int pagers); static void vmDestroy(USLOSS_Sysargs *USLOSS_SysargsPtr); void vmDestroyReal(void); void setUserMode(); /* *---------------------------------------------------------------------- * * start4 -- * * Initializes the VM system call handlers. * * Results: * MMU return status * * Side effects: * The MMU is initialized. * *---------------------------------------------------------------------- */ int start4(char *arg) { int pid; int result; int status; /* to get user-process access to mailbox functions */ systemCallVec[SYS_MBOXCREATE] = mbox_create; systemCallVec[SYS_MBOXRELEASE] = mbox_release; systemCallVec[SYS_MBOXSEND] = mbox_send; systemCallVec[SYS_MBOXRECEIVE] = mbox_receive; systemCallVec[SYS_MBOXCONDSEND] = mbox_condsend; systemCallVec[SYS_MBOXCONDRECEIVE] = mbox_condreceive; /* user-process access to VM functions */ systemCallVec[SYS_VMINIT] = vmInit; systemCallVec[SYS_VMDESTROY] = vmDestroy; // Initialize the phase 5 process table // Initialize other structures as needed result = Spawn("Start5", start5, NULL, 8*USLOSS_MIN_STACK, 2, &pid); if (result != 0) { USLOSS_Console("start4(): Error spawning start5\n"); Terminate(1); } result = Wait(&pid, &status); if (result != 0) { USLOSS_Console("start4(): Error waiting for start5\n"); Terminate(1); } Terminate(0); return 0; // not reached } /* start4 */ /* *---------------------------------------------------------------------- * * VmInit -- * * Stub for the VmInit system call. * * Results: * None. * * Side effects: * VM system is initialized. * *---------------------------------------------------------------------- */ static void vmInit(USLOSS_Sysargs *sysargs){ CheckMode(); int mappings = (int)(long)sysargs->arg1, pages = (int)(long)sysargs->arg2, frames = (int)(long)sysargs->arg3, pagers = (int)(long)sysargs->arg4; sysargs->arg1 = vmInitReal(mappings, pages, frames, pagers); if ((int)(long)sysargs->arg1 < 0) sysargs->arg4 = sysargs->arg1; else sysargs->arg4 = (void*)(long)0; setUserMode(); } /* vmInit */ /* *---------------------------------------------------------------------- * * vmDestroy -- * * Stub for the VmDestroy system call. * * Results: * None. * * Side effects: * VM system is cleaned up. * *---------------------------------------------------------------------- */ static void vmDestroy(USLOSS_Sysargs *USLOSS_SysargsPtr){ CheckMode(); vmDestroyReal(); } /* vmDestroy */ /* *---------------------------------------------------------------------- * * vmInitReal -- * * Called by vmInit. * Initializes the VM system by configuring the MMU and setting * up the page tables. * * Results: * Address of the VM region. * * Side effects: * The MMU is initialized. * *---------------------------------------------------------------------- */ void *vmInitReal(int mappings, int pages, int frames, int pagers){ int status; int dummy; int i; CheckMode(); if (vmRegion > 0){ if (DEBUG5) USLOSS_Console("vmInitReal: vmRegion already initialized\n"); return (void*)(long)-2; } if (mappings != pages){ if (DEBUG5) USLOSS_Console("vmInitReal: Mappings and pages are not equal.\n"); return (void*)(long)-1; } status = USLOSS_MmuInit(mappings, pages, frames, USLOSS_MMU_MODE_TLB); if (status != USLOSS_MMU_OK) { USLOSS_Console("vmInitReal: couldn't initialize MMU, status %d\n", status); abort(); } USLOSS_IntVec[USLOSS_MMU_INT] = FaultHandler; frameTable = malloc(frames * sizeof(FTE)); for(i = 0; i < frames; i ++){ frameTable[i].state = FUNUSED; frameTable[i].frame = 0; frameTable[i].page = 0; frameTable[i].pid = -1; } clockhand = 0; clockhandMbox = MboxCreate(1, 0); /* * Initialize page tables. */ for (i = 0; i < MAXPROC; i++){ processes[i].pid = -1; processes[i].numPages = pages; processes[i].pageTable = NULL; faults[i].pid = -1; faults[i].addr = NULL; faults[i].replyMbox = MboxCreate(1, sizeof(int)); } /* * Create the fault mailbox or semaphore */ faultMbox = MboxCreate(pagers, sizeof(FaultMsg)); /* * Fork the pagers. */ for(int i = 0; i < MAXPAGERS; i++){ pagerPID[i] = -1; if (i < pagers) pagerPID[i] = fork1("Pager", Pager, NULL, 8*USLOSS_MIN_STACK, PAGER_PRIORITY); } int blocks; diskSizeReal(1, &dummy, &dummy, &blocks); blocks *= 2; diskTable = malloc(blocks * sizeof(DTE)); for (i = 0; i < blocks; i++){ diskTable[i].pid = -1; diskTable[i].page = -1; diskTable[i].track = i / 2; diskTable[i].sector = (i % 2) * USLOSS_MmuPageSize() / USLOSS_DISK_SECTOR_SIZE; } /* * Zero out, then initialize, the vmStats structure */ memset((char *) &vmStats, 0, sizeof(VmStats)); vmStats.pages = pages; vmStats.frames = frames; vmStats.diskBlocks = blocks; vmStats.freeFrames = frames; vmStats.freeDiskBlocks = blocks; vmStats.new = 0; /* * Initialize other vmStats fields. */ vmRegion = USLOSS_MmuRegion(&dummy); return vmRegion; } /* vmInitReal */ /* *---------------------------------------------------------------------- * * PrintStats -- * * Print out VM statistics. * * Results: * None * * Side effects: * Stuff is printed to the USLOSS_Console. * *---------------------------------------------------------------------- */ void PrintStats(void) { USLOSS_Console("VmStats\n"); USLOSS_Console("pages: %d\n", vmStats.pages); USLOSS_Console("frames: %d\n", vmStats.frames); USLOSS_Console("diskBlocks: %d\n", vmStats.diskBlocks); USLOSS_Console("freeFrames: %d\n", vmStats.freeFrames); USLOSS_Console("freeDiskBlocks: %d\n", vmStats.freeDiskBlocks); USLOSS_Console("switches: %d\n", vmStats.switches); USLOSS_Console("faults: %d\n", vmStats.faults); USLOSS_Console("new: %d\n", vmStats.new); USLOSS_Console("pageIns: %d\n", vmStats.pageIns); USLOSS_Console("pageOuts: %d\n", vmStats.pageOuts); USLOSS_Console("replaced: %d\n", vmStats.replaced); } /* PrintStats */ /* *---------------------------------------------------------------------- * * vmDestroyReal -- * * Called by vmDestroy. * Frees all of the global data structures * * Results: * None * * Side effects: * The MMU is turned off. * *---------------------------------------------------------------------- */ void vmDestroyReal(void){ CheckMode(); r = USLOSS_MmuDone(); int i, status; FaultMsg dummy; if (vmRegion == NULL) return; /* * Kill the pagers here. */ vmRegion = NULL; for (i = 0; i < MAXPAGERS; i++) { if (pagerPID[i] == -1) break; if (DEBUG5) USLOSS_Console("vmDestroyReal: zapping pager %d, pid %d \n", i, pagerPID[i]); MboxSend(faultMbox, &dummy, sizeof(FaultMsg)); // wake up pager zap(pagerPID[i]); join(&status); } for (i = 0; i < MAXPROC; i++) { MboxRelease(faults[i].replyMbox); } MboxRelease(faultMbox); /* * Print vm statistics. */ PrintStats(); } /* vmDestroyReal */ /* *---------------------------------------------------------------------- * * FaultHandler * * Handles an MMU interrupt. Simply stores information about the * fault in a queue, wakes a waiting pager, and blocks until * the fault has been handled. * * Results: * None. * * Side effects: * The current process is blocked until the fault is handled. * *---------------------------------------------------------------------- */ static void FaultHandler(int type /* MMU_INT */, void* offset /* Offset within VM region */) { int cause, i, frameNum = 0, pageNum = 0; FaultMsg* fmsg = &(faults[getpid() % MAXPROC]); //ProcPtr current = &(processes[getpid() % MAXPROC]); if (1==0){ USLOSS_Console("%d",pageNum); } for (i = 0; i < MAXPAGERS; i++){ if (pagerPID[i] == getpid()){ USLOSS_Console("Pager %d (pid = %d) caused pagefault, aborting\n", i, getpid()); abort(); } } assert(type == USLOSS_MMU_INT); cause = USLOSS_MmuGetCause(); assert(cause == USLOSS_MMU_FAULT); vmStats.faults++; /* * Fill in faults[pid % MAXPROC], send it to the pagers, and wait for the * reply. */ pageNum = (int)(long)offset / USLOSS_MmuPageSize(); fmsg->pid = getpid(); fmsg->addr = offset; MboxSend(faultMbox, fmsg, sizeof(FaultMsg)); MboxReceive(fmsg->replyMbox, &frameNum, sizeof(int)); } /* FaultHandler */ /* *---------------------------------------------------------------------- * * Pager * * Kernel process that handles page faults and does page replacement. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int Pager(char *buf) { FaultMsg msg; char buffer[USLOSS_MmuPageSize()]; // buffer to read and write from disk Process *currProc; int frame = -1, page = 0, i, access = 0; while(1) { /* Wait for fault to occur (receive from mailbox) */ MboxReceive(faultMbox, &msg, sizeof(FaultMsg)); if (isZapped()) break; frame = -1; currProc = &processes[msg.pid % MAXPROC]; page = (int)(long)msg.addr / USLOSS_MmuPageSize(); /* Wait for fault to occur (receive from mailbox) */ /* Look for free frame */ /* Look for free frame */ if (vmStats.freeFrames > 0) { for (frame = 0; frame < vmStats.frames; frame++) { if (frameTable[frame].state == FUNUSED) { r = USLOSS_MmuMap(TAG, 0, frame, USLOSS_MMU_PROT_RW); vmStats.freeFrames--; break; } } }else{ ProcPtr other; /* If there isn't one then use clock algorithm to * replace a page (perhaps write to disk) */ for (int j = 0; j < 2; j++){ if (frame == -1){ for(i = 0; i < vmStats.frames; i++){ //MboxSend(clockhandMbox, 0, sizeof(int)); r = USLOSS_MmuGetAccess(clockhand, &access); if (access == 0){ frame = clockhand; other = &(processes[frameTable[frame].pid]); // set old page's info other->pageTable[frameTable[frame].page].state = INCORE; other->pageTable[frameTable[frame].page].frame = -1; clockhand = (clockhand + 1) % vmStats.frames; r = USLOSS_MmuMap(TAG, 0, frame, USLOSS_MMU_PROT_RW); break; }else { clockhand = (clockhand + 1) % vmStats.frames; } //MboxReceive(clockhandMbox, 0, sizeof(int)); } } // Look for unreferenced and dirty if (frame == -1){ for(i = 0; i < vmStats.frames; i++){ r = USLOSS_MmuGetAccess(clockhand, &access); if ((access & USLOSS_MMU_REF) == 0){ char* buff[USLOSS_MmuPageSize()]; int d; PTEptr otherPage; DTEptr otherDisk; frame = clockhand; other = &(processes[frameTable[frame].pid]); otherPage = &(other->pageTable[frameTable[frame].page]); r = USLOSS_MmuMap(TAG, 0, frame, USLOSS_MMU_PROT_RW); //write stuff to disk if (otherPage->diskBlock == -1) { if (vmStats.freeDiskBlocks == 0) { if (DEBUG5) USLOSS_Console("Pager: no free disk blocks, halting... \n %d", otherDisk); USLOSS_Halt(1); } for (d = 0; d < vmStats.diskBlocks; d++){ if (diskTable[d].pid == -1){ otherPage->diskBlock = d; diskTable[d].pid = other->pid; diskTable[d].page = frameTable[frame].page; break; } } } otherDisk = &(diskTable[otherPage->diskBlock]); memcpy(&buff, vmRegion, USLOSS_MmuPageSize()); //diskWriteReal(SWAPDISK, otherDisk->track, otherDisk->sector, USLOSS_MmuPageSize()/USLOSS_DISK_SECTOR_SIZE, &buff); // set old page's info other->pageTable[frameTable[frame].page].state = INCORE; other->pageTable[frameTable[frame].page].frame = -1; vmStats.pageOuts++; clockhand = (clockhand + 1) % vmStats.frames; break; }else{ r = USLOSS_MmuSetAccess(clockhand, access & USLOSS_MMU_DIRTY); clockhand = (clockhand + 1) % vmStats.frames; } } } } } // First time be used if (currProc->pageTable[page].state == UNUSED) { vmStats.new++; memset(vmRegion, 0, USLOSS_MmuPageSize()); }else { //USLOSS_Console("Pager(): Getting contents from disk not yet done, setting to 0 for now\n"); memset(vmRegion, 0, USLOSS_MmuPageSize()); //TODO: get page contents from disk if (currProc->pageTable[page].diskBlock != -1){ vmStats.pageIns++; } } // unmap r = USLOSS_MmuSetAccess(frame, 0); r = USLOSS_MmuUnmap(0, 0); // unmap page /* Load page into frame from disk, if necessary */ /* Unblock waiting (faulting) process */ currProc->pageTable[page].frame = frame; currProc->pageTable[page].state = INFRAME; frameTable[frame].state = FINUSE; frameTable[frame].pid = currProc->pid; frameTable[frame].page = page; r = USLOSS_MmuMap(TAG, page, frame, USLOSS_MMU_PROT_RW); MboxSend(msg.replyMbox, &frame, sizeof(int)); if (1==0){ USLOSS_Console("%d%s",r,buffer); } } return 0; } /* Pager */ /* setUserMode() Switch from kernel to user mode */ void setUserMode(){ int r = USLOSS_PsrSet( USLOSS_PsrGet() & ~USLOSS_PSR_CURRENT_MODE ); if (DEBUG5) { USLOSS_Console("%d get way from warning unused variable\n", r); } }
C
#define DISTANCE 3200 const int Dir_DS = 2; const int Dir_Sh = 3; const int Dir_St = 4; const int Dir_Rst = 5; const int Pul_DS = 6; const int Pul_Sh = 7; const int Pul_St = 8; const int Pul_Rst = 9; void setup() { //Direction Reg g pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); // Pulse Reg g pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); // Initialize Regs digitalWrite(Dir_Rst, HIGH); digitalWrite(Pul_Rst, HIGH); digitalWrite(Dir_Sh, LOW); digitalWrite(Pul_Sh, LOW); } void loop() { digitalWrite(8, LOW); digitalWrite(9, LOW); } //Pumps the shift registers with the apt signals void pump(unsigned int pul1,unsigned int pul2,unsigned int pul3,unsigned int pul4,unsigned int pul5,unsigned int pul6, unsigned int dir1,unsigned int dir2,unsigned int dir3,unsigned int dir4,unsigned int dir5,unsigned int dir6) { // Load Serial Direction //Let go of Reset digitalWrite(Dir_Rst, LOW); shift_Dir(dir1); shift_Dir(dir2); shift_Dir(dir3); shift_Dir(dir4); shift_Dir(dir5); shift_Dir(dir6); //!!!Shift!!! digitalWrite(Dir_St,HIGH); digitalWrite(Dir_St,LOW); // Load Serial Pulse //Let go of Reset digitalWrite(Dir_Rst, LOW); shift_Pul(pul1); shift_Pul(pul2); shift_Pul(pul3); shift_Pul(Pul4); shift_Pul(pul5); shift_Pul(pul6); //!!!Store!!! digitalWrite(Pul_St,HIGH); digitalWrite(Pul_St,LOW); //Reset Pulse Reg digitalWrite(Pul_Rst, HIGH); //Reset Direction Reg digitalWrite(Dir_Rst, HIGH); } //Writes to SR void shift_Dir(unsigned int signal) { if(signal) { //Set DS to HIGH digitalWrite(Dir_DS, HIGH); digitalWrite(Dir_DS, LOW); //Shift digitalWrite(Dir_Sh, HIGH); digitalWrite(Dir_Sh, LOW); } else { //Just Shift digitalWrite(Dir_Sh, HIGH); digitalWrite(Dir_Sh, LOW); } } //Writes to SH . void shift_Pul(unsigned int signal) { if(signal) { //Set DS to HIGH digitalWrite(Pul_DS, HIGH); digitalWrite(Pul_DS, LOW); //Shift digitalWrite(Pul_Sh, HIGH); digitalWrite(Pul_Sh, LOW); } else { //Just Shift digitalWrite(Pul_Sh, HIGH); digitalWrite(Pul_Sh, LOW); } }
C
#include <stdio.h> int main (int argc, char* argv[]) { char char_h = 'H'; char char_k = 'K'; char char_0 = '0'; char char_4 = '4'; char char_5 = '\x5B'; char char_6 = '\x5D'; putchar(char_h); putchar(char_k); putchar(char_0); putchar(char_4); putchar(char_5); putchar(char_6); return 0; }
C
#include <p18f25k20.h> #include <timers.h> #include <delays.h> #include <stdlib.h> #include <adc.h> #include "RenLCD.h" #define OSCmask 0b10001111 #define Fosc 5 //4MHz char str[16]; int analog[2]; //***************************** // FUNCTION PROTOTYPES //***************************** void init(void); void initTimers(void); void initI2C(void); void low_isr(void); void high_isr(void); /************************ INTERRUPT SETUP ************************/ #pragma config FOSC = INTIO67, LVP = OFF #pragma code high_vector = 0x08 //setup the high ISR vector void int_high(void) {_asm GOTO high_isr _endasm} #pragma code #pragma interrupt high_isr //the high ISR #pragma code low_vector = 0x18 //setup the low ISR vector void int_low(void) {_asm GOTO low_isr _endasm} #pragma code #pragma interruptlow low_isr //the low ISR //***************************** // MAIN //***************************** void main(){ Delay1KTCYx(50); init(); InitializeLCD(); //initTimers(); ClearLCD(); while(1){ OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST,ADC_CH0 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 0); ConvertADC(); while(BusyADC()); analog[0]=ReadADC(); OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST,ADC_CH1 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 0); ConvertADC(); while(BusyADC()); analog[1]=ReadADC(); SetLine1(); sprintf(str, "%4d %4d", analog[0],analog[1]); WriteLCD(str); Delay10KTCYx(10); } } /******************************* HELPER FUNCTIONS ********************************/ void init(){ //set internal oscillator speed OSCCON = (OSCCON&OSCmask)|(Fosc<<4); //port directions TRISA = 0xff; //all input TRISB = 0x00; //all output TRISC = 0x00; //all but RC3,4 are output } void high_isr (void) { PIR1bits.SSPIF = 0; } void low_isr (void) { PIR1bits.TMR1IF = 0; WriteTimer1(0xFFFF-40000); sprintf(str, "%4d %4d", analog[0],analog[1]); WriteLCD(str); } void initTimers() { T1CONbits.TMR1ON = 0; //timer 1 off // Initializing Timer 1 settings OpenTimer1( TIMER_INT_ON & T1_16BIT_RW & T1_SOURCE_INT & T1_PS_1_1 & T1_OSC1EN_OFF & T1_SYNC_EXT_OFF); //Initializing Interrupts RCONbits.IPEN = 1; //Initialize the IP IPR1bits.TMR1IP = 0; //Set Timer1 to LowP PIE1bits.TMR1IE = 0; //Enable TMR1 interrupt WriteTimer1(0xffff-40000); T1CONbits.TMR1ON = 0; //timer 0 on }
C
#include <stdio.h> int main() { int isListesi[100],x,n,i,j,toplam = 0,tmp; printf("Is listesinin uzunlugunu veriniz :"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Is listesinin %d. elemani :",i+1); scanf("%d",&isListesi[i]); } printf("\n\n--Is listesi --\n"); for (i=0; i<n; i++) { printf("%d ",isListesi[i]); } printf("\n\n"); printf("Isci mola vermeden kac saat calisabilir :"); scanf("%d",&x); i = 0; int elemanSayisi = n; while(i<elemanSayisi) { if(toplam + isListesi[i] <= x) { toplam += isListesi[i]; } else { elemanSayisi++; toplam = 0; tmp = isListesi[i]; isListesi[i] = -1; for (j=elemanSayisi-1; j>i; j--) { isListesi[j+1] = isListesi[j]; } isListesi[i+1] = tmp; } i++; } printf("\n--Molalar yerlestirildikten sonraki is listesi--1\n"); for (i=0; i<elemanSayisi; i++) { printf("%d ",isListesi[i]); } printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "lista_ligada.h" p_no criar_lista() { return NULL; } void destruir_lista(p_no lista){ if (lista != NULL) { destruir_lista(lista->prox); free(lista); } } void destruir_listaI(p_no lista){ p_no atual, prox; for (atual = lista; atual != NULL; atual = prox){ prox = atual->prox; free(atual); } } p_no adicionar_elemento(p_no lista, int elem){ p_no novoNo; novoNo = malloc(1*sizeof(No)); if (novoNo != NULL){ novoNo -> prox = lista; novoNo -> dado = elem; } return novoNo; } void imprimirI(p_no lista){ p_no atual; for (atual = lista; atual != NULL; atual = lista->prox){ printf("%d\n", atual->dado); } } void imprimirR(p_no lista){ if (lista != NULL){ imprimirR(lista->prox); printf("%d\n", lista->dado); } } p_no copiar_lista(p_no lista){ p_no novo; if (lista==NULL){ return NULL; } novo = malloc(sizeof(No)); novo->dado = lista->dado; novo->prox = copiar_lista(lista->prox); return novo; } p_no inverter_lista(p_no lista){ p_no ant, atual, invertida = NULL; atual = lista; while (atual != NULL){ ant = atual; atual = ant->prox; ant->prox = invertida; invertida = ant; } return invertida; } p_no concatenar_lista(p_no primeira, p_no segunda){ if (primeira == NULL){ return segunda; } primeira->prox = concatenar_lista(primeira->prox, segunda); return primeira; } p_no inserir_circular(p_no lista, int x){ p_no novo; novo = malloc(sizeof(No)); novo->dado = x; if (lista==NULL){ novo->prox = novo; } else{ novo->prox = lista->prox; lista->prox = novo; } return novo; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_for_five.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: umoff <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/03 21:23:58 by umoff #+# #+# */ /* Updated: 2020/02/06 11:42:26 by umoff ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" void ft_part_1_1(t_n_list **stack_a, t_n_list **stack_b, t_c_list **com_stack) { while (ft_calc_max(stack_a) != (*stack_a)->order) if (!*com_stack) *com_stack = ft_comnew(ft_rra(stack_a)); else ft_comadd(com_stack, ft_comnew(ft_rra(stack_a))); if (!*com_stack) *com_stack = ft_comnew(ft_pb(stack_a, stack_b)); else ft_comadd(com_stack, ft_comnew(ft_pb(stack_a, stack_b))); } void ft_part_1(t_n_list **stack_a, t_n_list **stack_b, t_c_list **com_stack) { while (ft_lstlens(stack_a) > 3) { if (ft_calc_max(stack_a) - 1 == (*stack_a)->order && (!*com_stack) && ft_lstlens(stack_a) == 5) *com_stack = ft_comnew(ft_pb(stack_a, stack_b)); else if (ft_calc_max(stack_a) - 1 == (*stack_a)->order && ft_lstlens(stack_a) == 5) ft_comadd(com_stack, ft_comnew(ft_pb(stack_a, stack_b))); else if (ft_calc_max(stack_a) == (*stack_a)->order && (!*com_stack)) *com_stack = ft_comnew(ft_pb(stack_a, stack_b)); else if (ft_calc_max(stack_a) == (*stack_a)->order) ft_comadd(com_stack, ft_comnew(ft_pb(stack_a, stack_b))); else if (!*com_stack) *com_stack = ft_comnew(ft_ra(stack_a)); else ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); } } void ft_part_2(t_n_list **stack_a, t_c_list **com_stack) { t_n_list *t2; t_n_list *t3; if (!*com_stack) *com_stack = ft_comnew(NULL); t2 = (*stack_a)->next; t3 = t2->next; if ((*stack_a)->order > t2->order && (*stack_a)->order < t3->order) ft_comadd(com_stack, ft_comnew(ft_sa(stack_a))); else if ((*stack_a)->order > t2->order && t2->order > t3->order) { ft_comadd(com_stack, ft_comnew(ft_sa(stack_a))); ft_comadd(com_stack, ft_comnew(ft_rra(stack_a))); } else if ((*stack_a)->order > t3->order && t2->order < t3->order) ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); else if ((*stack_a)->order < t2->order && (*stack_a)->order < t3->order) { ft_comadd(com_stack, ft_comnew(ft_sa(stack_a))); ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); } else if ((*stack_a)->order < t2->order && (*stack_a)->order > t3->order) ft_comadd(com_stack, ft_comnew(ft_rra(stack_a))); } void ft_for_two(t_n_list **stack_a, t_c_list **com_stack) { t_n_list *t1; t1 = (*stack_a)->next; if ((*stack_a)->order > t1->order) *com_stack = ft_comnew(ft_sa(stack_a)); } void ft_for_five(t_n_list **stack_a, t_n_list **stack_b, t_c_list **com_stack) { t_n_list *t2; t_n_list *t3; if (ft_lstlens(stack_a) == 2) return (ft_for_two(stack_a, com_stack)); ft_part_1(stack_a, stack_b, com_stack); t2 = (*stack_a)->next; t3 = t2->next; if (!((*stack_a)->order < t2->order && t2->order < t3->order)) ft_part_2(stack_a, com_stack); if (*stack_b && ft_lstlens(stack_b) == 2) { t2 = (*stack_b)->next; if (t2->order > (*stack_b)->order) ft_comadd(com_stack, ft_comnew(ft_rb(stack_b))); ft_comadd(com_stack, ft_comnew(ft_pa(stack_a, stack_b))); ft_comadd(com_stack, ft_comnew(ft_pa(stack_a, stack_b))); ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); } else if (*stack_b) { ft_comadd(com_stack, ft_comnew(ft_pa(stack_a, stack_b))); ft_comadd(com_stack, ft_comnew(ft_ra(stack_a))); } }
C
/* ** EPITECH PROJECT, 2018 ** atof ** File description: ** . */ #include <stdbool.h> #include "n_for_stek.h" double my_atof(char *str) { double val = 0; int e = 0; int i = 0; while (*str != '\0' && is_number(*str) == true) val = val * 10 + (*str++ - '0'); if (str[i] == '.') while (*str != '\0' && is_number(*str) == true) val = val * 10 + (*str++ - '0'); while (e++ < 0) val *= 0.1; return (val); } int is_number(char c) { if (!(c >= '0' && c <= '9')) return (false); return (true); }
C
/* Quiz 2 題目敘述 寫一個程式計算給定日期為星期幾。輸入會先告訴程式某年的 1 月 1 號為星期幾,例如範例中 2012 年的 1 月 1 號為星期日。接著程式會收到一些日期,並要計算出給定日期為星期幾,例如範例中程式將會收到 11 月 13 號,並計算出該日期為星期二。 (閏年計算請參考wiki) 輸入格式 第一行包含一個西元年以及該年的一月一日為星期幾,如範例中 2012 0。注意,0 代表星期日,1 代表星期一,以此類推。第二行會告訴程式接下來將有 n 組日期需要計算。n 的範圍為 1 至 10。接下來的 n 行,每一行將會有一組需要計算的日期(月、日),如範例中的 11 月 13 號。若輸入的「月」有誤請輸出 -1;若輸入的「日」有誤請輸出 -2。 輸出格式 共會輸出 n 個數字。我們用 0 代表星期日,1 代表星期一,以此類推。若輸入的「月」有誤請輸出 -1;若輸入的 「月」無誤但「日」有誤請輸出 -2。(數字間留一個空白) 輸入範例 2012 0 5 11 13 11 14 11 15 13 1 1 200 輸出範例 (請務必依照範例格式填寫,數字間留一個空白,否則系統將會判定答案錯誤) 2 3 4 -1 -2 */ #include <stdio.h> #include <stdlib.h> int main (void) { // read in the year and week day of the first day of the year int year = 0, day1st = 0; scanf("%d %d", &year, &day1st); // calculate leap day of the year int leapdays; if (year % 4 != 0) { leapdays = 28; } else if (year % 100 != 0) { leapdays = 29; } else if (year % 400 != 0) { leapdays = 28; } else { leapdays = 29; } printf ("lead days= %d\n", leapdays); // create dictionary for days of the month int daysOfMonth[12] = {31, leapdays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // read number of inputs int inputNum = 0; scanf("%d", &inputNum); int record[inputNum]; for (int cnt = 0; cnt < inputNum; cnt++) { int daysOfInput = 0, month = 0, date = 0; scanf("%d %d", &month, &date); if (month > 12 || month < 1) { record[cnt] = -1; continue; } if (date > daysOfMonth[month - 1] || date < 1) { record[cnt] = -2; continue; } // calculate the number of days form year start for (int monCnt = 0; monCnt < month - 1; monCnt++) { daysOfInput += daysOfMonth[monCnt]; } daysOfInput += (date - 1 + day1st); // calculate and print the the week day record[cnt] = daysOfInput % 7; } // print results for (int cnt = 0; cnt < inputNum; cnt++) { printf("%d ", record[cnt]); } printf("\n"); return 0; } /* 1. Input 1492 0 7 10 12 -1 0 12 -12 8 3 6 31 4 9 11 3 Output: 5 -1 -2 5 -2 1 6 2. Inputs: 1911 0 8 4 27 2 29 12 25 7 -5 11 6 2 0 10 10 3 100 Output: 4 -2 1 -2 1 -2 2 -2 3. Inputs: 2552 6 6 15 20 8 30 2 29 11 31 0 13 9 19 Output: -1 3 2 -2 -1 2 4. Input: 2005 6 7 -77 -132 12 25 8 31 7 6 1 1 1024 122 2 29 Output: -1 0 3 3 6 -1 -2 5. Input: 2000 6 10 2 29 1300 1 11 19 6 1272 8 31 4 9 9 23 2 28 1 1 10 1 Output: 2 -1 0 -2 4 0 6 1 6 0 */
C
#include <stdio.h> #include "../../../Helper/Array/Util/printArray.h" #include <malloc.h> void get2RepeatingItems(int *arr, int len, int *res1, int *res2) { int *count = (int *)calloc(len - 2, sizeof(int)); int i = 0, flag = 0; while (i < len) { count[arr[i] - 1]++; if (2 == count[arr[i] - 1]) { if (0 == flag) { *res1 = arr[i]; flag++; } else { *res2 = arr[i]; return; } } i++; } } int main () { int arr[] = {4, 2, 4, 5, 1, 3, 1}; int len = sizeof(arr) / sizeof(arr[0]); printIntArray(arr, len); int res1 = 0, res2 = 0; get2RepeatingItems(arr, len, &res1, &res2); printf("res1 = %d, res2 = %d\n", res1, res2); return 0; }
C
#include <stdio.h> int main(){ unsigned char s; ch=32; while(s<=127){ printf("%c [%03d] ",s,s); s++; } printf("\n"); return 0; }
C
#include <zlib.h> #include <stdio.h> #include "kseq.h" KSEQ_INIT(gzFile, gzread) static int g_len = 35; int main(int argc, char *argv[]) { int l, i, j; kseq_t *seq; gzFile fp; if (argc == 1) { fprintf(stderr, "splitfa <in.fa> [len=%d]\n", g_len); return 1; } if (argc >= 3) g_len = atoi(argv[2]); fp = gzopen(argv[1], "r"); seq = kseq_init(fp); while ((l = kseq_read(seq)) >= 0) { if (l < g_len) continue; for (i = 0; i <= l - g_len; ++i) { printf(">%s_%d\n", seq->name.s, i+1); for (j = 0; j < g_len; ++j) putchar(seq->seq.s[i + j]); putchar('\n'); } } kseq_destroy(seq); gzclose(fp); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <string.h> #include <ctype.h> #include <ncurses.h> #include "util.h" char username[9]={0}; int nrow = 15,ncol = 45; //char linharecebida[45]; //char useraeditarlinha[9]; //int posNL=-1; //char linhaeditada[45]; int checkuser(char *username){ int fd_cli,fd_ser; char fifo_nome[20]; PEDIDO p; int n; p.remetente = getpid(); p.tipo = 1; strcpy(p.username,username); fd_ser = open (FIFO_SER,O_WRONLY); n=write(fd_ser,&p,sizeof(PEDIDO)); //printf("Foi enviado %s\t",username); //ler resposta do servidor sprintf(fifo_nome,FIFO_CLI,getpid()); mkfifo(fifo_nome,0600); fd_cli=open(fifo_nome,O_RDONLY); read(fd_cli,&p,sizeof(PEDIDO)); close(fd_cli); //printf("Recebi valid = %d\n\n",p.valid); ncol = p.linhaPoxx; nrow = p.linhaPoxy; return p.valid; } int lockline(int linenumber){ //1 se puder editar linha 0 se nao int fd_cli,fd_ser; char fifo_nome[20]; PEDIDO p; int n; p.remetente = getpid(); p.tipo =3; strcpy(p.username,username); p.linhaPoxy = linenumber; sprintf(fifo_nome,FIFO_CLI,getpid()); mkfifo(fifo_nome,0600); fd_ser = open (FIFO_SER,O_WRONLY); n=write(fd_ser,&p,sizeof(PEDIDO)); //printf("Foi enviado ao serv %s\t",username); //ler resposta do servidor fd_cli=open(fifo_nome,O_RDONLY); n=read(fd_cli,&p,sizeof(PEDIDO)); close(fd_cli); printf("Recebi valid = %d\n\n",p.valid); return p.valid; } int unlockline(int linenumber,char *linhatxt,int useaspell){ int fd_cli,fd_ser; char fifo_nome[20]; PEDIDO p; int n; p.remetente = getpid(); p.tipo =4; memset(p.linha,0,sizeof(p.linha)); strcpy(p.linha,linhatxt); strcpy(p.username,username); linenumber -=3; p.linhaPoxy = linenumber; p.valid = useaspell; sprintf(fifo_nome,FIFO_CLI,getpid()); mkfifo(fifo_nome,0600); fd_ser = open (FIFO_SER,O_WRONLY); n=write(fd_ser,&p,sizeof(PEDIDO)); printf("Foi enviado ao serv %s\t",username); fd_cli=open(fifo_nome,O_RDONLY); n=read(fd_cli,&p,sizeof(PEDIDO)); close(fd_cli); printf("Recebi valid = %d\n\n",p.valid); return p.valid; } int logout(){ int fd_cli,fd_ser; char fifo_nome[20]; PEDIDO p; int n; p.remetente = getpid(); p.tipo =2; fd_ser = open (FIFO_SER,O_WRONLY); n=write(fd_ser,&p,sizeof(PEDIDO)); printf("\nFoi enviado logout\n"); sprintf(fifo_nome,FIFO_CLI,getpid()); unlink(fifo_nome); exit(1); } void freelinha(int posy,char *linhaoriginal){ int fd_cli,fd_ser; char fifo_nome[20]; PEDIDO p; int n; p.remetente = getpid(); p.tipo =7; memset(p.linha,0,sizeof(p.linha)); strcpy(p.linha,linhaoriginal); strcpy(p.username,username); posy -=3; p.linhaPoxy = posy; sprintf(fifo_nome,FIFO_CLI,getpid()); mkfifo(fifo_nome,0600); fd_ser = open (FIFO_SER,O_WRONLY); n=write(fd_ser,&p,sizeof(PEDIDO)); } void recebe(int s){ char fifo_nome[20]; endwin(); if(s == SIGUSR1){ printf("o servidor vai encerrar em 1 segundos\n" ); sleep(1); } if(s == SIGINT){ logout(); } sprintf(fifo_nome,FIFO_CLI,getpid()); unlink(fifo_nome); exit(0); } void show_help(char *name) { fprintf(stderr, "\ [uso] %s <opcoes>\n\ -h mostra essa tela e sai.\n\ -u username \n\", name) ;",name); exit(-1) ; } int main(int argc, char **argv) { int opt ,check=0,i; int posy,posx,fd_cli, res,edicao=0,ch; char *varAmb=NULL; int skip = 0; int uFARg = 0; fd_set fontes; int times = 0;//quantas vezes carregou no enter signal(SIGUSR1,recebe); //servidor a fechar signal(SIGINT,recebe);//fecha cliente //verifica se o server está a correr if (access(FIFO_SER,F_OK)!=0){ printf("O servidor não está a correr\n"); return 3; } WINDOW * uiWindow; WINDOW * notificacaoWindow; WINDOW * lnWindow; WINDOW * usersWindow; WINDOW * palavrasWindow; /*char *nrows = getenv("MEDIT_MAXLINES"); char *ncols = getenv("MEDIT_MAXCOLUMNS"); if(nrows == NULL || ncols == NULL){ puts("variaveis de ambiente nao definidas\n executar . ./script.sh"); exit(3); } nrow = atoi(nrows); ncol = atoi(ncols);*/ while( (opt = getopt(argc, argv, "hu:V:")) > 0 ) { switch ( opt ) { case 'h': show_help(argv[0]) ; break ; case 'u': strncpy(username,optarg,8); username[8]='\0'; //poe \0 no ultimo elemento //puts(username); uFARg = 1; break ; case 'v': //ler variavel ambiente varAmb=optarg; printf("%s : %s\n", varAmb ,getenv(varAmb)); break ; default: fprintf(stderr, "Opcao invalida ou faltando argumento: `%c'\n", optopt) ; return -1 ; } } // pede caso nao seja enviado pela linha de comandos do{ do{ if(uFARg == 0){ printf("insira o utilizador: "); scanf("%s",username );//fgets(username,9,stdin); fflush(stdin); } }while(strlen(username)>8); printf("utilizador: %s ",username); int ret = checkuser(username); //printf("return de checkuser %d\n",ret ); if( ret == 1){ printf("Valido\n"); skip = 1; } else if( ret == 2){ printf("Ja em uso\n"); uFARg = 0; } else{ printf("Invalido\n"); strcpy(username,""); uFARg = 0; } } while(skip != 1); //check = checauser(getenv("MEDIT_FICH"),username); printf("%d",check); char linha[ncol]; char linhaoriginal[ncol]; initscr(); //INCICIALIZA toda a implementação de estrutura de data start_color(); //Inicia funcionalidade das cores clear(); //limpa o ecra cbreak();// desliga o buffering do input curs_set(1); //Trata da visibilidade do cursor (0-invisible,1- normal, 2-high visibilty) noecho(); // Não haver echo das teclas keypad(stdscr,true); init_pair(1,COLOR_BLUE, COLOR_BLACK); //numero do par , cor texto , cor fundo init_pair(2,COLOR_WHITE, COLOR_BLACK); init_pair(3,COLOR_RED, COLOR_WHITE); notificacaoWindow = newwin(3,ncol,0,0); wbkgd(notificacaoWindow, COLOR_PAIR(1)); uiWindow = newwin(nrow+1,ncol,3,3);//linhas cols y x wbkgd(uiWindow, COLOR_PAIR(2)); lnWindow = newwin(nrow+1,3,3,0);//linhas cols y x wbkgd(lnWindow, COLOR_PAIR(1)); usersWindow = newwin(nrow+1,9,2,ncol+3);//linhas cols y x wbkgd(usersWindow, COLOR_PAIR(1)); palavrasWindow = newwin(nrow+2,20,2,ncol+15);//linhas cols y x wbkgd(palavrasWindow, COLOR_PAIR(1)); wrefresh(lnWindow); /*shortcutsWindow = newwin(4,75,18,0); wprintw(shortcutsWindow,"\n\t\t\tnotificacao"); wbkgd(shortcutsWindow, COLOR_PAIR(1));*/ wrefresh(uiWindow); //nodelay(stdscr,true); //getmaxyx(stdscr,nrow,ncol); wclear(notificacaoWindow); wclear(uiWindow); move(0,0); wprintw(notificacaoWindow,"Modo de navegação no texto"); posx = ncol/2; posy = nrow/2; move(posy,posx); // mvwprintw(uiWindow,3,(ncol/2)-3, "(%d,%d) ",posy-3,posx-3); /* wrefresh(uiWindow); wrefresh(notificacaoWindow);*/ int k=0,j=0; // imprime numero d linhas for (j = 0; j < nrow; j++) { for (k = 0; k < 3; k++) { char SposNL[3]; sprintf(SposNL, "%d ", j); SposNL[2] = '|'; mvwaddch(lnWindow,j,k,SposNL[k]); } } refresh(); wrefresh(lnWindow); wrefresh(notificacaoWindow); wrefresh(uiWindow); wrefresh(palavrasWindow); wrefresh(stdscr); int fd_ser,fd_lixo,n; char fifo_nome[20]; PEDIDO p; sprintf(fifo_nome,FIFO_CLI,getpid()); mkfifo(fifo_nome,0600); fd_cli = open(fifo_nome,O_RDONLY | O_NONBLOCK);//impedir que fique em espera fd_lixo = open(fifo_nome,O_WRONLY); fd_ser = open(FIFO_SER ,O_WRONLY); do{ move(posy,posx); wrefresh(stdscr); FD_ZERO(&fontes); // FD_ZERO() clears a set. FD_SET(0,&fontes); // add a given file descriptor from a set. FD_SET(fd_cli,&fontes); res = select(fd_cli+1,&fontes,NULL,NULL,NULL); if(res>0 && FD_ISSET(fd_cli,&fontes) ){ //pelo pipe /************lê do seu pipe************/ n=read(fd_cli,&p,sizeof(PEDIDO)); if(p.carater == 8 && p.tipo == 5){ //backspace mvwdelch(uiWindow,p.linhaPoxy-3,p.linhaPoxx-3); move(posy,posx); refresh(); wrefresh(uiWindow); } if(p.carater == 9 && p.tipo == 5){//delete mvwdelch(uiWindow,p.linhaPoxy-3,p.linhaPoxx-3); move(posy,posx); } if(p.tipo == 3){//show locked line mvwprintw(usersWindow,p.linhaPoxy+1,0,p.username); refresh(); wrefresh(usersWindow); } if(p.tipo == 4){//show unlocked line char *blankusername = " "; mvwprintw(usersWindow,p.linhaPoxy+1,0,blankusername); refresh(); wrefresh(usersWindow); } if(p.tipo == 5){//imprimir caracteres mvwaddch(uiWindow,p.linhaPoxy,p.linhaPoxx,p.carater); move(posy,posx); refresh(); wrefresh(uiWindow); } if(p.tipo ==6){ //mostras palavras na janela nova if(p.nPalavrasErradas > 0){ wclear(palavrasWindow); mvwprintw(palavrasWindow,0,0,"palavras erradas:"); for(i=1;i<=p.nPalavrasErradas;i++){ mvwprintw(palavrasWindow,i,0,p.palavrasErradas[i-1]); } refresh(); wrefresh(palavrasWindow); } else{ wclear(palavrasWindow); refresh(); wrefresh(palavrasWindow); } for(i=0;i<p.nPalavrasErradas;i++){ memset( p.palavrasErradas[i],0,20); } } if(p.tipo==7){ freelinha(posy,linhaoriginal); edicao = 0; //strcpy(linhaoriginal,linha); int k; for (k = 0; k < ncol; k++) { p.remetente = getpid(); p.tipo = 5; p.linhaPoxx = k; p.linhaPoxy = posy-3; p.carater = linhaoriginal[k]; n=write(fd_ser,&p,sizeof(PEDIDO)); } char *blankusername = " "; mvwprintw(usersWindow,p.linhaPoxy+1,0,blankusername); refresh(); wrefresh(usersWindow); } } if(res>0 && FD_ISSET(0,&fontes)){ //teclado ch = getch(); int ret=0; switch (ch) { case 10: // enter key modo de navegação times+=1; if(times == 1){ memset( linhaoriginal,0,sizeof(linhaoriginal)); int k; for (k = 0; k < ncol; k++) { int c = (mvwinch(uiWindow,posy-3, k) & A_CHARTEXT); linhaoriginal[k] = c; } } edicao= !edicao; wclear(notificacaoWindow); //wbkgd(notificacaoWindow, COLOR_PAIR(1)); if(edicao == 0){ // se esta a 0 é porque antes estava a 1 ou seja tem informacao para enviar para o servidor memset( linha,0,sizeof(linha)); int k; for (k = 0; k < ncol; k++) { int c = (mvwinch(uiWindow,posy-3, k) & A_CHARTEXT); linha[k] = c; } ret = unlockline(posy,linha,1); if(ret==1){ //edicao=0; times = 0; wprintw(notificacaoWindow,"Modo de navegação no texto"); } else{ edicao=1; wprintw(notificacaoWindow,"Modo de edição da linha"); } move(posy,posx); refresh(); wrefresh(notificacaoWindow); } else if(edicao == 1){ //edicao a 1 manda info para o serv para bloquear a linha if(lockline(posy-3)==1){ wprintw(notificacaoWindow,"Modo de edição da linha"); /* backup da linha */ } else{ edicao= !edicao; wprintw(notificacaoWindow,"esta linha ja esta a ser editada"); } } move(posy,posx); wrefresh(notificacaoWindow); break; case KEY_BACKSPACE: if(edicao==1){ if(posx >3)posx--; /* move(posy,posx); delch();*/ p.remetente = getpid(); p.tipo = 5; p.linhaPoxx = posx; p.linhaPoxy = posy; p.carater = 8; n=write(fd_ser,&p,sizeof(PEDIDO)); } break; case KEY_DC://faz delete dos chars no screen if(edicao==1){ // delch(); p.remetente = getpid(); p.tipo = 5; p.linhaPoxx = posx; p.linhaPoxy = posy; p.carater = 9; n=write(fd_ser,&p,sizeof(PEDIDO)); } break; case 27: //ESC cancela a edicao no modo de edicao de linha if(edicao == 1){ edicao=0; //scr_restore("bak"); //strcpy(linha,linhaoriginal); int k; for (k = 0; k < ncol; k++) { p.remetente = getpid(); p.tipo = 5; p.linhaPoxx = k; p.linhaPoxy = posy-3; p.carater = linhaoriginal[k]; n=write(fd_ser,&p,sizeof(PEDIDO)); //mvwaddch(uiWindow,posy,k,linhaoriginal[k-3]); } unlockline(posy,linhaoriginal,0); move(posy,posx); wclear(notificacaoWindow); wprintw(notificacaoWindow,"Modo de navegação no texto"); move(posy,posx); refresh(); wrefresh(notificacaoWindow); wrefresh(uiWindow); } else if(edicao==0){ endwin(); logout(); } break; //condition ? consequence : alternative case KEY_UP: posy = (posy>3 && !edicao)?posy-1:posy; move(posy,posx); break; case KEY_DOWN: posy = (posy<((nrow+3)-1) && !edicao)?posy+1:posy; move(posy,posx); break; case KEY_LEFT: posx = (posx>3)?posx-1:posx; move(posy,posx); break; case KEY_RIGHT: posx = (posx < ((ncol+2)))?posx+1:posx; move(posy,posx); break; default : if(edicao == 1){ //envia o carater para o SERVIDOR //nao imprime para o ecra //recebe do servidor e imprime //strcpy(p.linha,linhatxt); //strcpy(p.username,username); p.remetente = getpid(); p.tipo = 5; p.linhaPoxx = posx-3; p.linhaPoxy = posy-3; p.carater = ch; n=write(fd_ser,&p,sizeof(PEDIDO)); //printf("Foi enviado ao serv o char:%d[%d,%d] %s\t", ch,posx,posy); //mvaddch(posy,posx,ch); //move carater if(posx<(ncol+2) && posx != (ncol+2)){ posx++; } // else{ posx = ncol+2; //posy++; } move(posy,posx); } break; } if(ch==KEY_UP || ch==KEY_DOWN|| ch==KEY_LEFT|| ch==KEY_RIGHT){ move(posy,posx); mvwprintw(notificacaoWindow,2,(ncol/2)-3, "(%d,%d) ",posy-3,posx-3); refresh(); wrefresh(notificacaoWindow); } } } while (posy!=(nrow-1) || posx!=(ncol-1)); wgetch(uiWindow); endwin(); if ( argv[optind] != NULL ) { int i ; puts("* Argumentos em excesso *") ; for(i=optind; argv[i] != NULL; i++) { printf("-- %s\n", argv[i]) ; } } return 0 ; }
C
#include <stdio.h> #include <math.h> int main(void) { double x1, x2, y1, y2; printf("ù° (x1, y1) : "); scanf("%lf %lf", &x1, &y1); printf("ι° (x2, y2) : "); scanf("%lf %lf", &x2, &y2); printf("Distance = %lf", sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)))); return 0; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 3 int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; int TCOUNT, COUNT_LIMIT; void *inc_count(void *t) { int j,i; double result=0.0; int my_id = (int)t; for (i=0; i < TCOUNT; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %d, count = %d Threshold reached. ", my_id, count); printf("Just sent signal.\n"); } printf("inc_count(): thread %d, count = %d, unlocking mutex\n", my_id, count); pthread_mutex_unlock(&count_mutex); /* Do some work so threads can alternate on mutex lock */ sleep(1); } pthread_exit(NULL); } void *watch_count(void *t) { int my_id = (int)t; printf("Starting watch_count(): thread %d\n", my_id); pthread_mutex_lock(&count_mutex); if (count < COUNT_LIMIT) { printf("watch_count(): thread %d going into wait...\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); count += 125; printf("watch_count(): thread %d Condition signal received.\n", my_id); printf("watch_count(): thread %d count now = %d.\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); } int main(int argc, char *argv[]) { int i, rc, t1=1, t2=2, t3=3; TCOUNT = atoi(argv[1]); COUNT_LIMIT = atoi(argv[2]); pthread_t threads[3]; /*1. Initialize mutex and condition variable objects */ pthread_mutex_init(&count_mutex, NULL); pthread_cond_init (&count_threshold_cv, NULL); pthread_create(&threads[0], NULL, watch_count, (void *)t1); pthread_create(&threads[1], NULL, inc_count, (void *)t2); pthread_create(&threads[2], NULL, inc_count, (void *)t3); /* 2. Wait for all threads to complete */ for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\n", NUM_THREADS, count); /* 3. Clean up and exit */ pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(NULL); }
C
#include<stdio.h> void main() { int n,m,k; printf("enter the values:"); scanf("%d %d",&n,&m); k=pow(n,m); printf("the answer is=%d",k); }
C
#include <stdio.h> #include <string.h> void main() { int c=0; char s[10]; char rev[10]; scanf("%s",s); int i=0; int j=0; while(s[i] != '\0') { c=c+1; i++; } for(i=c-1;i>=0;i--) { rev[i]=s[j]; j++; } rev[i]='\0'; printf("%s",rev); }
C
#include "commands.h" //---------------------------------------Functions only for reading Image File---------------------------------// void read_IMGFile(const char * imageFileName, TheImage * image) { FILE * imageFile; int readSize; imageFile = fopen(imageFileName, "rb"); if (!imageFile) { printf("ERROR: Unable to open image file\n"); exit(1); } //store the information from the image file into our struct fseek(imageFile, 0, SEEK_END); // read the file to the end to obtain the file size image->size = ftell(imageFile); rewind(imageFile); // rewind to file start image->buffer = (unsigned char*)calloc(image->size, sizeof(unsigned char)); //stores the content of the image file readSize = fread(image->buffer, sizeof(unsigned char), image->size, imageFile); image->numOfOpenFiles = 0; image->currDepth = 0; strcpy(image->filename, imageFileName); } BootSector read_Sector(const char * imageFileName) { BootSector boot; FILE * imageFile; imageFile = fopen(imageFileName, "rb"); if (!imageFile) { printf("ERROR: Unable to open image file"); exit(1); } //otain and store all BPB information using the offset and byte size from specification fseek(imageFile,11,SEEK_SET); fread(boot.BytsPerSec, sizeof(unsigned char),BytsSize, imageFile); fseek(imageFile,13,SEEK_SET); fread(boot.SecPerClus, sizeof(unsigned char),SecSize, imageFile); fseek(imageFile,14,SEEK_SET); fread(boot.RsvdSecCnt, sizeof(unsigned char),RsvdSize, imageFile); fseek(imageFile,16,SEEK_SET); fread(boot.NumFATs, sizeof(unsigned char),FATsSize, imageFile); fseek(imageFile,32,SEEK_SET); fread(boot.TotSec32, sizeof(unsigned char),Total32Size, imageFile); fseek(imageFile,36,SEEK_SET); fread(boot.FATSz32, sizeof(unsigned char),FAT32Size, imageFile); fseek(imageFile,44,SEEK_SET); fread(boot.RootClus, sizeof(unsigned char),RootSize, imageFile); return boot; } int Num_Clusters(const TheImage * image) { //divie the size of the FAT Region by 4 bytes to obtain the # of clusters return FAT_Size(image)/4; } int Cluster_Size(const TheImage * image) { return (Hex2Decimal(image->boot.BytsPerSec, BytsSize) * Hex2Decimal(image->boot.SecPerClus, SecSize)); } int FAT_Size(const TheImage * image) //obtain the size of the FAT Region { //obtain the decimal value of the FATSz32, NumFATS, and BytsPerSec in the bootsector struct int BPB_FATSz32 = Hex2Decimal(image->boot.FATSz32, FAT32Size); int BPB_NumFATs = Hex2Decimal(image->boot.NumFATs, FATsSize); int BPB_BytsPerSec = Hex2Decimal(image->boot.BytsPerSec, BytsSize); //multiply each value together to get the FAT region size int FATsize= BPB_FATSz32 * BPB_NumFATs * BPB_BytsPerSec; return FATsize; } void Read_FATRegion(const TheImage * image, int * FATRegion) { unsigned char cluster_arr[4]; int i; int k; int Fat_start=FAT_Index(image); int Data_start=DATA_Index(image); int size = 0; for (i = Fat_start; i < Data_start; i = i + 4) //start from the begining of the FAT Region, until the begining of DATA Region { for (k = 0; k < 4; k++) //read every 4 bytes and turn into decimal value { cluster_arr[k] = image->buffer[i+k]; } FATRegion[size++] = Hex2Decimal(cluster_arr,4); } } int FAT_Index(const TheImage * image) { // get the size of the reseved region and that is your start index for the Fat refion return RSRVD_Size(image); } int DATA_Index(const TheImage * image) { // add the size of the Reserved region with FAT region to get the start index of the Data Region return RSRVD_Size(image) + FAT_Size(image); } int RSRVD_Size(const TheImage * image) //obtain the size of the Reserved Region { int BPB_BytsPerSec = Hex2Decimal(image->boot.BytsPerSec, BytsSize); int BPB_RsvdSecCnt = Hex2Decimal(image->boot.RsvdSecCnt, RsvdSize); int RSRVDsize= BPB_BytsPerSec * BPB_RsvdSecCnt ; return RSRVDsize; } void read_Entries_from_Dir(const TheImage * image, DirectoryEntry dirEntries[], int clusterNum, int *entryCount) { if(clusterNum < 2) clusterNum = 2; if(clusterNum > (Num_Clusters(image)+2)) clusterNum = (Num_Clusters(image)+2); int ass_clusters[200]; // [ass]ociated [clusters] find_Clusters_Associated(image, clusterNum, ass_clusters); *entryCount = 0; int i = 0; unsigned char tempcluster[Cluster_Size(image)]; find_Cluster(image, ass_clusters[i], tempcluster); int j = 1; while(j <= 8) { DirectoryEntry temp = read_Entry(tempcluster, j); if(temp.attributes[0] != 0x00) // dir is empty { dirEntries[(*entryCount)++] = temp; } j++; } i++; } // get array of associated characters void find_Clusters_Associated(const TheImage * image, int strtCluster, int * ass_clusters) { if(strtCluster < 2) strtCluster = 2; if(strtCluster > (Num_Clusters(image)+2)) strtCluster = (Num_Clusters(image)+2); int region[Num_Clusters(image)]; int i = 0; Read_FATRegion(image, region); while(region[strtCluster] != 0 && region[strtCluster] < 0x0FFFF8) { ass_clusters[i++] = strtCluster; strtCluster = region[strtCluster]; } ass_clusters[i++] = strtCluster; ass_clusters[i] = -1; // had to add this line because there needs to be an endpoint set } // function for getting the bytes from a cluster void find_Cluster(const TheImage * image, int currClusterNum, unsigned char * theCluster) { if(currClusterNum < 2) currClusterNum = 2; if(currClusterNum > ((Num_Clusters(image))+2)) currClusterNum = ((Num_Clusters(image))+2); int index = DATA_Index(image) + (currClusterNum - 2) * Cluster_Size(image); int i; for(i = 0; i < Cluster_Size(image); i++) { theCluster[i] = image->buffer[index+i]; } } DirectoryEntry read_Entry(const unsigned char * theCluster, int entryNum) { DirectoryEntry entry; entryNum--; int index = 32 + (64 * (entryNum)); memcpy(entry.dirName, theCluster + index, 11); index = index + 11; memcpy(entry.attributes, theCluster + index, 1); index = index + 1; memcpy(entry.ntres, theCluster + index, 1); index = index + 1; memcpy(entry.tenthSecCreated, theCluster + index, 1); index = index + 1; memcpy(entry.timeCreated, theCluster + index, 2); index = index + 2; memcpy(entry.dateCreated, theCluster + index, 2); index = index + 2; memcpy(entry.lastAccessed, theCluster + index, 2); index = index + 2; memcpy(entry.fstClusHI, theCluster + index, 2); index = index + 2; memcpy(entry.writeTime, theCluster + index, 2); index = index + 2; memcpy(entry.writeDate, theCluster + index, 2); index = index + 2; memcpy(entry.fstClusLO, theCluster + index, 2); index = index + 2; memcpy(entry.size, theCluster + index, 4); index = index + 4; return entry; } int get_AvailableCluster(const TheImage * image) //perform a linear search over the FAT until an empty clushter is found { int FAT[Num_Clusters(image)]; // creat a FAT array with the num of clusters Read_FATRegion(image, FAT); // stores FAT region into int array int i = Hex2Decimal(image->boot.RootClus, RootSize); while(i< Num_Clusters(image)){ if (FAT[i] == 0) return i; i++; } return -1; } DirectoryEntry create_DIRENTRY(const char * Filename, unsigned char attr, unsigned int availablecluster) { DirectoryEntry dirEntry; int i=0; int fileSize; if(strlen(Filename) <= 11) fileSize= strlen(Filename); while(i < fileSize) { dirEntry.dirName[i] = (unsigned char) Filename[i]; i++; } i=fileSize; while( i < 11) { dirEntry.dirName[i] = 0x00; i++; } dirEntry.attributes[0] = attr; // Set DIR_Attr to ATTR_ARCHIVE dirEntry.ntres[0] = 0x00; // Set DIR_NTRes, reserved. unsigned char bytes[4]; bytes[0] = availablecluster & 0xFF; bytes[1] = (availablecluster >> 8) & 0xFF; bytes[2] = (availablecluster >> 16) & 0xFF; bytes[3] = (availablecluster >> 24) & 0xFF; dirEntry.fstClusLO[0] = bytes[0]; //Set DIR_FstClusLO nad DIR_FstClusHI after converting bytes to unsigned chars dirEntry.fstClusLO[1] = bytes[1]; dirEntry.fstClusHI[0] = bytes[2]; dirEntry.fstClusHI[1] = bytes[3]; while(i<4) //Set DIR_FileSize =0; { dirEntry.size[i] = 0x00; i++; } return dirEntry; } void Update_FATEntry(const TheImage * image, int cluster, unsigned char * empty_clus) { int FATindexpos = FAT_Index(image); int position = FATindexpos + cluster * 4; //obtain the correct position located in the buffer int i=0; while(i<4) { image->buffer[position+i] = empty_clus[i]; //insert )xFFFFFFFF i++; } } bool add_DIRENTRY(const TheImage * image, DirectoryEntry newEntry, int cluster) { int i, j; int position = DATA_Index(image) + (cluster - 2) * Cluster_Size(image);//obtain the correct position located in the buffer // check for the first empty space int clusterPos = -1; for (i = 0; i < 8; i++) { for (j = 0; j < 64; j++) { if (image->buffer[position + j + (i * 64)] != 0x00) break; else if (j == 63) clusterPos = i; } if (clusterPos != -1) break; } position += (clusterPos * 64) + 32; for (i = 0; i <11; i++) image->buffer[position++] = newEntry.dirName[i]; for (i = 0; i < 1; i++) image->buffer[position++] = newEntry.attributes[i]; for (i = 0; i < 1; i++) image->buffer[position++] = newEntry.ntres[i]; for (i = 0; i < 1; i++) image->buffer[position++] = newEntry.tenthSecCreated[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.timeCreated[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.dateCreated[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.lastAccessed[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.fstClusHI[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.writeTime[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.writeDate[i]; for (i = 0; i < 2; i++) image->buffer[position++] = newEntry.fstClusLO[i]; for (i = 0; i < 4; i++) image->buffer[position++] = newEntry.size[i]; return true; }
C
#include <stdio.h> #include <ctype.h> int stack[1000]; #define SIZE_OF 1000 int i = 0; int evalute_prefix_boolean_expersion(char c[]); int stack_isnt_empty(); int is_op(char a); void push(char s); void make_boolean_expersion_to_prefix(char c[], char g[]); char pop(); int pop_int(); void push_int(); int main() { char c[] = "(~1 | 1) | 0"; char v[1000]; make_boolean_expersion_to_prefix(c, v); printf("\n%s", v); int h = evalute_prefix_boolean_expersion(v); printf("\n%d",h); return 0; } void make_boolean_expersion_to_prefix(char array[], char copy[]) { int i; int j = 0; int is_exit_op = 0; for (i = 0; array[i] != '\0'; i++) { if (isdigit(array[i])) copy[j++] = array[i]; else if (is_op(array[i])) { push(array[i]); printf("\n%c", array[i]); } else if (array[i] == ')') while (stack_isnt_empty()) copy[j++] = pop(); else if (array[i] == '~') { copy[j++] = array[i + 1]; copy[j++] = array[i]; i++; } } while (stack_isnt_empty()) copy[j++] = pop(); copy[j] = '\0'; } int evalute_prefix_boolean_expersion(char prefix[]) { int i; int number1, number2; for (i = 0; prefix[i] != '\0'; i++) { if (isdigit(prefix[i])) push_int(prefix[i] - '0'); else if (is_op(prefix[i])) { number1 = pop_int(); number2 = pop_int(); switch (prefix[i]) { case '|': push_int(number1 | number2); break; case '&': push_int(number1 & number2); break; } } else if (prefix[i] == '~') { number1 = pop(); if (number1 == 1) push_int(0); else push_int(1); } } return pop_int(); } void push(char a) { extern int i, stack[]; if (i < SIZE_OF) stack[i++] = a; else printf("\nyour stack is full"); } char pop() { extern int i, stack[]; if (i > 0) return stack[--i]; printf("\nyour stack is empty"); return 0; } int stack_isnt_empty() { extern int i; if (i > 0) return 1; return 0; } int is_op(char s) { if (s == '|' || s == '&') return 1; return 0; } void push_int(int a) { extern int i, stack[]; if (i < SIZE_OF) stack[i++] = a; else printf("\nyour stack is full"); } int pop_int() { extern int i, stack[]; if (i > 0) return stack[--i]; printf("\nyour stack is empty"); return 0; }
C
#include <stdio.h> #include <string.h> #include "mpi.h" #include <time.h> int main(int argc , char * argv[]) { int my_rank; /* rank of process */ int p; /* number of process */ int source; /* rank of sender */ int dest; /* rank of reciever */ int tag = 0; /* tag for messages */ int message; /* storage for message */ MPI_Status status; /* return status for */ /* recieve */ /* Start up MPI */ MPI_Init( &argc , &argv ); /* Find out process rank */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); /* Find out number of process */ MPI_Comm_size(MPI_COMM_WORLD, &p); time_t sto = time(NULL); int st, en , r,rem; if (my_rank == 0 ){ st = 2 ; en = 9; r= (en-st+1)/p; } MPI_Bcast( &st,1, MPI_INT,0, MPI_COMM_WORLD); MPI_Bcast( &r,1, MPI_INT,0, MPI_COMM_WORLD); MPI_Bcast( &en,1, MPI_INT,0, MPI_COMM_WORLD); int i , beg=st+r*my_rank,subCount=0,TotalCount; if (my_rank == p-1){ r = (en-beg); } printf("beg is %d r is %d \n" , beg,r); for (i=0; i < r ; ++i){ int j,prime = 0; if (beg == 2 ) ++prime; for (j=2; j <beg; ++j){ if (beg%j == 0 )prime++;} if(prime==0)++subCount; beg++; } MPI_Reduce(&subCount,&TotalCount,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD); if (my_rank == 0){ printf("total is %d \n" , TotalCount); printf("time is %.2f\n", (double)(time(NULL) - sto)); } /* shutdown MPI */ MPI_Finalize(); return 0; }
C
/******************************************************************** * $ID: main.c Wed 2016-10-19 09:39:02 +0800 lz * * * * Description: * * * * Maintainer: (lizhu) <[email protected]> * * * * CopyRight (c) 2016 ZHYTEK * * All rights reserved. * * * * This file is free software; * * you are free to modify and/or redistribute it * * under the terms of the GNU General Public Licence (GPL). * * * * Last modified: * * * * No warranty, no liability, use this at your own risk! * ********************************************************************/ // unsigned int strlen (char *s); // strlen()用来计算指定的字符串s 的长度,不包括结束字符"\0"。 // 注意一下字符数组,例如 // char str[100] = "http://see.xidian.edu.cn/cpp/u/biaozhunku/"; // 定义了一个大小为100的字符数组,但是仅有开始的11个字符被初始化了,剩下的都是0,所以 sizeof(str) 等于100,strlen(str) 等于11。 //如果字符的个数等于字符数组的大小,那么strlen()的返回值就无法确定了,例如 // char str[6] = "abcxyz"; // strlen(str)的返回值将是不确定的。因为str的结尾不是0,strlen()会继续向后检索,直到遇到'\0',而这些区域的内容是不确定的。 // // 注意:strlen() 函数计算的是字符串的实际长度,遇到第一个'\0'结束。如果你只定义没有给它赋初值,这个结果是不定的,它会从首地址一直找下去,直到遇到'\0'停止。而sizeof返回的是变量声明后所占的内存数,不是实际长度,此外sizeof不是函数,仅仅是一个操作符,strlen()是函数。 // #include<stdio.h> // #include<string.h> // int main() // { // char *str1 = "http://see.xidian.edu.cn/cpp/u/shipin/"; // char str2[100] = "http://see.xidian.edu.cn/cpp/u/shipin_liming/"; // char str3[5] = "12345"; // printf("strlen(str1)=%d, sizeof(str1)=%d\n", strlen(str1), sizeof(str1)); // printf("strlen(str2)=%d, sizeof(str2)=%d\n", strlen(str2), sizeof(str2)); // printf("strlen(str3)=%d, sizeof(str3)=%d\n", strlen(str3), sizeof(str3)); // return 0; // } // #include <stdio.h> #include <string.h> int main() { char str[100]; int i; char cc; printf("please input str:"); scanf("%s",str); printf("please input cc:"); getchar(); scanf("%c",&cc); for(i = 0; i < strlen(str); i++) { if(str[i] == cc) { printf("%d\n", i); } } return 0; } /********************* End Of File: main.c *********************/
C
#include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> int main(int argc,char *argv[]) { FILE *fp; int sockfd,newsockfd,portno,r; char fname[100],fname1[100],text[100]; struct sockaddr_in serv_addr; portno = atoi(argv[2]); sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<0) { printf("Error on socket creation\n"); exit(0); } else printf("socket created\n"); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr(argv[1]); serv_addr.sin_port=htons(portno); if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0) { printf("Error in Connection...\n"); exit(0); } else printf("Connected...\n"); //memset(fname,'\0',100); //memset(fname1,'\0',100); //memset(text,'\0',100); printf("Enter the filename existing in the server:\n"); scanf("%s",fname); printf("Enter the filename to be written to:\n"); scanf("%s",fname1); fp=fopen(fname1,"w"); send(sockfd,fname,100,0); while(1) { r=recv(sockfd,text,100,0); text[r]='\0'; fprintf(fp,"%s",text); if(strcmp(text,"error")==0) printf("file not available\n"); if(strcmp(text,"Done")==0) { printf("file is transferred\n"); fclose(fp); close(sockfd); break; } else fputs(text,stdout); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "binarieTree.h" #include "binarieTree.c" int main(){ bTree novaArv; Node *bsc; criaArv(&novaArv); inserirRaiz(&novaArv, 55); inserirValor(novaArv, 72); inserirValor(novaArv, 30); inserirValor(novaArv, 25); inserirValor(novaArv, 80); inserirValor(novaArv, 90); inserirValor(novaArv, 15); inserirValor(novaArv, 40); novaArv = delete(novaArv, 90); inOrdem(novaArv); bsc = busca(novaArv, 30); /*Busca o nó com valor 30 e atribui a bsc*/ /*Printa o nó e seus filhos esquerdo e direito*/ printf("o no buscado foi o: %d\n", bsc->data); printf("o filho a direita eh: %d\n", bsc->right->data); printf("o filho a esquerda eh: %d\n", bsc->left->data); novaArv = liberar(novaArv); /*Limpa a árvore da memória*/ ta_Vazia(novaArv); /*Verifica se a árvore está vazia*/ return 0; }
C
/**************getSource.c************/ #include <stdio.h> #include <string.h> #include "getSource.h" #define MAXLINE 120 /* 1行の最大文字数 */ #define MAXERROR 30 /* これ以上のエラーがあったら終り */ #define MAXNUM 14 /* 定数の最大桁数 */ #define TAB 5 /* タブのスペース */ static FILE *sourceFile; /* ソースファイル */ static FILE *targetFile; /* LaTeX出力ファイル */ static char line[MAXLINE]; /* 1行分の入力バッファー */ static int lineIndex = -1; /* 次に読む文字の位置 */ static char ch; /* 最後に読んだ文字 */ static Token currentToken; /* 最後に読んだトークン */ static KindT idKind; /* 現トークン(Identifier)の種類 */ static int spaces; /* そのトークンの前のスペースの個数 */ static int CR; /* その前のCRの個数 */ static int printed = 0; /* トークンは印字済みか */ static int errorNo = 0; /* 出力したエラーの数 */ static char nextChar(); /* 次の文字を読む関数 */ static int isKeySym(KeyId k); /* tは記号か? */ static int isKeyWd(KeyId k); /* tは予約語か? */ static void printSpaces(); /* トークンの前のスペースの印字 */ static void printCurrentToken(); /* トークンの印字 */ static void writeInitCodeToTargetFile(FILE *targetFile); struct keyWd { /* 予約語や記号と名前(KeyId) */ char *word; KeyId keyId; }; static struct keyWd KeyWdT[] = { /* 予約語や記号と名前(KeyId)の表 */ {"begin", Begin}, {"end", End}, {"if", If}, {"then", Then}, {"while", While}, {"do", Do}, {"return", Ret}, {"function", Func}, {"var", Var}, {"const", Const}, {"odd", Odd}, {"write", Write}, {"writeln", WriteLn}, {"$dummy1", end_of_KeyWd}, /* 記号と名前(KeyId)の表 */ {"+", Plus}, {"-", Minus}, {"*", Mult}, {"/", Div}, {"(", Lparen}, {")", Rparen}, {"=", Equal}, {"<", Lss}, {">", Gtr}, {"<>", NotEq}, {"<=", LssEq}, {">=", GtrEq}, {",", Comma}, {".", Period}, {";", Semicolon}, {":=", Assign}, {"$dummy2", end_of_KeySym} }; int isKeyWd(KeyId k) /* キーkは予約語か? */ { return (k < end_of_KeyWd); } int isKeySym(KeyId k) /* キーkは記号か? */ { if (k < end_of_KeyWd) return 0; return (k < end_of_KeySym); } /* 文字の種類を示す表にする */ static KeyId charClassT[256]; static void initCharClassT(KeyId *charClassT) /* 文字の種類を示す表を作る関数 */ { int i; for (i = 0; i < 256; i++) charClassT[i] = others; for (i = '0'; i <= '9'; i++) charClassT[i] = digit; for (i = 'A'; i <= 'Z'; i++) charClassT[i] = letter; for (i = 'a'; i <= 'z'; i++) charClassT[i] = letter; charClassT['+'] = Plus; charClassT['-'] = Minus; charClassT['*'] = Mult; charClassT['/'] = Div; charClassT['('] = Lparen; charClassT[')'] = Rparen; charClassT['='] = Equal; charClassT['<'] = Lss; charClassT['>'] = Gtr; charClassT[','] = Comma; charClassT['.'] = Period; charClassT[';'] = Semicolon; charClassT[':'] = colon; } /* Ref: ソースファイルのopen */ int openSourceAndTarget(char *sourceFileName, char *targetFileName) { /* open source file */ if ((sourceFile = fopen(sourceFileName, "r")) == NULL) { printf("can't open %s\n", sourceFileName); return 0; } /* open target file */ if ((targetFile = fopen(targetFileName, "w")) == NULL) { printf("can't open %s\n", targetFileName); return 0; } return 1; } /* ソースファイルと.texファイルをclose */ void closeSourceAndTarget() { fclose(sourceFile); fclose(targetFile); } /* New: initialize env */ void writeInitCodeToTargetFile(FILE *targetFile) { fprintf(targetFile, "\\documentstyle[12pt]{article}\n"); /* LaTeXコマンド */ fprintf(targetFile, "\\begin{document}\n"); fprintf(targetFile, "\\fboxsep=0pt\n"); fprintf(targetFile, "\\def\\insert#1{$\\fbox{#1}$}\n"); fprintf(targetFile, "\\def\\delete#1{$\\fboxrule=.5mm\\fbox{#1}$}\n"); fprintf(targetFile, "\\rm\n"); } /* Ret: initialize env */ void initSource() { ch = '\n'; printed = 1; initCharClassT(charClassT); writeInitCodeToTargetFile(targetFile); } /* period ends file */ void finalSource() { if (currentToken.kind == Period) printCurrentToken(); else errorInsert(Period); fprintf(targetFile, "\n\\end{document}\n"); } /* 通常のエラーメッセージの出力の仕方(参考まで) */ /* void error(char *m) { if (lineIndex > 0) printf("%*s\n", lineIndex, "***^"); else printf("^\n"); printf("*** error *** %s\n", m); errorNo++; if (errorNo > MAXERROR){ printf("too many errors\n"); printf("abort compilation\n"); exit (1); } } */ void errorNoCheck() /* エラーの個数のカウント、多すぎたら終わり */ { if (errorNo++ > MAXERROR) { fprintf(targetFile, "too many errors\n\\end{document}\n"); printf("abort compilation\n"); exit(1); } } void errorType(char *m) /* 型エラーを.texファイルに出力 */ { printSpaces(); fprintf(targetFile, "\\(\\stackrel{\\mbox{\\scriptsize %s}}{\\mbox{", m); printCurrentToken(); fprintf(targetFile, "}}\\)"); errorNoCheck(); } void errorInsert(KeyId k) /* keyString(k)を.texファイルに挿入 */ { if (k < end_of_KeyWd) /* 予約語 */ fprintf(targetFile, "\\ \\insert{{\\bf %s}}", KeyWdT[k].word); else /* 演算子か区切り記号 */ fprintf(targetFile, "\\ \\insert{$%s$}", KeyWdT[k].word); errorNoCheck(); } void errorMissingId() /* 名前がないとのメッセージを.texファイルに挿入 */ { fprintf(targetFile, "\\insert{Identifier}"); errorNoCheck(); } void errorMissingOp() /* 演算子がないとのメッセージを.texファイルに挿入 */ { fprintf(targetFile, "\\insert{$\\otimes$}"); errorNoCheck(); } void errorDelete() /* 今読んだトークンを読み捨てる */ { int i = (int) currentToken.kind; printSpaces(); printed = 1; if (i < end_of_KeyWd) /* 予約語 */ fprintf(targetFile, "\\delete{{\\bf %s}}", KeyWdT[i].word); else if (i < end_of_KeySym) /* 演算子か区切り記号 */ fprintf(targetFile, "\\delete{$%s$}", KeyWdT[i].word); else if (i == (int) Identifier) /* Identfier */ fprintf(targetFile, "\\delete{%s}", currentToken.u.id); else if (i == (int) Num) /* Num */ fprintf(targetFile, "\\delete{%d}", currentToken.u.value); } void errorMessage(char *m) /* エラーメッセージを.texファイルに出力 */ { fprintf(targetFile, "$^{%s}$", m); errorNoCheck(); } void errorF(char *m) /* エラーメッセージを出力し、コンパイル終了 */ { errorMessage(m); fprintf(targetFile, "fatal errors\n\\end{document}\n"); if (errorNo) printf("total %d errors\n", errorNo); printf("abort compilation\n"); exit(1); } int errorN() /* エラーの個数を返す */ { return errorNo; } char nextChar() /* 次の1文字を返す関数 */ { char ch; if (lineIndex == -1) { if (fgets(line, MAXLINE, sourceFile) != NULL) { /* puts(line); */ /* 通常のエラーメッセージの出力の場合(参考まで) */ lineIndex = 0; } else { errorF("end of file\n"); /* end of fileならコンパイル終了 */ } } if ((ch = line[lineIndex++]) == '\n') { /* chに次の1文字 */ lineIndex = -1; /* それが改行文字なら次の行の入力準備 */ return '\n'; /* 文字としては改行文字を返す */ } return ch; } /* 次のトークンを読んで返す関数 */ Token nextToken() { int i = 0; int num; KeyId cc; Token temp; /* identifier */ char identifierName[MAXNAME]; printCurrentToken(); /* 前のトークンを印字 */ spaces = 0; CR = 0; /* 次のトークンまでの空白や改行をカウント */ while (1) { if (ch == ' ') spaces++; else if (ch == '\t') spaces += TAB; else if (ch == '\n') { spaces = 0; CR++; } else break; ch = nextChar(); } /* 空白出ないchに対して */ switch (cc = charClassT[ch]) { case letter: /* identifier */ /* while letter or digit */ do { if (i < MAXNAME) identifierName[i] = ch; i++; ch = nextChar(); } while (charClassT[ch] == letter || charClassT[ch] == digit); if (i >= MAXNAME) { errorMessage("too long"); i = MAXNAME - 1; } /* end of identifier */ identifierName[i] = '\0'; /* 全ての予約語をチェック。 */ for (i = 0; i < end_of_KeyWd; i++) if (strcmp(identifierName, KeyWdT[i].word) == 0) { temp.kind = KeyWdT[i].keyId; currentToken = temp; printed = 0; return temp; } temp.kind = Identifier; /* ユーザの宣言した名前の場合 */ strcpy(temp.u.id, identifierName); break; case digit: /* number */ num = 0; do { num = 10 * num + (ch - '0'); i++; ch = nextChar(); } while (charClassT[ch] == digit); if (i > MAXNUM) errorMessage("too large"); temp.kind = Num; temp.u.value = num; break; case colon: if ((ch = nextChar()) == '=') { ch = nextChar(); temp.kind = Assign; /* ":=" */ break; } else { temp.kind = nul; break; } case Lss: if ((ch = nextChar()) == '=') { ch = nextChar(); temp.kind = LssEq; /* "<=" */ break; } else if (ch == '>') { ch = nextChar(); temp.kind = NotEq; /* "<>" */ break; } else { temp.kind = Lss; break; } case Gtr: if ((ch = nextChar()) == '=') { ch = nextChar(); temp.kind = GtrEq; /* ">=" */ break; } else { temp.kind = Gtr; break; } default: temp.kind = cc; ch = nextChar(); break; } currentToken = temp; printed = 0; return temp; } /* t.kind == k のチェック */ /* t.kind == k なら、次のトークンを読んで返す */ /* t.kind != k ならエラーメッセージを出し、t と k が共に記号、または予約語なら */ /* t を捨て、次のトークンを読んで返す( t を k で置き換えたことになる) */ /* それ以外の場合、k を挿入したことにして、t を返す */ Token checkTokenAndGetNextToken(Token t, KeyId k) { if (t.kind == k) return nextToken(); if ((isKeyWd(k) && isKeyWd(t.kind)) || (isKeySym(k) && isKeySym(t.kind))) { errorDelete(); errorInsert(k); return nextToken(); } errorInsert(k); return t; } static void printSpaces() /* 空白や改行の印字 */ { while (CR-- > 0) fprintf(targetFile, "\\ \\par\n"); while (spaces-- > 0) fprintf(targetFile, "\\ "); CR = 0; spaces = 0; } /* 現在のトークンの印字 */ void printCurrentToken() { int i = (int) currentToken.kind; if (printed) { printed = 0; return; } printed = 1; printSpaces(); /* トークンの前の空白や改行印字 */ if (i < end_of_KeyWd) /* 予約語 */ fprintf(targetFile, "{\\bf %s}", KeyWdT[i].word); else if (i < end_of_KeySym) /* 演算子か区切り記号 */ fprintf(targetFile, "$%s$", KeyWdT[i].word); else if (i == (int) Identifier) { /* Identfier */ switch (idKind) { case varId: fprintf(targetFile, "%s", currentToken.u.id); return; case parId: fprintf(targetFile, "{\\sl %s}", currentToken.u.id); return; case funcId: fprintf(targetFile, "{\\it %s}", currentToken.u.id); return; case constId: fprintf(targetFile, "{\\sf %s}", currentToken.u.id); return; } } else if (i == (int) Num) /* Num */ fprintf(targetFile, "%d", currentToken.u.value); } void setIdKind(KindT k) /* 現トークン(Identifier)の種類をセット */ { idKind = k; }
C
#include "types.h" #include "stat.h" #include "user.h" #define NUM_OF_CHILDRENS 10 #define NUM_OF_CHILD_LOOPS 1000 int main(int argc, char *argv[]) { int i,j,index,wTime,rTime,ioTime = 0; int fork_id = 1; int c_array[NUM_OF_CHILDRENS][4]; for (i=0 ; i < NUM_OF_CHILDRENS ; i++) // init array for (j=0 ; j < 4 ; j++) c_array[i][j] = 0; for (i=0 ; i < NUM_OF_CHILDRENS && fork_id !=0; i++) { fork_id = fork(); if (fork_id == 0) { for (j=0 ; j < NUM_OF_CHILD_LOOPS ; j++) printf(2,"child <%d> prints for the <%d>\n",getpid(),j); exit(); } } while ((fork_id = wait2(&wTime,&rTime,&ioTime)) > 0) { c_array[index][0] = fork_id; c_array[index][1] = wTime; // waiting time c_array[index][2] = rTime; // run time c_array[index][3] = wTime+ioTime+rTime; // turnaround time -> end time - creation time index++; } for (index = 0 ; index < NUM_OF_CHILDRENS ; index++) { printf(2,"Child <%d>: Waiting time %d , Running time %d , Turnaround time %d\n",c_array[index][0],c_array[index][1],c_array[index][2],c_array[index][3]); } exit(); }
C
/* *********************************************************************** File Name : p2p_sys_list.c Description : P2Pミドルウエア リスト構造操作関数定義 Remark : Copyright (c) 2004 by Matsushita Electric Industrial Co., Ltd 作成日: 2004/06/21 T.Inagaki 新規作成 修正日: 2011/06/30 Yoshino *********************************************************************** */ #include "p2p_sys_def.h" #include "p2p_sys_moduleID.h" #include "p2p_sys_lock.h" #include "p2p_sys_list.h" #include "p2p_sys_def.h" #include "p2p_sys.h" #include "p2p_sys_print.h" /* *********************************************************************** Function : P2P_SYS_ListInit() Description : リスト構造初期化 Input : ST_P2P_SYS_List**:リストの先頭ポインタ Output : INT8: RET_NOERR:成功、 RET_INVALID_ARGS:パラメータ異常 Date : 2004/06/21 新規作成 *********************************************************************** */ INT8 P2P_SYS_ListInit( ST_P2P_SYS_List **ppListHead) { if(!ppListHead) { return(RET_INVALID_ARGS); } *ppListHead = NULL; return(RET_NOERR); } /* *********************************************************************** Function : P2P_SYS_ListAdd() Description : リストへの追加 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List**: リストの先頭ポインタ : ST_P2P_SYS_List*: 追加するリスト Output : RET_NOERR: 成功、RET_INVALID_ARGS:パラメータ異常 : その他:その他のエラー Date : 2004/06/21 新規作成 *********************************************************************** */ INT8 P2P_SYS_ListAdd( LOCK_TYPE *pLock, ST_P2P_SYS_List **ppListHead, ST_P2P_SYS_List *pNew) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListAdd]" { INT8 Rval = RET_UNKNOWN_ERR; ST_P2P_SYS_List *pList; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); if(!ppListHead || !pNew) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s parameter illegal", FUNC_NAME)); return(RET_INVALID_ARGS); } /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(RET_UNKNOWN_ERR); } } if(*ppListHead) { pList = *ppListHead; while(pList->pNext) { pList = pList->pNext; } pList->pNext = pNew; } else { *ppListHead = pNew; } pNew->pNext = NULL; Rval = RET_NOERR; /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(%d)", FUNC_NAME, Rval)); return(Rval); } /* *********************************************************************** Function : P2P_SYS_ListAddOnTop() Description : リストの先頭へのデータの追加 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List**: リストの先頭ポインタ : ST_P2P_SYS_List*: 追加するデータ Output : RET_NOERR: 成功、RET_INVALID_ARGS:パラメータ異常 : その他:その他のエラー Date : 2004/06/21 新規作成 *********************************************************************** */ INT8 P2P_SYS_ListAddOnTop( LOCK_TYPE *pLock, ST_P2P_SYS_List **ppListHead, ST_P2P_SYS_List *pNew) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListAddComOnTop]" { INT8 Rval = RET_UNKNOWN_ERR; ST_P2P_SYS_List *pList; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); if(!ppListHead || !pNew) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s parameter illegal",FUNC_NAME)); return(RET_INVALID_ARGS); } /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(RET_UNKNOWN_ERR); } } pList = *ppListHead; *ppListHead = pNew; pNew->pNext = pList; Rval = RET_NOERR; /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(%d)", FUNC_NAME,Rval)); return(Rval); } /* *********************************************************************** Function : P2P_SYS_ListDelete() Description : リストから項目の削除 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List**: リストの先頭ポインタ : ST_P2P_SYS_List*: 削除すべきリスト Output : INT8: RET_NOERR:正常終了、 RET_INVALID_ARGS:パラメータ異常 その他:その他のエラー Date : 2004/06/21 新規作成 *********************************************************************** */ INT8 P2P_SYS_ListDelete( LOCK_TYPE *pLock, ST_P2P_SYS_List **ppListHead, ST_P2P_SYS_List *pNew) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListDelete]" { INT8 Rval = RET_UNKNOWN_ERR; ST_P2P_SYS_List *pList, *pListFwd; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); if(!ppListHead || !pNew) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s parameter illegal", FUNC_NAME)); return(RET_INVALID_ARGS); } /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(RET_UNKNOWN_ERR); } } if(*ppListHead != NULL) { pListFwd = pList = *ppListHead; while(pList != NULL) { if(pList == pNew) { break; } pListFwd = pList; pList = pListFwd->pNext; } if(pList) { if(pList == *ppListHead) { /* it's the head of the list */ *ppListHead = pList->pNext; } else { pListFwd->pNext = pList->pNext; } Rval = RET_NOERR; } else { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s cannot delete the contents", FUNC_NAME)); } } /* if(*ppListHead) */ else { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s no contents", FUNC_NAME)); } /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(%d)", FUNC_NAME,Rval)); return(Rval); } /* *********************************************************************** Function : P2P_SYS_ListGet() Description : リストから所望の項目の取得 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List*: リストの先頭 : INT8 (*)(ST_P2P_SYS_List, void*):所望の項目を選び出す関数 : void*: 上記関数の第2引数に指定するポインタ Output : ST_P2P_SYS_List*: 所望の項目へのポインタ Date : 2004/06/21 新規作成 リストに選択された全ての項目に対して選択関数がコールされる。 選択関数がRET_NOERRを返答したときに処理を終了し、その項目へのポインタを リターンする。 *********************************************************************** */ ST_P2P_SYS_List* P2P_SYS_ListGet( LOCK_TYPE *pLock, ST_P2P_SYS_List *pListHead, INT8 (*fn)(ST_P2P_SYS_List*, void*), void *pVoid) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListGet]" { ST_P2P_SYS_List *pList; ST_P2P_SYS_List *pListReturn = NULL; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); if(!fn) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s parameter illegal", FUNC_NAME)); return(NULL); } /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(NULL); } } pList = pListHead; while(pList) { if(RET_NOERR == fn(pList, pVoid)) { pListReturn = pList; break; } pList = pList->pNext; } /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(0x%08X)", FUNC_NAME, pListReturn)); return(pListReturn); } /* *********************************************************************** Function : P2P_SYS_ListGetNext() Description : リストの先頭項目を取り出す。 Input : LOCK_TYPE*: 排他定数へのポインタ : ST_P2P_SYS_List*: リストの先頭番地 Output : ST_P2P_SYS_List*: リストの先頭項目へのポインタ リストに項目がない場合はNULL Date : 2004/06/21 新規作成 *********************************************************************** */ ST_P2P_SYS_List* P2P_SYS_ListGetNext( LOCK_TYPE *pLock, ST_P2P_SYS_List *pListHead) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListGetNext]" { ST_P2P_SYS_List *pListReturn = NULL; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(NULL); } } pListReturn = pListHead; /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(0x%08X)", FUNC_NAME, pListReturn)); return(pListReturn); } /* *********************************************************************** Function : P2P_SYS_ListSort() Description : リストの項目をバブルソートをかける Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List*: リストの先頭番地へのポインタ : INT8 (*)(void*, void*, void*):リストの並び替えを評価する ための関数。 : void*: 評価関数の第3引数に指定されるポインタ Output : INT8: LIST_CHANGED:順番が変更された LIST_NOT_CHANGE:順番が変更されなかった Date : 2004/06/21 新規作成 リストの隣り合う全ての項目を第1引数、第2引数にして評価関数が呼び出される。 評価関数は第1引数と第2引数の順番を入れ替えるならLIST_ROTATEを返す。 *********************************************************************** */ INT8 P2P_SYS_ListSort( LOCK_TYPE *pLock, ST_P2P_SYS_List **ppListHead, INT8 (*fnCompare)(void*, void*, void*), void *pVoid) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListSort]" { UINT8 byFlag, byChanged; ST_P2P_SYS_List *pReqTmp1, *pReqTmp2, *pReqFront; if(!ppListHead || !fnCompare) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s illegal ReqBuff or fnCompare is Specified", FUNC_NAME)); return(RET_INVALID_ARGS); } byChanged = 0; /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } if(*ppListHead != NULL) { byFlag = 1; while(byFlag) { byFlag = 0; pReqTmp1 = *ppListHead; pReqTmp2 = pReqTmp1->pNext; pReqFront = pReqTmp1; while(pReqTmp2 != NULL) { if(LIST_ROTATE == fnCompare((void*)pReqTmp1, (void*)pReqTmp2, pVoid)) { /* change the order */ byChanged = 1; if(pReqTmp1 == *ppListHead) { *ppListHead = pReqTmp2; } else { pReqFront->pNext = pReqTmp2; } pReqTmp1->pNext = pReqTmp2->pNext; pReqTmp2->pNext = pReqTmp1; byFlag = 1; pReqTmp1 = pReqTmp2; pReqTmp2 = pReqTmp1->pNext; } /* if(-1 == fnComppare(pReqTmp1, pReqTmp2, pExtInfo)) */ pReqFront = pReqTmp1; pReqTmp1 = pReqTmp2; pReqTmp2 = pReqTmp1->pNext; } /* while(pReqTmp2) */ } /* while(byFlag) */ } /* if(*ppListHead) */ /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } if(!byChanged) { /* * no rotation occurred in this queue. * the client waiting the something happen */ return(LIST_NOT_CHANGE); } return(LIST_CHANGED); } /* *********************************************************************** Function : P2P_SYS_ListEnum() Description : リスト項目の検証 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List*: リストの先頭ポインタ : INT8 (*)(ST_P2P_List*, void*):検証関数 : void*: 検証関数の第2引数へのポインタ Output : INT8: RET_NOERR:正常終了、RET_INVALID_ARGS:パラメータ異常 その他:その他の異常 Date : 2004/06/21 新規作成 リストのすべての項目について検証関数が呼び出される。 *********************************************************************** */ INT8 P2P_SYS_ListEnum( LOCK_TYPE *pLock, ST_P2P_SYS_List *pListHead, INT8 (*fn)(ST_P2P_SYS_List*, void*), void *pVoid) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListEnum]" { INT8 Rval = RET_UNKNOWN_ERR; ST_P2P_SYS_List *pList; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); if(!fn) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s parameter illegal", FUNC_NAME)); return(RET_INVALID_ARGS); } /* lock */ if(pLock) { if(RET_NOERR != P2P_SYS_Lock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); return(RET_UNKNOWN_ERR); } } pList = pListHead; while(pList) { switch(fn(pList, pVoid)) { case LIST_LOOP_END: pList = NULL; break; default: pList = pList->pNext; break; } } Rval = RET_NOERR; /* unlock */ if(pLock) { if(RET_NOERR != P2P_SYS_Unlock(pLock)) { P2P_SYS_PRINTF((LOG_ERR, &gsSysDebugLog, "%s lock error", FUNC_NAME)); /* it won't happen */ } } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(%d)", FUNC_NAME,Rval)); return(Rval); } static INT8 P2P_SYS_ListGetCounter( ST_P2P_SYS_List *pList, void *pVoid) { UINT16 *pwCount; if(pList && pVoid) { pwCount = (UINT16*)pVoid; (*pwCount)++; return(LIST_LOOP_CONTINUE); } return(LIST_LOOP_END); } /* *********************************************************************** Function : P2P_SYS_ListGetCount() Description : リストの項目数の取得 Input : LOCK_TYPE*: 排他制御定数へのポインタ : ST_P2P_SYS_List*: リストの先頭ポインタ : UINT16*: リストの項目数を格納する領域 Output : INT8: RET_NOERR:正常終了 RET_INVALID_ARGS:パラメータ異常 Date : 2004/06/21 新規作成 *********************************************************************** */ INT8 P2P_SYS_ListGetCount( LOCK_TYPE *pLock, ST_P2P_SYS_List *pListHead, UINT16 *pwCount) #undef FUNC_NAME #define FUNC_NAME "[P2P_SYS_ListGetCount]" { INT8 Rval; UINT16 wCount = 0; P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s start", FUNC_NAME)); Rval = P2P_SYS_ListEnum(pLock, pListHead, P2P_SYS_ListGetCounter, (void*)&wCount); if(pwCount) { *pwCount = wCount; } P2P_SYS_PRINTF((LOG_DEBUG, &gsSysDebugLog, "%s end(%d,count=%d)", FUNC_NAME, Rval, wCount)); return(Rval); }
C
/*************************************************************************** * MICA * File: RGB.h * Workspace: micaOs * Project Name: libMica * Version: v1.0 * Author: Craig Cheney * * Brief: * Header for controlling RGB LED * * Authors: * Craig Cheney * * Change Log: * 2018.02.28 CC - Document created * 2020.06.15 CC - Updated to generic ********************************************************************************/ /* Header Guard */ #ifndef RGB_H #define RGB_H /*************************************** * Included files ***************************************/ #include "micaCommon.h" /*************************************** * Macro Definitions ***************************************/ #define RGB_ACTIVE_HIGH (1) #define RGB_ACTIVE_LOW (0) #define RGB_R_MASK (1u << 0) #define RGB_G_MASK (1u << 1) #define RGB_B_MASK (1u << 2) #define RGB_ERROR_NONE (0) #define RGB_ERROR_INIT (1u << 0) /* Struct has not been initialized */ #define RGB_ERROR_PINWRITE (1u << 1) /* Function pointer is invalid */ #define RGB_ERROR_LOCKED (1u << 2) /* Structure was locked */ /*************************************** * Enumerated types ***************************************/ /* Color Types */ typedef enum { RGB_None = 0x00, RGB_Red = RGB_R_MASK, RGB_Green = RGB_G_MASK, RGB_Blue = RGB_B_MASK, RGB_Yellow = RGB_R_MASK + RGB_G_MASK, /* Red + Green */ RGB_Magenta = RGB_R_MASK + RGB_B_MASK, /* Red + Blue */ RGB_Cyan = RGB_G_MASK + RGB_G_MASK, /* Green + Blue */ RGB_White = RGB_R_MASK + RGB_G_MASK + RGB_B_MASK /* All On */ } RGB_Colors_T; /* LED state */ typedef enum { RGB_OFF = 0x00, RGB_ON = 0x01 } RGB_LED_T; /*************************************** * Structures ***************************************/ typedef struct { void (*fn_pin_R_Write) (uint8_t pinVal); /* Generic function to write Red LED pin state */ void (*fn_pin_G_Write) (uint8_t pinVal); /* Generic function to write Green LED pin state */ void (*fn_pin_B_Write) (uint8_t pinVal); /* Generic function to write Blue LED pin state */ bool _Red; /* State of R LED */ bool _Green; /* State of G LED */ bool _Blue; /* State of B LED */ bool _activeLow; /* If this is set to true, values are inverted before being written to the pins */ bool _init; /* initialization variable */ } RGB_S; /* Default struct to initialize - guarantees _init is 0 */ extern const RGB_S RGB_DEFAULT_S; /*************************************** * Function declarations ***************************************/ uint32_t RGB_Start(RGB_S *const state, bool activePinVal); uint32_t RGB_Write(RGB_S *const state, RGB_Colors_T color); uint32_t RGB_R_Write(RGB_S *const state, RGB_LED_T ledR); uint32_t RGB_G_Write(RGB_S *const state, RGB_LED_T ledG); uint32_t RGB_B_Write(RGB_S *const state, RGB_LED_T ledB); uint32_t RGB_R_Toggle(RGB_S *const state); uint32_t RGB_G_Toggle(RGB_S *const state); uint32_t RGB_B_Toggle(RGB_S *const state); #endif /* RGB_H */ /* [] END OF FILE */
C
#include <stdio.h> #define N 30 int main(void) { char str[N]="abcdefghij"; char *ptr; ptr =str; while (*ptr != '\0') { printf("%c",*ptr); ptr++; } printf("\n"); return 0; }
C
// // 16bpp bitmap functionality // //! \file tonc_bmp16.c //! \author J Vijn //! \date 20060604 - 20070703 // /* === NOTES === * 20070704. Tested except for bmp16_line */ #include "tonc_memmap.h" #include "tonc_core.h" #include "tonc_video.h" // -------------------------------------------------------------------- // FUNCTIONS // -------------------------------------------------------------------- //! Plot a single pixel on a 16-bit buffer /*! \param x X-coord. \param y Y-coord. \param clr Color. \param dstBase Canvas pointer (halfword-aligned plz). \param dstP Canvas pitch in bytes. \note Slow as fuck. Inline plotting functionality if possible. */ void bmp16_plot(int x, int y, u32 clr, void *dstBase, uint dstP) { u16 *dstL= (u16*)(dstBase+y*dstP + x*2); dstL[0]= clr; } //! Draw a horizontal line on an 16bit buffer /*! \param x1 First X-coord. \param y Y-coord. \param x2 Second X-coord. \param clr Color. \param dstBase Canvas pointer (halfword-aligned plz). \param dstP Canvas pitch in bytes. \note Does normalization, but not bounds checks. */ void bmp16_hline(int x1, int y, int x2, u32 clr, void *dstBase, uint dstP) { // --- Normalize --- if(x2<x1) { int tmp= x1; x1= x2; x2= tmp; } u16 *dstL= (u16*)(dstBase+y*dstP + x1*2); // --- Draw --- memset16(dstL, clr, x2-x1+1); } //! Draw a vertical line on an 16bit buffer /*! \param x X-coord. \param y1 First Y-coord. \param y2 Second Y-coord. \param clr Color. \param dstBase Canvas pointer (halfword-aligned plz). \param dstP Canvas pitch in bytes. \note Does normalization, but not bounds checks. */ void bmp16_vline(int x, int y1, int y2, u32 clr, void *dstBase, uint dstP) { // --- Normalize --- if(y2<y1) { int tmp= y1; y1= y2; y2= tmp; } uint height= y2-y1+1; u16 *dstL= (u16*)(dstBase+y1*dstP); dstP /= 2; // --- Draw --- while(height--) { dstL[x]= clr; dstL += dstP; } } //! Draw a line on an 16bit buffer /*! \param x1 First X-coord. \param y1 First Y-coord. \param x2 Second X-coord. \param y2 Second Y-coord. \param clr Color. \param dstBase Canvas pointer (halfword-aligned plz). \param dstP Canvas pitch in bytes. \note Does normalization, but not bounds checks. */ void bmp16_line(int x1, int y1, int x2, int y2, u32 clr, void *dstBase, uint dstP) { int ii, dx, dy, xstep, ystep, dd; u16 *dstL= (u16*)(dstBase + y1*dstP + x1*2); dstP /= 2; // --- Normalization --- if(x1>x2) { xstep= -1; dx= x1-x2; } else { xstep= +1; dx= x2-x1; } if(y1>y2) { ystep= -dstP; dy= y1-y2; } else { ystep= +dstP; dy= y2-y1; } // --- Drawing --- if(dy == 0) // Horizontal { for(ii=0; ii<=dx; ii++) dstL[ii*xstep]= clr; } else if(dx == 0) // Vertical { for(ii=0; ii<=dy; ii++) dstL[ii*ystep]= clr; } else if(dx>=dy) // Diagonal, slope <= 1 { dd= 2*dy - dx; for(ii=0; ii<=dx; ii++) { *dstL= clr; if(dd >= 0) { dd -= 2*dx; dstL += ystep; } dd += 2*dy; dstL += xstep; } } else // Diagonal, slope > 1 { dd= 2*dx - dy; for(ii=0; ii<=dy; ii++) { *dstL= clr; if(dd >= 0) { dd -= 2*dy; dstL += xstep; } dd += 2*dx; dstL += ystep; } } } //! Draw a rectangle in 16bit mode; internal routine. /*! \param left Left side of rectangle; \param top Top side of rectangle. \param right Right side of rectangle. \param bottom Bottom side of rectangle. \param clr Color. \param dstBase Canvas pointer. \param dstP Canvas pitch in bytes \note Does normalization, but not bounds checks. */ void bmp16_rect(int left, int top, int right, int bottom, u32 clr, void *dstBase, uint dstP) { int tmp; // --- Normalization --- if(right<left) { tmp= left; left= right; right= tmp; } if(bottom<top) { tmp= top; top= bottom; bottom= tmp; } uint width= right-left, height= bottom-top; u16 *dstL= (u16*)(dstBase+top*dstP + left*2); dstP /= 2; // --- Draw --- while(height--) { memset16(dstL, clr, width); dstL += dstP; } } //! Draw a rectangle in 16bit mode; internal routine. /*! \param left Left side of rectangle; \param top Top side of rectangle. \param right Right side of rectangle. \param bottom Bottom side of rectangle. \param clr Color. \param dstBase Canvas pointer. \param dstP Canvas pitch in bytes \note Does normalization, but not bounds checks. \note PONDER: RB in- or exclusive? */ void bmp16_frame(int left, int top, int right, int bottom, u32 clr, void *dstBase, uint dstP) { int tmp; // --- Normalization --- if(right<left) { tmp= left; left= right; right= tmp; } if(bottom<top) { tmp= top; top= bottom; bottom= tmp; } uint width= right-left, height= bottom-top; u16 *dstL= (u16*)(dstBase+top*dstP + left*2); dstP /= 2; // --- Top line --- memset16(dstL, clr, width); if(height<2) return; dstL += dstP; height -= 2; // --- Left/right lines --- while(height--) { dstL[0]= clr; dstL[width-1]= clr; dstL += dstP; } // --- Bottom line --- memset16(dstL, clr, width); } // EOF
C
// exercise 1-15: rewrite the temperature conversion program of sectio 1.2 to use a function for conversion #include <stdio.h> // rewrite temp conversion program to use functions double celsiusToFahrenheit(double celsius) { return (9.0 / 5.0) * celsius + 32; } double fahrenheitToCelsius(double fahrenheit) { return (5.0 / 9.0) * (fahrenheit - 32); } main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; celsius = lower; printf(" C F \n"); printf("***********\n"); while (celsius <= upper) { fahr = celsiusToFahrenheit(celsius); printf("%3.0f %6.1f\n", celsius, fahr); celsius = celsius + step; } }
C
#include <stdio.h> #include <stdlib.h> /* First Missing Positive */ #define DEBUG 1 void swap(int* i,int* j){ int t = *i; *i = *j; *j = t; } void dump(int* a, int N) { int i = 0; for(;i<N;i++) printf("%d ",a[i]); printf("\n"); } int firstMissingPositive(int* arr, int size) { int i,j,k; // 1. Move all negative numbers to right i = 0; j = size-1; while(i<=j){ while(i<=j && arr[i] >= 0) i++; while(i<=j && arr[j] < 0) j--; if(i<j) swap(arr+i,arr+j); } // All negative or 0, $i never moved, $j is at front if(i == 0 && j == -1) return 1; if(DEBUG){ printf("First: "); dump(arr,size); printf("i: %d, j: %d\n",i,j); } // 2. Assign arr[k-1] to negative if visited for(i = 0;i<=j;i++){ k = abs(arr[i]); if(k <= size && k > 0) // ignore k == 0 { if(arr[k-1] > 0) arr[k-1] = -arr[k-1]; else if(arr[k-1] == 0) arr[k-1] = -(size+1); } if(DEBUG){ printf("k : %d\n",k); dump(arr,size); } } // 3. Find first non-negative for(i = 0;i<=j;i++) if(arr[i]>=0) return i+1; return j+2; } /* Tester */ int main() { //int arr[] = {0,5,-2,3,7,1,2,-15}; //int arr[] = {0,-10,1,-5,0,2,3,4}; //int arr[] = {1,2,0}; // 3 //int arr[] = {1}; // 2 //int arr[] = {1,2,3}; // 4 //int arr[] = {0}; // 1 //int arr[] = {2,2}; // 1 //int arr[] = {-10,-3,-100,-1000,-239,1}; int arr[] = {1,0,3,3,0,2}; int arr_size = sizeof(arr)/sizeof(arr[0]); printf("%d\n", firstMissingPositive(arr, arr_size)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> static int do_cat(int fd); static void die(const char *s); int main(int argc, char *argv[]) { int i; if(argc < 2) { if (do_cat(STDIN_FILENO) < 0) { exit(1); } } else { for (i = 1; i < argc; i++) { int fd; fd = open(argv[1], O_RDONLY); if (do_cat(fd) < 0) { die(argv[1]); } } } exit(0); } #define BUFFER_SIZE 2048 static int do_cat(int fd) { unsigned char buf[BUFFER_SIZE]; int n; if (fd < 0) return fd; do { n = read(fd, buf, sizeof buf); if (n < 0) return -1; if (write(STDOUT_FILENO, buf, n) < 0) return -1; } while(0 == n); if (close(fd) < 0) return -1; return 1; } static void die(const char *s) { perror(s); exit(1); }
C
#include<stdio.h> #include<stdlib.h> #include<pthread.h> int x; void *increment() { int i; for(i=0;i<10000;i++) { x++; } } void *decrement() { int i; for(i=0;i<10000;i++) { x--; } } int main() { int pthread_equal(pthread_t tid1, pthread_t tid2); pthread_t tid1, tid2; pthread_create(&tid1, NULL, increment,NULL); pthread_create(&tid2, NULL, decrement,NULL); printf("The value of x is %d\n",x); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "vehcule.c" #include "game.c" int main(int argc, char *argv[]) { int c; printf("choix de configuration: 1-configuration ,2-configuration\n"); scanf("%d",&c); char* file_name; switch (c) { case 1: file_name="config2.txt";break; case 2: file_name="config3.txt";break; default: break; } game g = init_game(file_name); affiche(g); solution sol; int k,l; int M2[6][6]; for(k=0;k<6;k++){ for(l=0;l<6;l++) M2[k][l]=g.M[k][l]; } vehcule T2[8]; for(k=0;k<8;k++){ T2[k]=g.T[k]; } sol = jouer(M2,T2,0); printf("probleme est resolu ? %d\n",sol.resolu); if(sol.resolu==1){ printf("voici la solution:\n"); int i; for(i=0;i<sol.taille_pile;i++){ printf("(%d,%d,%c)",sol.pile[i].v,sol.pile[i].pas,sol.pile[i].d); } printf("\n"); } else printf("pas de solution avec au plus 9 mouvement"); system("pause"); }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "main.h" int main(int argc, char *argv[]) { //Compilador /* Função que recebe arquivo */ if(argc == 1) { //Execução sem enviar arquivo txt printf("[ERRO] Arquivo a ser lido não enviado\n"); return 0; } /* Função que chama o Analisador Léxico */ analisador_lexico(argv[1]); } int analisador_lexico (char *arquivo){ /* INICIALIZAÇÃO DE VARÍAVEIS USADAS NO ANALISADOR */ char cadeia[29]; char buffer; int automato = 0; int caracter_valido = 1; //essas sao variaveis de controle pra saber qndo tem quebra de linha qndo o nmero eh racional etc int controle_cadeia = 0; int controle_arquivo = 0; int controle_racional = 0; int controle_quebra_linha = 0; int acerto = 1; for(int a=0; a<29; a++){ // zero a cadeia igualando ela a (null) da tabela ASCII cadeia[a] = 0; } FILE *arquivo_entrada = fopen(arquivo, "r"); FILE *arquivo_saida = fopen("saida.txt", "w"); fprintf(arquivo_saida,"Analise lexica: \n"); if (arquivo_entrada == NULL) { printf("[ERRO] Arquivo não encontrado\n"); return 0; } printf("Início da análise léxica do arquivo \n\n"); /* INÍCIO DA LEITURA DO ARQUIVO */ while(!feof(arquivo_entrada)) { if(controle_cadeia == 0) { /* ANÁLISE PARA INÍCIO DE CADEIA */ /* A análise de início de cadeia checa o caracter e seleciona qual o automato que será utilizado e, em seguida, parte cada a Análise da cadeia, tendo o conhecimento de qual automato será utilizado */ automato = inicio_cadeia(cadeia, arquivo_entrada, &controle_arquivo); // a varialvel "automato" sai dessa func com o automato q eu to no momento controle_cadeia++; } else { /*ANÁLISE DO RESTO DA CADEIA */ fread(&buffer,1,1,arquivo_entrada);//buffer recebe o prox caracter cadeia[controle_cadeia] = buffer; controle_cadeia++; caracter_valido = check_valido_geral(buffer, automato, &controle_racional); if (condicao_final(buffer,automato)){ acerto = 1; if(automato != 3) { cadeia[controle_cadeia - 1] = '\0'; } printf("condicao final atingida -- cadeia reconhecida %s \n", cadeia); devolve_cadeia(cadeia, automato, arquivo_saida, acerto, controle_racional); controle_racional = 0; controle_arquivo = controle_arquivo + controle_cadeia; if(automato != 3) { controle_arquivo = controle_arquivo - 1; } controle_cadeia = 0; } else if (!(caracter_valido) ) { cadeia[controle_cadeia - 1] = '\0'; printf("caracter invalido detectado -- cadeia reconhecida %s \n", cadeia); acerto = 0; devolve_cadeia(cadeia, automato, arquivo_saida, acerto, controle_racional); controle_arquivo = controle_arquivo + controle_cadeia; controle_arquivo = controle_arquivo - 1; controle_cadeia = 0; controle_racional = 0; } } } cadeia[controle_cadeia-1] = '\0'; printf("fim de arquivo atingido -- cadeia reconhecida %s \n", cadeia); //REALIZAR CHECAGEM DA CADEIA FINAL devolve_cadeia(cadeia, automato, arquivo_saida, acerto, controle_racional); fclose(arquivo_entrada); fclose(arquivo_saida); return 0; } int seleciona_automato(char caract){ //analisa qual automato será utilizado a partir do caracter reconhecido. if (confere_numero (caract)){ //Automato de números reais e inteiros printf("Automato de numeros selecionado \n"); return 1; } if(confere_letra(caract)){ //Autômato para identificadores e palavras reservadas printf("Automato de identificadores ou palavras reservadas selecionado \n"); return 2; } if (caract == 123){ //Autômato para comentários printf("Automato de comentários selecionado \n"); return 3; } if (confere_reservado(caract) || !(confere_branco(caract))){ //Autômato para símbolos reservados printf("Automato de simbolos reservados selecionado \n"); return 4; } return 0; } int confere_numero (char caract){ //Confere se o caractere é numero, checando seu valor na tabela ASCII if (caract >= 48 && caract <= 57){ return 1; } return 0; } int confere_letra (char caract) { //Confere se caracter é letra minúscula ou maiúscula if ((caract >= 65 && caract <= 90) || (caract >= 97 && caract <= 122)){ return 1; } return 0; } int confere_reservado (char caract) { //Confere se caracter está dentro da tabela de símbolos reservados; char simbolos_reservados [14] = {'=', '<', '>', '+', '-', '*', '/', ':', ';', ',', '.', '(', ')', '}'}; for (int i = 0; i < 14; i++) { if(caract == simbolos_reservados[i]) return 1; } return 0; } int confere_branco (char caract) { //Confere se caracter checado é espaço ou quebra de linha; if (caract == 32 || caract == 10){ return 1; } return 0; } int check_valido_geral (char buffer, int automato, int* racional) { if (automato == 1){ //Automato de numeros /* Checa se é número ou, caso seja racional se existe apenas um único . na cadeia */ if(confere_numero(buffer)){ return 1; } else if( (buffer == '.')) { *racional = *racional + 1; if(*racional >= 2) return 0; return 1; } return 0; } if (automato == 2){ //Automato de identificadores reservadas /* Para palavras e identificados reservados qualquer caracter que não seja letra retorna invalido para esse caso */ if(confere_letra(buffer) || confere_numero(buffer)) return 1; return 0; } if (automato == 3){ //Automato para comentários /* Checa se eh quebra de linha ou final de arquivo*/ if(buffer == 10 || buffer == 0) return 0; return 1; } if(automato == 4) { if (confere_reservado(buffer) || !(confere_branco(buffer))) return 1; } return 0; } int inicio_cadeia (char cadeia[], FILE* arquivo, int* controle_arquivo){ //Limpa a cadeia for(int a=0; a<29; a++){ // zero a cadeia igualando ela a (null) da tabela ASCII cadeia[a] = 0; } //Inicia cadeia e seleciona o automato que será utilizado fseek(arquivo, *controle_arquivo, SEEK_SET); fread(&cadeia[0], 1, 1, arquivo); while (confere_branco(cadeia[0]) && !feof(arquivo)) { fread(&cadeia[0], 1, 1, arquivo); *controle_arquivo = *controle_arquivo + 1;; } printf("Analisando caracter %c \n", cadeia[0]); return seleciona_automato(cadeia[0]); } int devolve_cadeia(char cadeia [], int automato, FILE* saida, int acerto,int racional){ if (automato == 1){ if(acerto && !racional){ fprintf(saida, "%s, num_int \n", cadeia); return 1; } else if (acerto && racional) { fprintf(saida, "%s, num_real \n", cadeia); return 1; } else if (!acerto) { fprintf(saida, "%s, num_invalido \n", cadeia); return 1; } } if (automato == 2) { if(strcmp(cadeia, "program")==0){ fprintf( saida, "%s, comando_reservado_program\n", cadeia); return 1; }; if(strcmp(cadeia, "begin")==0){ fprintf( saida, "%s, comando_reservado_begin\n", cadeia); return 1; }; if(strcmp(cadeia, "end")==0){ fprintf(saida, "%s, comando_reservado_end\n", cadeia); return 1; }; if(strcmp(cadeia, "const")==0){ fprintf(saida, "%s, comando_reservado_const\n", cadeia); return 1; }; if(strcmp(cadeia, "var")==0){ fprintf(saida, "%s, comando_reservado_var\n", cadeia); return 1; }; if(strcmp(cadeia, "real")==0){ fprintf(saida, "%s, comando_reservado_real\n", cadeia); return 1; }; if(strcmp(cadeia, "integer")==0){ fprintf(saida, "%s, comando_reservado_integer\n", cadeia); return 1; }; if(strcmp(cadeia, "procedure")==0){ fprintf(saida, "%s, comando_reservado_procedure\n", cadeia); return 1; }; if(strcmp(cadeia, "else")==0){ fprintf(saida, "%s, comando_reservado_else\n",cadeia); return 1; }; if(strcmp(cadeia, "read")==0){ fprintf(saida, "%s, comando_reservado_read\n", cadeia); return 1; }; if(strcmp(cadeia, "write")==0){ fprintf(saida, "%s, comando_reservado_write\n", cadeia); return 1; }; if(strcmp(cadeia, "while")==0){ fprintf(saida, "%s, comando_reservado_while\n", cadeia); return 1; }; if(strcmp(cadeia, "do")==0){ fprintf(saida, "%s, comando_reservado_do\n", cadeia); return 1; }; if(strcmp(cadeia, "if")==0){ fprintf(saida, "%s, comando_reservado_if\n", cadeia); return 1; }; if(strcmp(cadeia, "for")==0){ fprintf(saida, "%s, comando_reservado_for\n", cadeia); return 1; }; fprintf(saida, "%s, identificador\n", cadeia); } if(automato == 3) { if (acerto) { fprintf(saida, "%s, comentario \n", cadeia); return 1; } else { fprintf(saida, "%s, comentario_nao_fechado \n", cadeia); return 1; } } if (automato == 4) { if(acerto && strlen(cadeia)<3){ if(strncmp(cadeia, "=",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_igual\n", cadeia); return 1; }; if(strncmp(cadeia, "<", 1)==0 ){ if(strcmp(cadeia, "<>" )==0 ){ fprintf(saida, "%s, comando_reservado_diferente\n", cadeia); return 1; } if(strcmp(cadeia, "<=")==0){ fprintf(saida, "%s, comando_reservado_menor_igual\n", cadeia); return 1; } if( cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_menor\n", cadeia); return 1; } }; if(strncmp(cadeia, ">",1)==0){ if(strncmp(cadeia, ">=",2)==0 ){ fprintf(saida, "%s, comando_reservado_maior_igual\n", cadeia); return 1; } if( cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_maior\n", cadeia); return 1; } }; if(strncmp(cadeia, ":",1)==0){ if(strncmp(cadeia, ":=",2)==0){ fprintf(saida, "%s, comando_reservado_atribuicao\n", cadeia); return 0; } if( cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_dois_pontos\n", cadeia); return 1; } }; if(strcmp(cadeia, "+")==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_mais\n", cadeia); return 1; }; if(strncmp(cadeia, "-",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_menos\n", cadeia); return 1; }; if(strncmp(cadeia, "*",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_asterisco\n", cadeia); return 1; }; if(strncmp(cadeia, "/",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_barra\n", cadeia); return 1; }; if(strncmp(cadeia, ";",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_ponto_virgula\n", cadeia); return 1; }; if(strncmp(cadeia, ".",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_ponto\n", cadeia); return 1; }; if(strncmp(cadeia, ",",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_virgula\n", cadeia); return 1; }; if(strncmp(cadeia, "(",1)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_abre_parenteses\n", cadeia); return 1; }; if(strncmp(cadeia, ")",3)==0 && cadeia[1] == '\0'){ fprintf(saida, "%s, comando_reservado_fecha_parenteses\n", cadeia); return 1; }; fprintf(saida, "%s, simbolo_nao_reconhecido\n", cadeia); return 1; } else { fprintf(saida, "%s, simbolo_nao_reconhecido\n", cadeia); return 1; } } } int condicao_final(char buffer, int automato) { if (automato == 1){ if(confere_branco(buffer)) return 1; if(confere_reservado(buffer) && buffer != '.') return 1; return 0; } if(automato == 2) { if(confere_branco(buffer)) return 1; if(confere_reservado(buffer)) return 1; return 0; } if (automato == 3){ if(buffer == '}') return 1; return 0; } if(automato==4){ if(!confere_reservado(buffer)) return 1; } return 0; }
C
#include <stdio.h> #include <GL/glut.h> #include "math.h" void init(void); void sinandcos(void); int main(int argc, char** argv) { glutInit(&argc, argv); // Initialize GLUT. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set display mode. glutInitWindowPosition(200, 100); // Set top-left display-window position. glutInitWindowSize(800, 400); // Set display-window width and height. glutCreateWindow("Sine and Cosine Visualization"); // Create display window with given title. init(); // Execute initialization procedure. glutDisplayFunc(sinandcos); // Send graphics to display window. glutMainLoop(); // Display everything and wait. return 0; } void init(void) { glClearColor(1.0, 1.0, 1.0, 0.0); // Set display-window color to white. glMatrixMode(GL_PROJECTION); // Set project parameters. gluOrtho2D(-2*M_PI-1, 2*M_PI+1, -1.25, 1.25); // Set vertical and horizontal clipping planes. } void sinandcos(void) { glClear(GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f(1.0, 0.0, 0.0); //SET X AND Y AXIS AND Y HASH MARKS glBegin(GL_LINES); glVertex2d(-2*(M_PI), 0); glVertex2d(2*(M_PI), 0); glVertex2d(0, -1); glVertex2d(0, 1); glVertex2d(-.1, 1); //Y HASHES glVertex2d(.1, 1); glVertex2d(-.1, -1); glVertex2d(.1, -1); glEnd(); for (float i = -2*M_PI; i <= 7; i += M_PI/2) //X HASHES { glBegin(GL_LINES); glVertex2d(i, .04); glVertex2d(i, -.04); glEnd(); } for (float i = -2*M_PI; i < 2*M_PI; i += .00001) { glColor3f(0.0, 0.0, 1.0); //PLOT SINE (Blue) glBegin(GL_POINTS); glVertex2d(i, sin(i)); glEnd(); glColor3f(0.0, 1.0, 0.0); //PLOT COSINE (Green) glBegin(GL_POINTS); glVertex2d(i, cos(i)); glEnd(); } glFlush(); // Process all OpenGL routines ASAP. }
C
# include<stdio.h> # include<math.h> int main() { float x1,y1,x2,y2,x3,y3; scanf("%f %f",&x1,&y1); scanf("%f %f",&x2,&y2); scanf("%f %f",&x3,&y3); printf("\n"); float a = (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1); float b = (x3-x1)*(x3-x1)+(y3-y1)*(y3-y1); float c = (x3-x2)*(x3-x2)+(y3-y2)*(y3-y2); if(a==b+c||b==a+c||c==a+b) printf("1\n"); else printf("0\n"); return 0; }
C
/*1652270 2 ˴*/ #include <stdio.h> #include <stdlib.h> //malloc/realloc #include <io.h> //exit /* P.10 Ԥ峣 */ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define LOVERFLOW -2 typedef int Status; /* P.28 ʽ */ typedef int ElemType; //ɸҪ޸Ԫص typedef struct LNode { ElemType data; // struct LNode *next; //ֱӺ̵ָ } LNode, *LinkList; /* P.19-20ijͶתΪʵʵC */ Status InitList(LinkList *L); Status DestroyList(LinkList *L); Status ClearList(LinkList *L); Status ListEmpty(LinkList L); int ListLength(LinkList L); Status GetElem(LinkList L, int i, ElemType *e); int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType e1, ElemType e2)); Status PriorElem(LinkList L, ElemType cur_e, ElemType *pre_e); Status NextElem(LinkList L, ElemType cur_e, ElemType *next_e); Status ListInsert(LinkList *L, int i, ElemType e); Status ListDelete(LinkList *L, int i, ElemType *e); Status ListTraverse(LinkList L, Status(*visit)(ElemType e)); /* ʼԱ */ Status InitList(LinkList *L) { /* ͷռ䣬ֵͷָ */ *L = (LNode *)malloc(sizeof(LNode)); if (*L == NULL) exit(LOVERFLOW); (*L)->next = NULL; return OK; } /* ɾԱ */ Status DestroyList(LinkList *L) { LinkList q, p = *L; //ָԪ /* (ͷ)ͷ */ while (p) { //Ϊգѭִ q = p->next; //ץסһ free(p); p = q; } *L = NULL; //ͷָNULL return OK; } /* Աͷ㣩 */ Status ClearList(LinkList *L) { LinkList q, p = (*L)->next; /* Ԫ㿪ʼͷ */ while (p) { q = p->next; //ץסһ free(p); p = q; } (*L)->next = NULL; //ͷnextNULL return OK; } /* жǷΪձ */ Status ListEmpty(LinkList L) { /* жͷnext򼴿 */ if (L->next == NULL) return TRUE; else return FALSE; } /* ij */ int ListLength(LinkList L) { #if 1 LinkList p = L->next; //ָԪ int len = 0; /* ѭм */ while (p) { p = p->next; len++; } return len; #else int len = 0; LinkList p = L; while ((p = p->next) != NULL) len++; return len; #endif } /* ȡԪ */ Status GetElem(LinkList L, int i, ElemType *e) { LinkList p = L->next; //ָԪ int pos = 1; //ʼλΪ1 /* ΪNULL δiԪ */ while (p != NULL && pos<i) { p = p->next; pos++; } if (!p || pos>i) return ERROR; *e = p->data; return OK; } /* ҷָԪ */ int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType e1, ElemType e2)) { LinkList p = L->next; //Ԫ int pos = 1; //ʼλ /* ѭ */ while (p && (*compare)(e, p->data) == FALSE) { p = p->next; pos++; } return p ? pos : 0; } /* ҷָԪصǰԪ */ Status PriorElem(LinkList L, ElemType cur_e, ElemType *pre_e) { #if 1 LinkList p = L->next; //ָԪ if (p == NULL) //ձֱӷ return ERROR; /* ӵ2㿪ʼѭ(Ƚȣ֤ǰ) */ while (p->next && p->next->data != cur_e) p = p->next; if (p->next == NULL) //δҵ return ERROR; *pre_e = p->data; return OK; #else LinkList p = L; //ָͷ /* ѭȽֵǷ */ while (p->next && p->next->data != cur_e) p = p->next; if (p->next == NULL || p == L) //δҵԪձ return ERROR; *pre_e = p->data; return OK; #endif } /* ҷָԪصĺԪ */ Status NextElem(LinkList L, ElemType cur_e, ElemType *next_e) { LinkList p = L->next; //Ԫ if (p == NULL) //ձֱӷ return ERROR; /* к̽ҵǰֵʱ */ while (p->next && p->data != cur_e) p = p->next; if (p->next == NULL) return ERROR; *next_e = p->next->data; return OK; } /* ָλǰһԪ */ Status ListInsert(LinkList *L, int i, ElemType e) { LinkList s, p = *L; //pָͷ int pos = 0; /* Ѱҵi-1 */ while (p && pos<i - 1) { p = p->next; pos++; } if (p == NULL || pos>i - 1) //iֵǷ򷵻 return ERROR; //ִе˱ʾҵָλãpָi-1 s = (LinkList)malloc(sizeof(LNode)); if (s == NULL) return LOVERFLOW; s->data = e; //½ֵ s->next = p->next; //½nextǵi p->next = s; //i-1next½ return OK; } /* ɾָλõԪأɾԪصֵeз */ Status ListDelete(LinkList *L, int i, ElemType *e) { LinkList q, p = *L; //pָͷ int pos = 0; /* Ѱҵi㣨p->nextǵi㣩 */ while (p->next && pos<i - 1) { p = p->next; pos++; } if (p->next == NULL || pos>i - 1) //iֵǷ򷵻 return ERROR; //ִе˱ʾҵ˵i㣬ʱpָi-1 q = p->next; //qָi p->next = q->next; //i-1nextָi+1 *e = q->data; //ȡiֵ free(q); //ͷŵi return OK; } /* Ա */ Status ListTraverse(LinkList L, Status(*visit)(ElemType e)) { extern int line_count; //mainжĴӡм㷨޹أ LinkList p = L->next; line_count = 0; //ָʼֵ㷨޹أ while (p && (*visit)(p->data) == TRUE) p = p->next; if (p) return ERROR; printf("\n");//ӡһУֻΪ˺ÿ㷨޹ return OK; } #define INSERT_NUM 115 //ʼеԪ #define MAX_NUM_PER_LINE 10 //ÿԪظ int line_count = 0; //ӡʱļ void difference(LinkList *La, LinkList *Lb) {//ɾLbݣLa޸ΪԭLaLbĶԳƲ LinkList Alast = *La, searchAPrev, searchBPrev; //LinkList newNode; LinkList tmpA, tmpB; while (Alast->next) Alast = Alast->next; searchBPrev = (*Lb); while (searchBPrev->next) { searchAPrev = (*La); while (searchAPrev != Alast && searchAPrev->next->data != searchBPrev->next->data) { searchAPrev = searchAPrev->next; } if (searchAPrev == Alast) { //newNode = (LinkList)malloc(sizeof(LNode)); //if (!newNode) //{ // exit(LOVERFLOW); //} tmpB = searchBPrev->next; searchBPrev->next = tmpB->next; tmpA = Alast->next; tmpB->next = tmpA; Alast->next = tmpB; } else { tmpA = searchAPrev->next; searchAPrev->next = searchAPrev->next->next; if (tmpA == Alast) { Alast = searchAPrev; } free(tmpA); tmpB = searchBPrev->next; searchBPrev->next = tmpB->next; free(tmpB); } } } Status MyVisit(ElemType e) { printf("%3d->", e); /* ÿMAX_NUM_PER_LINEӡһ */ if ((++line_count) % MAX_NUM_PER_LINE == 0) printf("\n"); return OK; } int main() { const int data_LA[] = { 1,2,3,5,7,9 }; const int data_LB[] = { 1, 3,8,9,6 }; LinkList LA, LB; InitList(&LA); InitList(&LB); if (1) { for (int i = 0; i < sizeof(data_LA) / sizeof(data_LA[0]); i++) { ListInsert(&LA, 1, data_LA[sizeof(data_LA) / sizeof(data_LA[0]) - i - 1]); } } if (1) { for (int i = 0; i < sizeof(data_LB) / sizeof(data_LB[0]); i++) { ListInsert(&LB, 1, data_LB[sizeof(data_LB) / sizeof(data_LB[0]) - i - 1]); } } printf("LA ݣ\n"); ListTraverse(LA, MyVisit); printf("\nLB ݣ\n"); ListTraverse(LB, MyVisit); printf("\n\nԳƲLA ݣ\n"); difference(&LA, &LB); ListTraverse(LA, MyVisit); printf("\n\nԳƲLB ݣ\n"); ListTraverse(LB, MyVisit); printf("\n"); return 0; }
C
/* * pseultra/tools/bootcsum/src/bootcsum.c * PIFrom ipl2 checksum function decomp * * (C) pseudophpt 2018 */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #define MAGIC 0x95DACFDC uint64_t calculate_checksum (uint32_t *bcode); static inline uint64_t checksum_helper (uint64_t op1, uint64_t op2, uint64_t op3); int main (int argc, char *argv[]) { // If arguments not adequate if (argc < 2) { printf("Usage: bootcsum <rom file> [<expected checksum>]\n"); return -1; } FILE* rom_file; uint32_t rom_buffer[0x1000 / sizeof(uint32_t)]; rom_file = fopen(argv[1], "rb"); fread(rom_buffer, sizeof(uint32_t), 0x1000 / sizeof(uint32_t), rom_file); fclose(rom_file); // LE to BE for (int i = 0; i < 0x1000 / sizeof(uint32_t); i++) { uint32_t le = rom_buffer[i]; uint32_t be = ((le & 0xff) << 24) | ((le & 0xff00) << 8) | ((le & 0xff0000) >> 8) | ((le & 0xff000000) >> 24); rom_buffer[i] = be; } // Verification or calculation if (argc == 2) { // Calculation uint64_t checksum = calculate_checksum(&rom_buffer[0x10]); printf("0x%llx\n", checksum); return 0; } if (argc == 3) { // Verification uint64_t expected_checksum = strtoll(argv[2], NULL, 0); uint64_t checksum = calculate_checksum(&rom_buffer[0x10]); if (checksum == expected_checksum) { printf("Correct\n"); return 0; } else { printf("Incorrect:\n"); printf("Expected 0x%llx, got 0x%llx\n", expected_checksum, checksum); return -1; } } } /* * Helper function commonly called during checksum */ static inline uint64_t checksum_helper (uint64_t op1, uint64_t op2, uint64_t op3) { int high_mult; int low_mult; if (op2 == 0) { op2 = op3; } low_mult = (op1 * op2) & 0x00000000FFFFFFFF; high_mult = ((op1 * op2) & 0xFFFFFFFF00000000) >> 32; if (high_mult - low_mult == 0) { return low_mult; } else return high_mult - low_mult; } /* * Decompiled checksum function */ uint64_t calculate_checksum (uint32_t *bcode) { uint32_t *bcode_inst_ptr = bcode; uint32_t loop_count = 0; uint32_t bcode_inst = *bcode_inst_ptr; uint32_t next_inst; uint32_t prev_inst; uint32_t frame [16]; uint32_t sframe [4]; // Calculate magic number uint32_t magic = MAGIC ^ bcode_inst; // Generate frame. This is done earlier in IPC2 for (int i = 0; i < 16; i ++) { frame[i] = magic; }; // First part of checksum, calculates frame for (;;) { /* Loop start, 11E8 - 11FC */ prev_inst = bcode_inst; bcode_inst = *bcode_inst_ptr; loop_count ++; bcode_inst_ptr ++; next_inst = *(bcode_inst_ptr); /* Main processing */ frame[0] += checksum_helper(0x3EF - loop_count, bcode_inst, loop_count); frame[1] = checksum_helper(frame[1], bcode_inst, loop_count); frame[2] ^= bcode_inst; frame[3] += checksum_helper(bcode_inst + 5, 0x6c078965, loop_count); if (prev_inst < bcode_inst) { frame[9] = checksum_helper(frame[9], bcode_inst, loop_count); } else frame[9] += bcode_inst; frame[4] += ((bcode_inst << (0x20 - (prev_inst & 0x1f))) | (bcode_inst >> (prev_inst & 0x1f))); frame[7] = checksum_helper(frame[7], ((bcode_inst >> (0x20 - (prev_inst & 0x1f))) | (bcode_inst << (prev_inst & 0x1f))), loop_count); if (bcode_inst < frame[6]) { frame[6] = (bcode_inst + loop_count) ^ (frame[3] + frame[6]); } else frame[6] = (frame[4] + bcode_inst) ^ frame[6]; frame[5] += (bcode_inst >> (0x20 - (prev_inst >> 27))) | (bcode_inst << (prev_inst >> 27)); frame[8] = checksum_helper(frame[8], (bcode_inst << (0x20 - (prev_inst >> 27))) | (bcode_inst >> (prev_inst >> 27)), loop_count); if (loop_count == 0x3F0) break; uint32_t tmp1 = checksum_helper(frame[15], (bcode_inst >> (0x20 - (prev_inst >> 27))) | (bcode_inst << (prev_inst >> 27)), loop_count); frame[15] = checksum_helper( tmp1, (next_inst << (bcode_inst >> 27)) | (next_inst >> (0x20 - (bcode_inst >> 27))), loop_count ); uint32_t tmp2 = ((bcode_inst << (0x20 - (prev_inst & 0x1f))) | (bcode_inst >> (prev_inst & 0x1f))); uint32_t tmp3 = checksum_helper(frame[14], tmp2, loop_count); // v0 at 1384 uint32_t tmp4 = checksum_helper(tmp3, (next_inst >> (bcode_inst & 0x1f)) | (next_inst << (0x20 - (bcode_inst & 0x1f))), loop_count); // v0 at 13a4 frame[14] = tmp4; frame[13] += ((bcode_inst >> (bcode_inst & 0x1f)) | (bcode_inst << (0x20 - (bcode_inst & 0x1f)))) + ((next_inst >> (next_inst & 0x1f)) | (next_inst << (0x20 - (next_inst & 0x1f)))); frame[10] = checksum_helper(frame[10] + bcode_inst, next_inst, loop_count); frame[11] = checksum_helper(frame[11] ^ bcode_inst, next_inst, loop_count); frame[12] += (frame[8] ^ bcode_inst); } // Second part, calculates sframe // Every value in sframe is initialized to frame[0] for (int i = 0; i < 4; i ++) { sframe[i] = frame[0]; } uint32_t *frame_word_ptr = &frame[0]; uint32_t frame_word; for (uint32_t frame_number = 0; frame_number != 0x10; frame_number ++) { // Updates frame_word = *frame_word_ptr; // Calculations sframe[0] += ((frame_word << (0x20 - frame_word & 0x1f)) | frame_word >> (frame_word & 0x1f)); if (frame_word < sframe[0]) { sframe[1] += frame_word; } else { sframe[1] = checksum_helper(sframe[1], frame_word, 0); } if (((frame_word & 0x02) >> 1) == (frame_word & 0x01)) { sframe[2] += frame_word; } else { sframe[2] = checksum_helper(sframe[2], frame_word, frame_number); } if (frame_word & 0x01 == 1) { sframe[3] ^= frame_word; } else { sframe[3] = checksum_helper(sframe[3], frame_word, frame_number); } frame_word_ptr ++; } // combine sframe into checksum uint64_t checksum = sframe[2] ^ sframe[3]; checksum |= checksum_helper(sframe[0], sframe[1], 0x10) << 32; checksum &= 0x0000ffffffffffff; return checksum; }
C
//perm_access.c - test access() #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> int main() { int fd; struct stat statbuf;; pid_t pid; uid_t ruid, euid; if (stat("test.txt", &statbuf) == -1) { perror("fail to stat"); exit(1); } if ((ruid = getuid()) == -1) { perror("fail to get ruid"); exit(1); } if ((euid = geteuid()) == -1) { perror("fail to get euid"); exit(1); } printf("real id is : %u, effective id is : %u \n", (unsigned int)ruid, (unsigned int)euid); printf("file owner is : %u\n", statbuf.st_uid); if (access("test.txt", R_OK) == -1) { perror("fail to access"); exit(1); } printf("access successfully!\n"); if ((fd == open("test.txt", O_RDONLY)) == -1) { perror("fail to open"); exit(1); } printf("ready to read\n"); close(fd); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_unsigned_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: trbonnes <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/25 10:24:06 by trbonnes #+# #+# */ /* Updated: 2019/11/14 10:51:55 by trbonnes ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" static unsigned long long int ft_size(unsigned long long int tmp, unsigned long long int size) { while (tmp > 0) { tmp = tmp / 10; size++; } return (size); } static char *ft_zero(void) { char *str; if (!(str = malloc(sizeof(char) * 2))) return (NULL); str[0] = '0'; str[1] = '\0'; return (str); } static char *ft_fullup(unsigned long long int tmp, unsigned long long int size, unsigned long long int n) { char *str; int i; if (n == 0) str = ft_zero(); else { if (!(str = malloc(sizeof(char) * size + 1))) return (NULL); i = size - 1; while (tmp > 0) { str[i--] = ((tmp % 10) + '0'); tmp = tmp / 10; } str[size] = '\0'; } return (str); } char *ft_unsigneditoa(unsigned long long int n) { char *str; unsigned long long int size; unsigned long long int tmp; size = 0; tmp = n; size = ft_size(tmp, size); str = ft_fullup(tmp, size, n); return (str); }
C
#include "userprog/syscall.h" #include <stdio.h> #include <syscall-nr.h> #include "threads/interrupt.h" #include "threads/thread.h" #include <devices/shutdown.h> #include <filesys/filesys.h> #include "userprog/process.h" #include "filesys/file.h" #include "devices/input.h" #include "threads/malloc.h" #include "vm/page.h" #include "userprog/pagedir.h" #include "threads/vaddr.h" static void syscall_handler(struct intr_frame *); struct vm_entry *check_address(void *addr, void *esp); void check_valid_buffer(void *buffer, unsigned size, void *esp, bool to_write); void check_valid_string(const void *str, void *esp); void get_argument(void *esp, int *arg, int count); void halt(void); void exit(int status); tid_t exec(const char *cmd_line); bool create(const char *file, unsigned inital_size); bool remove(const char *file); int wait(tid_t pid); int open(const char *file); int filesize(int fd); int read(int fd, void *buffer, unsigned size); int write(int fd, void *buffer, unsigned size); void seek(int fd, unsigned position); unsigned tell(int fd); void close(int fd); int mmap(int fd, void *addr); void munmap(int mapid); void do_munmap(struct mmap_file *mmap_file); void syscall_init(void) { intr_register_int(0x30, 3, INTR_ON, syscall_handler, "syscall"); //lock 초기화 lock_init(&filesys_lock); } void halt(void) { printf("%s\n", thread_name()); shutdown_power_off(); } void exit(int status) { //프로세스 디스크립터에 exit_status 저장 thread_current()->exit_status = status; printf("%s: exit(%d)\n", thread_name(), status); thread_exit(); } bool create(const char *file, unsigned initial_size) { //파일 생성 lock_acquire(&filesys_lock); bool success = filesys_create(file, initial_size); lock_release(&filesys_lock); return success; } bool remove(const char *file) { //파일 제거 lock_acquire(&filesys_lock); bool success = filesys_remove(file); lock_release(&filesys_lock); return success; } //자식 프로세스를 생성하고 프로그램을 실행시키는 시스템 콜 tid_t exec(const char *cmd_line) { struct thread *child; tid_t pid; //명령어(cmd_line)에 해당하는 프로그램을 수행하는 프로세스 생성 pid = process_execute(cmd_line); //생성된 자식 프로세스의 프로세스 디스크립터 검색 child = get_child_process(pid); //자식 프로세스의 프로그램이 로드될 때 까지 대기 sema_down(&child->load_sema); //프로그램 로드 성공 시 자식 프로세스 pid 반환 if (child->loaded == true) return pid; //프로그램 로드 실패시 -1 리턴 else return -1; } int wait(tid_t pid) { //자식 프로세스가 종료될 때 까지 대기 return process_wait(pid); } int open(const char *file) { lock_acquire(&filesys_lock); //파일 open struct file *f = filesys_open(file); int fd; //해당 파일이 존재하지 않을 시 -1 리턴 if (f == NULL) { lock_release(&filesys_lock); return -1; } //해당 파일 객체에 파일 디스크립터 부여 fd = process_add_file(f); lock_release(&filesys_lock); //파일 디스크립터 리턴 return fd; } int filesize(int fd) { lock_acquire(&filesys_lock); struct file *f = process_get_file(fd); if (!f) { lock_release(&filesys_lock); return -1; } int size = file_length(f); lock_release(&filesys_lock); return size; } int read(int fd, void *buffer, unsigned size) { //파일 디스크립터를 이용하여 파일 객체 검색 int i; //파일 디스크립터가 0인 경우 if (fd == 0) { char *cur_buffer = (char *)buffer; //input_getc 함수 이용하여 키보드 데이터 읽음 for (i = 0; i < size; i++) { cur_buffer[i] = input_getc(); } //버퍼 크기 리턴 return size; } //lock 사용하여 동시 접근 방지 lock_acquire(&filesys_lock); struct file *f = process_get_file(fd); int bytes; if (f == NULL) { //널일 경우 lock 해제 후 리턴 -1 lock_release(&filesys_lock); return -1; } else { //파일 read bytes = file_read(f, buffer, size); //lock 해제 lock_release(&filesys_lock); //읽은 바이트 수 리턴 return bytes; } } int write(int fd, void *buffer, unsigned size) { //파일 디스크립터가 1인 경우 if (fd == 1) { //버퍼에 저장된 값 화면 출력 putbuf((const char *)buffer, size); //버퍼의 크기 리턴 return size; } //lock 사용하여 동시 접근 방지 lock_acquire(&filesys_lock); struct file *f = process_get_file(fd); int bytes; if (f == NULL) { //널일 경우 lock 해제 후 리턴 -1 lock_release(&filesys_lock); return -1; } else { //파일 write bytes = file_write(f, buffer, size); //락 해제 lock_release(&filesys_lock); //파일에 쓴 바이트 수 리턴 return bytes; } } void seek(int fd, unsigned position) { lock_acquire(&filesys_lock); struct file *f = process_get_file(fd); if (f == NULL) { lock_release(&filesys_lock); return; } //해당 열린 파일의 위치를 position만큼 이동 file_seek(f, position); lock_release(&filesys_lock); } unsigned tell(int fd) { lock_acquire(&filesys_lock); struct file *f = process_get_file(fd); if (!f) { lock_release(&filesys_lock); return -1; } off_t offset = file_tell(f); lock_release(&filesys_lock); return offset; } void close(int fd) { //해당 파일 디스크립터에 해당하는 파일을 닫고 //파일 디스크립터 엔트리 초기화 lock_acquire(&filesys_lock); process_close_file(fd); lock_release(&filesys_lock); } static void syscall_handler(struct intr_frame *f) { //system call's argument loading from stack int *h_esp = f->esp; int syscall_num = *h_esp; int arg[5]; // printf("\nsyscall number : %d\n", syscall_num); check_address(h_esp, h_esp); switch (syscall_num) { case SYS_HALT: // 0 halt(); break; case SYS_EXIT: // 1 get_argument(h_esp, arg, 1); exit(arg[0]); f->eax = arg[0]; break; case SYS_EXEC: // 2 get_argument(h_esp, arg, 1); check_valid_string((const void *)arg[0], h_esp); //check f->eax = exec(arg[0]); //return tid_t break; case SYS_WAIT: // 3 get_argument(h_esp, arg, 1); f->eax = wait(arg[0]); //return int break; case SYS_CREATE: // 4 get_argument(h_esp, arg, 2); //get argument check_valid_string((const void *)arg[0], h_esp); //check f->eax = create((const char *)arg[0], (unsigned)arg[1]); //get return break; case SYS_REMOVE: // 5 get_argument(h_esp, arg, 1); check_valid_string((const void *)arg[0], h_esp); //check f->eax = remove((const void *)arg[0]); break; case SYS_OPEN: // 6 get_argument(h_esp, arg, 1); check_valid_string((const void *)arg[0], h_esp); f->eax = open(arg[0]); break; case SYS_FILESIZE: // 7 get_argument(h_esp, arg, 1); f->eax = filesize(arg[0]); break; case SYS_READ: // 8 get_argument(h_esp, arg, 3); check_valid_buffer((void *)arg[1], (unsigned)arg[2], h_esp, true); f->eax = read(arg[0], (const void *)arg[1], (unsigned)arg[2]); break; case SYS_WRITE: // 9 get_argument(h_esp, arg, 3); check_valid_buffer((void *)arg[1], (unsigned)arg[2], h_esp, false); f->eax = write(arg[0], (const void *)arg[1], (unsigned)arg[2]); break; case SYS_SEEK: // 10 get_argument(h_esp, arg, 2); seek(arg[0], (unsigned)arg[1]); break; case SYS_TELL: // 11 get_argument(h_esp, arg, 1); f->eax = tell(arg[0]); break; case SYS_CLOSE: // 12 get_argument(h_esp, arg, 1); close(arg[0]); break; case SYS_MMAP: get_argument(h_esp, arg, 2); f->eax = mmap(arg[0], (void *)arg[1]); break; case SYS_MUNMAP: get_argument(h_esp, arg, 1); munmap(arg[0]); break; default: printf("default\n"); } } void get_argument(void *esp, int *arg, int count) { //esp for stack pointer, count is number of argument int i; int *ptr; for (i = 0; i < count; i++) { //esp 다음 자리에 arg[i] 배정 ptr = (int *)esp + i + 1; //ptr이 커널 영역을 침입하지 않는지 체크 check_address(ptr, esp); arg[i] = *ptr; } } struct vm_entry *check_address(void *addr, void *esp) { //check address is user's address //user address : 0x08048000~0xc0000000 // if (!((void *)0x08048000 < addr && addr < (void *)0xc0000000)) if (addr < (void *)0x08048000 || addr >= (void *)0xc0000000) exit(-1); bool loaded = false; struct vm_entry *vme = find_vme(addr); if(vme) { vme->pinned = true; handle_mm_fault(vme); loaded = vme->is_loaded; } if(!loaded) exit(-1); return vme; } void check_valid_buffer(void *buffer, unsigned size, void *esp, bool to_write) { int i; struct vm_entry *vme; char *l_buffer = (char *)buffer; for (i = 0; i < size; i++) { //주소 유저영역 여부 검사와 vm_entry 획득 vme = check_address((void *)l_buffer, esp); //해당 주소에 대한 vm_entry존재 여부와 vm_entry의 writable멤버가 true인지 검사 if ((vme != NULL) && to_write) if (!vme->writable) exit(-1); l_buffer++; } } void check_valid_string(const void *str, void *esp) { //str에 대한 vm_entry 존재 여부 확인 struct vm_entry *vme = check_address(str, esp); while (*(char *)str != 0) { if (vme == NULL) { exit(-1); } str = (char *)str + 1; vme = check_address(str, esp); } } /* mmap fd: 프로세스의 가상 주소공간에 매핑할 파일 addr: 매핑을 시작할 주소(page 단위 정렬) 성공 시 mapping id를 리턴, 실패 시 에러코드(-1) 리턴 요구페이징에 의해 파일 데이터를 메모리로 로드 */ int mmap(int fd, void *addr) { struct mmap_file *m_file; struct file *f, *rf; off_t ofs = 0; static int map_id = 0; f = process_get_file(fd); if (f == NULL || !is_user_vaddr(addr) || addr <= 0 || (int)addr % PGSIZE != 0) { return -1; // 이상한 인자 } rf = file_reopen(f); if (!rf || file_length(rf) == 0) { return -1; } //mmap구조체 생성 m_file = (struct mmap_file *)malloc(sizeof(struct mmap_file)); if (m_file == NULL) { return -1; } //mmap 구조체 초기화 list_init(&m_file->vme_list); m_file->mapid = ++map_id; m_file->file = rf; uint32_t read_bytes = file_length(rf); while (read_bytes > 0) { size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE; size_t page_zero_bytes = PGSIZE - page_read_bytes; // 이미 존재한다면 에러 if (find_vme(addr)) { return -1; } struct vm_entry *vme = malloc(sizeof(struct vm_entry)); if (!vme) return -1; // vme 초기화; vme->type = VM_FILE; vme->vaddr = addr; vme->writable = true; vme->is_loaded = false; vme->file = rf; vme->offset = ofs; vme->read_bytes = page_read_bytes; vme->zero_bytes = page_zero_bytes; list_push_back(&m_file->vme_list, &vme->mmap_elem); // hash vm에 삽입 insert_vme(&thread_current()->vm, vme); read_bytes -= page_read_bytes; ofs += page_read_bytes; addr += PGSIZE; } list_push_back(&thread_current()->mmap_list, &m_file->elem); return m_file->mapid; } void munmap(int mapping) { struct thread *t = thread_current(); struct list_elem *e = list_begin(&t->mmap_list); struct list_elem *next_elem; //mmap_list에서 해제할 mmap_file 검색 while (e != list_end(&t->mmap_list)) { struct mmap_file *m_file = list_entry(e, struct mmap_file, elem); next_elem = list_next(e); //mmap_list내에서 mapping에 해당하는 mapid를 갖는 모든 vm_entry을 해제 //인자로 넘겨진 mapping값이 CLOSE_ALL인경우 모든 파일매핑을 제거 //매핑 제거 시 do_munmap()함수호출 if (m_file->mapid == mapping || mapping == CLOSE_ALL) { do_munmap(m_file); list_remove(&m_file->elem); free(m_file); if (mapping != CLOSE_ALL) break; } e = next_elem; } } // 매핑 제거 void do_munmap(struct mmap_file *mmap_file) { struct thread *t = thread_current(); struct list_elem *next_elem; struct list_elem *e = list_begin(&mmap_file->vme_list); struct file *f = mmap_file->file; //vme list 순회 while (e != list_end(&mmap_file->vme_list)) { next_elem = list_next(e); struct vm_entry *vme = list_entry(e, struct vm_entry, mmap_elem); //vm_entry가 물리 페이지와 load되어 있다면 if (vme->is_loaded) { //dirty bit 검사 pagedir.c if (pagedir_is_dirty(t->pagedir, vme->vaddr)) { //lock lock_acquire(&filesys_lock); //file write file_write_at(vme->file, vme->vaddr, vme->read_bytes, vme->offset); lock_release(&filesys_lock); } // pagedir_get_page(t->pagedir, vme->vaddr); palloc_free_page(pagedir_get_page(t->pagedir, vme->vaddr)); //page clear pagedir_clear_page(t->pagedir, vme->vaddr); } //mmap_list에서 제거 list_remove(&vme->mmap_elem); delete_vme(&t->vm, vme); free(vme); e = next_elem; } //file close 처리 if(f) { lock_acquire(&filesys_lock); file_close(f); lock_release(&filesys_lock); } }
C
//??? int fun(int n) { if (n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)) return 1; else return 0; } int main() { int n = 0, i = 0; cin >> n; for (i = 1; i <= n; i++) { int year = 0, mon1 = 0, mon2 = 0, sum = 0, j = 0, temp = 0; cin >> year >> mon1 >> mon2; int mon[13] = {0, 31, 28 + fun(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (mon2 < mon1) { temp = mon1; mon1 = mon2; mon2 = temp; } for (j = mon1; j < mon2; j++) { sum += mon[j]; } if (sum % 7 == 0) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
C
#include<stdio.h> #include<stdlib.h> /* Practica 4 Calculadora lunes 24 de febrero de 2020*/ float num1, num2, Resultado; int main() { char op; printf("Calculadora simple\n"); printf("Escribe el primer numero: \n"); scanf("%f", &num1); printf("Escribe la operacion a realizar: \n"); fflush(stdin); scanf("%c", &op); printf("Escribe el segundo numero: \n"); scanf("%f", &num2); switch(op) { case '+': Resultado=num1+num2; break; case '-': Resultado=num1-num2; break; case '*': Resultado=num1*num2; break; case '/': Resultado= num1/num2; default: printf: ("operador invalido \n"); } printf(" %.2f %c %.2f = %.2f ", num1, op, num2, Resultado); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** Returns the arguments of a command */ #include <stdlib.h> #include "my.h" char **parse_command(char const *command, char const sep) { char **args = NULL; args = my_str_to_word_array(command, sep); for (unsigned int i = 0 ; args[i] ; i++) args[i] = my_clean_str(args[i]); my_strarr_remove_empty(args); return (args); }
C
/* Escreva um programa em que o usurio insira um nmero qualquer. Se o nmero digitado for um da tabela abaixo, o programa deve retornar os caracteres indicados, seno, o programa deve retornar o caractere 0 (zero). Utilize o comando switch*/ #include <stdio.h> #include <stdlib.h> int main() { int numero; printf("Insira um numero: "); scanf("%d", &numero); switch(numero) { case 1: printf("A"); break; case 2: printf("B"); break; case 3: printf("C"); break; case 4: printf("D"); break; default: printf("Numero invalido"); } }
C
#include <stdio.h> #include <unistd.h> #include "../../Src/globals.h" int main(int argc){ if(argc >= 2){ return 1; } char *username = getlogin(); if(username == NULL){ puts(RED_TEXT"Error: Unable to Receive Username"RESET); }else{ printf("%s\n",username); } return 0; }
C
#include <stdio.h> #include "miniProject.h" #define PASS 1 #define FAIL 0 int test1(); // Test for meeting overlap int test2(); // Test for NULL int test3(); // Test for NULL int test4(); // Test for Loading from file int main() { //printf("Test 1 is %s\n", test1() ? "PASS" : "FAIL" ); //printf("Test 1 is %s\n", test2() ? "PASS" : "FAIL" ); //printf("Test 1 is %s\n", test3() ? "PASS" : "FAIL" ); //printf("Test 4 is %s\n", test4() ? "PASS" : "FAIL" ); return 0; } /* Testing for meeting overlap */ int test1() { AD* ptr = createAD(); createMeeting(ptr, 10, 11, 450); insertMeeting(ptr); createMeeting(ptr, 11.3, 11.8, 455); insertMeeting(ptr); createMeeting(ptr, 8, 9, 460); insertMeeting(ptr); if (insertMeeting(ptr) == MEETING_OVERLAP) { destroyAD(ptr); return PASS; } destroyAD(ptr); return FAIL; } /* Testing for null pointer */ int test2() { if (insertMeeting(NULL) == PTR_NOT_INIT) return PASS; return FAIL; return 0; } /* Testing for null pointer */ int test3() { if( createMeeting(NULL, 10, 11, 450) == PTR_NOT_INIT) return PASS; return FAIL; return 0; } /* Testing for loading from file */ int test4() { AD* ptr = createAD(); if(ptr == NULL) return FAIL; if( loadFromFile(ptr) != PTR_NOT_INIT) { printAD(ptr); return PASS; } return FAIL; }
C
#ifndef __oclga_simple_chromosome__ #define __oclga_simple_chromosome__ #include "ga_utils.c" typedef struct { int genes[SIMPLE_CHROMOSOME_GENE_SIZE]; } __SimpleChromosome; /* ============== populate functions ============== */ // functions for populate void simple_chromosome_do_populate(global __SimpleChromosome* chromosome, uint* rand_holder) { uint gene_elements_size[] = SIMPLE_CHROMOSOME_GENE_ELEMENTS_SIZE; for (int i = 0; i < SIMPLE_CHROMOSOME_GENE_SIZE; i++) { chromosome->genes[i] = rand_range(rand_holder, gene_elements_size[i]); } } __kernel void simple_chromosome_populate(global int* chromosomes, global uint* input_rand) { int idx = get_global_id(0); // out of bound kernel task for padding if (idx >= POPULATION_SIZE) { return; } // create a private variable for each kernel to hold randome number. uint ra[1]; init_rand(input_rand[idx], ra); simple_chromosome_do_populate(((global __SimpleChromosome*) chromosomes) + idx, ra); input_rand[idx] = ra[0]; } /* ============== mutate functions ============== */ void simple_chromosome_do_mutate(global __SimpleChromosome* chromosome, uint* ra) { // create element size list uint elements_size[] = SIMPLE_CHROMOSOME_GENE_ELEMENTS_SIZE; uint gene_idx = rand_range(ra, SIMPLE_CHROMOSOME_GENE_SIZE); // use gene's mutate function to mutate it. SIMPLE_CHROMOSOME_GENE_MUTATE_FUNC(chromosome->genes + gene_idx, elements_size[gene_idx], ra); } __kernel void simple_chromosome_mutate(global int* cs, float prob_mutate, global uint* input_rand) { int idx = get_global_id(0); // out of bound kernel task for padding if (idx >= POPULATION_SIZE) { return; } uint ra[1]; init_rand(input_rand[idx], ra); float prob_m = rand_prob(ra); if (prob_m > prob_mutate) { input_rand[idx] = ra[0]; return; } simple_chromosome_do_mutate((global __SimpleChromosome*) cs, ra); } __kernel void simple_chromosome_mutate_all(global int* cs, float prob_mutate, global uint* input_rand) { int idx = get_global_id(0); // out of bound kernel task for padding if (idx >= POPULATION_SIZE) { return; } uint elements_size[] = SIMPLE_CHROMOSOME_GENE_ELEMENTS_SIZE; int i; uint ra[1]; init_rand(input_rand[idx], ra); for (i = 0; i < SIMPLE_CHROMOSOME_GENE_SIZE; i++) { if (rand_prob(ra) > prob_mutate) { continue; } SIMPLE_CHROMOSOME_GENE_MUTATE_FUNC(cs + i, elements_size[i], ra); } input_rand[idx] = ra[0]; } /* ============== crossover functions ============== */ __kernel void simple_chromosome_calc_ratio(global float* fitness, global float* ratio, global float* best, global float* worst, global float* avg) { int idx = get_global_id(0); // we use the first kernel to calculate the ratio if (idx > 0) { return; } utils_calc_ratio(fitness, ratio, best, worst, avg, idx, POPULATION_SIZE); } __kernel void simple_chromosome_pick_chromosomes(global int* cs, global float* fitness, global int* p_other, global float* ratio, global uint* input_rand) { int idx = get_global_id(0); // out of bound kernel task for padding if (idx >= POPULATION_SIZE) { return; } uint ra[1]; init_rand(input_rand[idx], ra); global __SimpleChromosome* chromosomes = (global __SimpleChromosome*) cs; global __SimpleChromosome* parent_other = (global __SimpleChromosome*) p_other; int i; int cross_idx = random_choose_by_ratio(ratio, ra, POPULATION_SIZE); // copy the chromosome to local memory for cross over for (i = 0; i < SIMPLE_CHROMOSOME_GENE_SIZE; i++) { parent_other[idx].genes[i] = chromosomes[cross_idx].genes[i]; } input_rand[idx] = ra[0]; } __kernel void simple_chromosome_do_crossover(global int* cs, global float* fitness, global int* p_other, global float* best_local, float prob_crossover, global uint* input_rand, int generation_idx) { int idx = get_global_id(0); // out of bound kernel task for padding if (idx >= POPULATION_SIZE) { return; } uint ra[1]; init_rand(input_rand[idx], ra); // keep the shortest path, we have to return here to prevent async barrier if someone is returned. if (fabs(fitness[idx] - *best_local) < 0.000001) { input_rand[idx] = ra[0]; return; } else if (rand_prob(ra) >= prob_crossover) { input_rand[idx] = ra[0]; return; } global __SimpleChromosome* chromosomes = (global __SimpleChromosome*) cs; global __SimpleChromosome* parent_other = (global __SimpleChromosome*) p_other; int i; // keep at least one for . int cross_start = rand_range(ra, SIMPLE_CHROMOSOME_GENE_SIZE - 1); int cross_end = cross_start + rand_range(ra, SIMPLE_CHROMOSOME_GENE_SIZE - cross_start); // copy partial genes from other chromosome for (i = cross_start; i < cross_end; i++) { chromosomes[idx].genes[i] = parent_other[idx].genes[i]; } input_rand[idx] = ra[0]; } #endif
C
#include "klist.h" #include "kset.h" #include "kmap.h" #include "klinkedlist.h" #include "kqueue.h" #include "kstack.h" #include "stdio.h" int equals(void *A , void *B){ // A , B are string ! if(strcmp(A,B) == 0){ return 1; }else{ return 0; } } int main() { int length,cursor; Klist *list = klist_new(sizeof(char*),equals); // Adding !!! list = klist_add(list,"A"); list = klist_add(list,"B"); list = klist_add(list,"C"); list = klist_add(list,"D"); // Putting list = klist_put(list,2,"PUT"); // Removing list = klist_remove(list,1); // Length length = klist_length(list); for(cursor = 0 ; cursor < length ; cursor++){ printf("list[%d] = %s\n", cursor, (char *) klist_get(list, cursor)); } printf("\n\n--------------------------------------------------------------\n\n"); Kset *set = kset_new(sizeof(char*),equals); // Adding !!! set = kset_add(set,"A"); set = kset_add(set,"B"); set = kset_add(set,"C"); set = kset_add(set,"D"); // Putting set = kset_put(set,2,"PUT"); // Removing set = kset_remove(set,1); // Length length = kset_length(set); for(cursor = 0 ; cursor < length ; cursor++){ printf("set[%d] = %s\n", cursor, (char *) kset_get(set, cursor)); } printf("\n\n--------------------------------------------------------------\n\n"); Kmap *map = kmap_new(sizeof(char*),sizeof(char*),equals); // Putting map = kmap_put(map,"KEY_1","VALUE_1"); map = kmap_put(map,"KEY_2","VALUE_2"); map = kmap_put(map,"KEY_1","VALUE_3"); // Removing map = kmap_remove(map,"KEY_2"); // Length length = kmap_length(map); for(cursor = 0 ; cursor < length ; cursor++){ printf("map[%s] = %s\n", (char *) kmap_key(map, cursor), (char *) kmap_value(map, cursor)); } printf("\n\n--------------------------------------------------------------\n\n"); Klinkedlist *linkedlist = klinkedlist_new(equals); // Adding !!! linkedlist = klinkedlist_add(linkedlist,"A"); linkedlist = klinkedlist_add(linkedlist,"B"); linkedlist = klinkedlist_add(linkedlist,"C"); linkedlist = klinkedlist_add(linkedlist,"D"); // Putting linkedlist = klinkedlist_put(linkedlist,2,"PUT"); // Removing linkedlist = klinkedlist_remove(linkedlist,1); // Length length = klinkedlist_length(linkedlist); for(cursor = 0 ; cursor < length ; cursor++){ printf("linkedlist[%d] = %s\n", cursor, (char *) klinkedlist_get(linkedlist, cursor)); } printf("\n\n--------------------------------------------------------------\n\n"); Kqueue *queue = kqueue_new(); // Pushing queue = kqueue_push(queue,"A"); queue = kqueue_push(queue,"B"); queue = kqueue_push(queue,"C"); queue = kqueue_push(queue,"D"); // Poping length = kqueue_length(queue); for(cursor = 0 ; cursor < length ; cursor++){ void *data = NULL; queue = kqueue_pop(queue,&data); printf("queue[%d] = %s\n", cursor, (char *) data); } printf("\n\n--------------------------------------------------------------\n\n"); Kstack *stack = kstack_new(); // Pushing stack = kstack_push(stack,"A"); stack = kstack_push(stack,"B"); stack = kstack_push(stack,"C"); stack = kstack_push(stack,"D"); // Poping length = kstack_length(stack); for(cursor = 0 ; cursor < length ; cursor++){ void *data = NULL; stack = kstack_pop(stack,&data); printf("stack[%d] = %s\n", cursor, (char *) data); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* untangle_ways.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: solefir <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/07 12:58:35 by solefir #+# #+# */ /* Updated: 2019/08/08 20:38:18 by solefir ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/lem_in.h" static void find_ends(t_room ***graph, t_way *dupl, t_way **from, t_way **to) { from[0] = (*graph)[dupl->id]->occup; while (from[0]->id == to[0]->id && (from[0] = from[0]->next)) to[0] = to[0]->parent; from[1] = dupl; to[1] = (*graph)[dupl->id]->occup; while (from[1]->id == to[1]->id && (to[1] = to[1]->parent)) from[1] = from[1]->next; from[0]->parent->parent = to[0]; to[0]->next = from[0]->parent; from[1]->parent->parent = to[1]; to[1]->next = from[1]->parent; while (from[0]->id != g_count_room - 1) { (*graph)[from[0]->id]->occup = from[0]; from[0] = from[0]->parent; } } int untangle_ways(t_room ***graph, t_way **way) { t_way *dupl; t_way *(from[2]); t_way *(to[2]); dupl = *way; while (dupl) { if (dupl->id && dupl->id != g_count_room - 1 && (*graph)[dupl->id]->occup != dupl && (to[0] = dupl)) find_ends(graph, dupl, from, to); dupl = dupl->parent; } return (1); }
C
#include<stdlib.h> #include<string.h> #include<sys/types.h> #include<unistd.h> #include<stdio.h> char * getSelfLocation(){ char link[1024]; int n; char * exe; exe = ( char * ) malloc ( 1024 * sizeof(char)); if ( exe == NULL) { printf("Error allocating memory. Exiting \n"); exit(0); } snprintf(link,sizeof link,"/proc/%d/exe",getpid()); n = readlink(link,exe,1024); if ( n ==-1) { fprintf(stderr,"ERRORRRRR\n"); exit(1); } exe[n] = 0; return exe; } void enable_history(){ char command[2048] = "rlwrap " ; strcat(command , getSelfLocation()); strcat ( command , " " ) ; strcat ( command , " --enabled" ) ; system(command); exit(0); }
C
#include <stdio.h> int main (int argc, char* argv[]) {int numbers[4]= {0}; char name [4] = {'a'}; //first, print them out raw printf("numbers:%d %d %d\n", numbers[0], numbers[1], numbers [2],numbers [3]); printf("name each : %c %c %c %c\n", name[0],name[1], name [2],name [3]); printf("name: %s\n", name); // setup the numbers numbers[0]=1; numbers[1]=2; numbers[2]=3; numbers[3]=4; //setup the name name [0]='z'; name[1]='e'; name[2]='d'; name[3]='\0'; //then print them out initialized printf("numbers:%d %d %d %d\n", numbers[0],numbers[1], numbers[1],numbers[3]); printf("name each:%c %c %c %c\n", name[0],name[1], name[2], name[3]); //print the name like a string printf("name:%s\n", name); //another way to use name char *another="zed"; printf("another:%s\n", another); printf("another each :%c %c %c %C\n", another[0], another[1], another[2], another[3]); return 0; }
C
/*------------------------------------------------------------------------- * * soe_prf.c * High-level interface that abstracts the underlying PRFs used for * the generation of the ORAM pmap. * * identification * src/common/soe_prf.c * *------------------------------------------------------------------------- */ #include "soe_c.h" #include "common/soe_prf.h" #include "logger/logger.h" #ifdef PRF #include <openssl/conf.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/hmac.h> unsigned char *key = (unsigned char *) "01234567890123456789012345678901"; unsigned int keylen = 34*sizeof(char); #endif void prf(unsigned int level, unsigned int offset, unsigned int counter, unsigned char *token) { #ifdef PRF /*Use an HMAC-SHA256 to generate the cryptographic token * Example from https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html */ int msg[3]; unsigned int md_len; msg[0] = level; msg[1] = offset; msg[2] = counter; EVP_MD_CTX *ctx = NULL; if (!(ctx = EVP_MD_CTX_new())){ selog(ERROR, "could not inittialize hmac context"); abort(); } if(1 != EVP_DigestInit_ex(ctx,EVP_sha256(), NULL)){ selog(ERROR, "Could not initalize SHA256"); abort(); } if(1 != EVP_DigestUpdate(ctx,(const unsigned char*) msg, sizeof(int)*3)){ selog(ERROR, "Could not update digest"); abort(); } if(1 != EVP_DigestFinal_ex(ctx, token, &md_len)){ selog(ERROR, "Could not finalize md"); abort(); } EVP_MD_CTX_free(ctx); #else /* If we are not generating tokens with a PRF just copy the counter */ int next = counter + 1; memcpy(token, &counter, sizeof(unsigned int)); memcpy(token + sizeof(unsigned int), &next, sizeof(unsigned int)); memcpy(token + 2*sizeof(unsigned int), &counter, sizeof(unsigned int)); memcpy(token + 3*sizeof(unsigned int), &next, sizeof(unsigned int)); #endif }
C
/* * Description: * Provide the function prototypes for managing shared memory * * void* connect_shm(int key, int size) * - REQ_conn_1: This function has two arguments: * - The first argument serves as the key for the shared memory segment. * - The second argument contains the size (in bytes) of the shared memory segment to be allocated. * - REQ_conn_2: The return value for this function is a pointer to the shared memory area which has been attached (and possibly created) by this function. * - REQ_conn_3: If, for some reason, this function cannot connect to the shared memory area as requested, it shall return a NULL pointer. * - REQ_conn_4: A program using this library function must be able to use it to attach the maximum number of shared memory segments to the calling process. (Note that Solaris 11 does not have a limit to the number of attachments, so you can use the limit that Linux supports). * * int detach_shm(void *addr) * - REQ_detach_1: This function detaches the shared memory segment attached to the process via the argument addr. * - REQ_detach_2: The associated shared memory segment is not deleted from the system. * - REQ_detach_3: This function will return OK (0) on success, and ERROR (-1) otherwise. * * int destroy_shm(int key) * - REQ_destroy_1: This function detaches all shared memory segments (attached to the calling process by connect_shm( )) associated with the argument key from the calling process. * - REQ_destroy_2: The shared memory segment is then subsequently deleted from the system. * - REQ_destroy_3: This function will return OK (0) on success, and ERROR (-1) otherwise. * * void show_segments() * loops accross all shared memory segments currently connected and logs them * * bool shm_lock(int key) * Note: this function does nothing unless use_semaphores(true) is called. * Given the same key used for the _shm* functions, this function attempts to * lock the systemV semaphore (created upon connect_shm). This is useful when * attempting to coordinate shared memory access accross processes. Return * true if the lock was positively acquired, returns false otherwise. * * bool shm_unlock(int key) * Note: this function does nothing unless use_semaphores(true) is called. * Given the same key used for the _shm* functions, this function attempts to * unlock the systemV semaphore (created upon connect_shm). This is useful when * attempting to coordinate shared memory access accross processes. Return * true if the lock was positively unlocked, returns false otherwise. * * void use_semaphores(bool set) * Setting to true enables the use of sem_lock() and sum_unlock() for coordinating * access to a shared memory segment. By default semaphores are not created and * shm_lock() and shm_unlock() do nothing until 'true' is passed into an invocation * of this function. This must be called before using connect_shm or else undefined * behavior will occur. * * Note on semaphore behavior: semaphores are created on connect_shm() and destroyed * on destroy_shm() and detach_shm() only if the detected number of attachments * for the segment being protected by the semaphore is 0. This is not fool-proof * since multiple apps can be using effectively different segments but using * the same semaphore, thus the attachment count can be wrong which could lead to * unsupported behavior (deleting the semaphore while another process is still * using it). */ #define SHM_OK 0 #define SHM_ERROR -1 #define SHM_MAX_SEGMENTS 4096 #define SHM_MAX_LINUX_ATTACHMENTS 65514 typedef struct SegmentNode { int key; int shm_id; int lock_id; int size; List* attachments; } SegmentNode; void* connect_shm(int key, int size); int detach_shm(void* addr); int destroy_shm(int key); void show_segments(); bool shm_lock(int key); bool shm_unlock(int key); void use_semaphores(bool set);
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> #include <time.h> #include <string.h> #include "ux_fs.h" int main(int argc, char **argv) { struct ux_dirent dir; struct ux_superblock sb; struct ux_inode inode; time_t tm; off_t nsectors = UX_MAXBLOCKS; int devfd, error, i; int map_blks; char block[UX_BSIZE]; if (argc != 2) { fprintf(stderr, "uxmkfs: Need to specify device\n"); exit(1); } devfd = open(argv[1], O_WRONLY); if (devfd < 0) { fprintf(stderr, "uxmkfs: Failed to open device\n"); exit(1); } error = lseek(devfd, (off_t)(nsectors * UX_BSIZE), SEEK_SET); if (error == -1) { fprintf(stderr, "uxmkfs: Cannot create filesystem" " of specified size\n"); exit(1); } lseek(devfd, 0, SEEK_SET); /* * Fill in the fields of the superblock and write * it out to the first block of the device. */ sb.s_magic = UX_MAGIC; sb.s_mod = UX_FSCLEAN; sb.s_nifree = UX_MAXFILES - 4; sb.s_nbfree = UX_MAXBLOCKS - 2; /* * First 4 inodes are in use. Inodes 0 and 1 are not * used by anything, 2 is the root directory and 3 is * lost+found. */ sb.s_inode[0] = UX_INODE_INUSE; sb.s_inode[1] = UX_INODE_INUSE; sb.s_inode[2] = UX_INODE_INUSE; sb.s_inode[3] = UX_INODE_INUSE; /* * The rest of the inodes are marked unused */ for (i = 4 ; i < UX_MAXFILES ; i++) sb.s_inode[i] = UX_INODE_FREE; /* * The first two blocks are allocated for the entries * for the root and lost+found directories. */ sb.s_block[0] = UX_BLOCK_INUSE; sb.s_block[1] = UX_BLOCK_INUSE; /* * The rest of the blocks are marked unused */ for (i = 2 ; i < UX_MAXBLOCKS ; i++) sb.s_block[i] = UX_BLOCK_FREE; write(devfd, (char *)&sb, sizeof(struct ux_superblock)); /* * The root directory and lost+found directory inodes * must be initialized. */ time(&tm); memset((void *)&inode, 0, sizeof(struct ux_inode)); inode.i_mode = S_IFDIR | 0755; inode.i_nlink = 3; /* ".", ".." and "lost+found" */ inode.i_atime = tm; inode.i_mtime = tm; inode.i_ctime = tm; inode.i_uid = 0; inode.i_gid = 0; inode.i_size = 3 * sizeof(struct ux_dirent); inode.i_blocks = 1; inode.i_addr[0] = UX_FIRST_DATA_BLOCK; lseek(devfd, (UX_INODE_BLOCK + UX_ROOT_INO)* UX_BSIZE, SEEK_SET); write(devfd, (char *)&inode, sizeof(struct ux_inode)); memset((void *)&inode, 0 , sizeof(struct ux_inode)); inode.i_mode = S_IFDIR | 0755; inode.i_nlink = 2; /* "." and ".." */ inode.i_atime = tm; inode.i_mtime = tm; inode.i_ctime = tm; inode.i_uid = 0; inode.i_gid = 0; inode.i_size = 2 * sizeof(struct ux_dirent); inode.i_blocks = 1; inode.i_addr[0] = UX_FIRST_DATA_BLOCK + 1; lseek(devfd, (UX_INODE_BLOCK + UX_ROOT_INO + 1)* UX_BSIZE, SEEK_SET); write(devfd, (char *)&inode, sizeof(struct ux_inode)); /* * Fill in the directory entries for root */ lseek(devfd, UX_FIRST_DATA_BLOCK * UX_BSIZE, SEEK_SET); memset((void *)&block, 0, UX_BSIZE); write(devfd, block, UX_BSIZE); lseek(devfd, UX_FIRST_DATA_BLOCK * UX_BSIZE, SEEK_SET); memset(&dir, 0, sizeof(struct ux_dirent)); dir.d_ino = 2; strcpy(dir.d_name, "."); write(devfd, (char *)&dir, sizeof(struct ux_dirent)); dir.d_ino = 2; strcpy(dir.d_name, ".."); write(devfd, (char *)&dir, sizeof(struct ux_dirent)); dir.d_ino = 3; strcpy(dir.d_name, "lost+found"); write(devfd, (char *)&dir, sizeof(struct ux_dirent)); /* * Fill in the directory entries for lost+found */ lseek(devfd, UX_FIRST_DATA_BLOCK * UX_BSIZE + UX_BSIZE, SEEK_SET); memset((void *)&block, 0, UX_BSIZE); write(devfd, block, UX_BSIZE); lseek(devfd, UX_FIRST_DATA_BLOCK * UX_BSIZE + UX_BSIZE, SEEK_SET); memset(&dir, 0, sizeof(struct ux_dirent)); dir.d_ino = 2; strcpy(dir.d_name, "."); write(devfd, (char *)&dir, sizeof(struct ux_dirent)); dir.d_ino = 2; strcpy(dir.d_name, ".."); write(devfd, (char *)&dir, sizeof(struct ux_dirent)); close(devfd); return 0; }
C
#include <stdio.h> #include <stdlib.h> int jednaki(char *s1, char *s2) { int i = 0, b = 0; while(*(s1 + i) != '\0' && *(s2 + i) != '\0'){ if(*(s1 + i) != *(s2 + i)){ b = 1; break; } i++; } if(b == 0 && *(s1 + i) == '\0' && *(s2 + i) == '\0') return 1; else return 0; } int main() { char s1[20]; char s2[20]; printf("Unesite prvi string:"); scanf("%s",s1); printf("\nUnesite drugi string:"); scanf("%s",s2); int jdk=jednaki(s1,s2); if(jdk == 1){ printf("\nJednaki su."); } else printf("\nNisu jednaki."); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* * T = O(Nlog(N)) * * */ typedef int ElementType; void printArr(ElementType a[], int n){ int i; for(i = 0; i < n; i++){ printf(" <%d> ", a[i]); } printf("\n---------------------------\n"); } // 有序子列的归并,两个有序子列合并为一个有序子列 void Merge(ElementType A[], ElementType TempA[], int L, int R, int RightEnd){ /* L = 左边的起始位置,R = 右边的起始位置,RightEnd = 右边的终点位置*/ int LeftEnd, temp, NumElements, i; LeftEnd = R - 1;// 右边的终点位置,假设左右两边紧挨着 temp = L;// 存放结果的数组的初始位置, 与L相对 NumElements = RightEnd - L + 1;// 计算出元素的个数 while(L <= LeftEnd && R <= RightEnd){ // 其中一个子序列已经空了,跳出 // 注意是<=,保证了排序的稳定性? if(A[L] <= A[R]) TempA[temp++] = A[L++]; else TempA[temp++] = A[R++]; } while(L <= LeftEnd)// 直接复制左边剩下的 TempA[temp++] = A[L++]; while(R <= RightEnd)// 直接复制右边剩下的 TempA[temp++] = A[R++]; for(i = 0; i < NumElements; i++, RightEnd--) A[RightEnd] = TempA[RightEnd]; } // 分而治之 void MSort(ElementType A[], ElementType TempA[], int L, int RightEnd){ int Center; if(L < RightEnd){ Center = (L + RightEnd) / 2; MSort(A, TempA, L, Center);// 左边递归的排序 MSort(A, TempA, Center + 1, RightEnd);// 右边递归的排序 Merge(A, TempA, L, Center + 1, RightEnd);// 左右已经排序的子列合并为一个子列 printArr(TempA, RightEnd - L + 1); } } // 统一函数接口 void Merge_sort1(ElementType A[], int N){ ElementType *TempA; // 为什么不在Merge函数内部使用TempA TempA = (ElementType *)malloc(sizeof(ElementType) * N); if(TempA == NULL){ printf("空间不足\n"); return; } MSort(A, TempA, 0, N - 1); free(TempA); } // 非递归算法 void Merge_pass(ElementType A[], ElementType TempA[], int N, int length){ // length = 当前有序子列的长度 int i, j; for(i = 0; i <= N - 2 * length; i += 2 * length) Merge(A, TempA, i, i + length, i + 2 * length - 1);; if(i + length < N)// 归并最后2个子列 Merge(A, TempA, i, i + length, N - 1); else// 最后只剩下1个子列 for(j = i; j < N; j++) TempA[j] = A[j]; } void Merge_sort(ElementType A[], int N){ int length = 1;// 初始化子序列的长度为1 ElementType *TempA; TempA = (ElementType *)malloc(sizeof(ElementType) * N); if(TempA == NULL){ printf("空间不足\n"); return; } while(length < N){ Merge_pass(A, TempA, N, length); length *= 2; Merge_pass(TempA, A, N, length); length *= 2; } free(TempA); } int main(){ int arr[1024] = {0}; printf("please input the disorder numbers: \n"); int i = 0; int n = 0; scanf("%d", &arr[i]); while(arr[i]){ i++; scanf("%d", &arr[i]); } n = i; printf("n = %d\n", n); printf("before sort...\n"); printArr(arr, n); Merge_sort(arr, n); printf("after sort...\n"); printArr(arr, n); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "person.h" /*_____________________*/ int main() { p1 = malloc(sizeof(struct Person)); strcpy(p1->name, "ȫ浿"); p1->age = 30; strcpy(p1->address, " 걸 ѳ"); printf("%s %d %s\n", p1->name, p1->age, p1->address); free(p1); return 0; }
C
#include <stdio.h> #include <stdbool.h> char text[10000]; int main() { int i = 0; bool isFirstQuote = true; char ch; while((ch = getchar()) != EOF){ if(ch == 34 && isFirstQuote){ printf("``"); isFirstQuote = false; } else if(ch == 34 && !isFirstQuote){ printf("''"); isFirstQuote = true; } else printf("%c",ch); } return 0; }
C
#include <stdio.h> #include <stdlib.h> void main(void) { printf("Hello world!\n"); const int length=10; const int width=5; int area; area=length*width; printf("area is equal %d",area); return 0; }
C
/* * Copyright (c) 1994,1996 by Sun Microsystems Inc. * All rights reserved. */ #ident "@(#)strcmp.c 1.1 96/09/20 SMI" #include <sys/salib.h> /* * Compare strings: s1>s2: >0 s1==s2: 0 s1<s2: <0 */ int strcmp(register char *s1, register char *s2) { while (*s1 == *s2++) if (*s1++ == '\0') return (0); return (*s1 - *--s2); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <sys/ioctl.h> #include <linux/spi/spidev.h> #define LENGTH 3 int main(int argc, char **argv) { int spi_fd = 0; int mode = SPI_MODE_0; int result; int value; struct spi_ioc_transfer spi; unsigned char data_out[LENGTH] = {0x1,0x00,0x0}; unsigned char data_in[LENGTH]; double Vin = 0; double deg_c = 0,max = 0 ,min = 24; double c2Value; int i = 0; ioctl(spi_fd,SPI_IOC_WR_MODE,&mode); memset(&spi,0,sizeof(struct spi_ioc_transfer)); spi . tx_buf = (unsigned long)&data_out; spi . rx_buf = (unsigned long)&data_in; spi . len = LENGTH; spi . delay_usecs = 0; spi . speed_hz = 100000; spi . bits_per_word = 8; spi . cs_change = 0; /* Open SPI device */ spi_fd = open("/dev/spidev0.0",O_RDWR); /* Set SPI Mode_0 */ result = ioctl(spi_fd, SPI_IOC_MESSAGE(1), &spi); if(result < 0) printf("Error\n"); /* Loop forever printing the CH0 and CH1 Voltages */ /* Once per second. */ while(1){ data_out[1] = 0x10; //setting what channel i want to read ioctl(spi_fd,SPI_IOC_MESSAGE(1),&spi);// storing the data into data_in value = (data_in[1] << 8) | data_in[2]; // printf("First byte: %d\n", data_in[1]); // printf("Second byte: %d\n", data_in[2]); Vin = (value * 3.3) /1024; data_out[1] = 0xA0; //setting what channel i want to read ioctl(spi_fd,SPI_IOC_MESSAGE(1),&spi);// storing the data into data_in c2Value = ((data_in[1] << 8) + data_in[2]) & 0x03FF;; c2Value = (c2Value * Vin) / 1024; deg_c = (100 * c2Value) - 50; printf("Degrees(C): %f\n",deg_c); usleep(1000000); //setting up max and min values if(deg_c > max) max = deg_c; if(deg_c < min) min = deg_c; i = i+1; printf("%d\n",i); //printing max and min values after 15 seconds if(i == 15){ i = 0; printf("Max: %f Celcius & Min: %f Celcius\n",max,min); } } /* Use the SPI_IOC_MESSAGE(1) ioctl() as described in the class notes */ return 0; }
C
/* * Created on Sat Jul 11 2020 * * Created by: Glen Zachariah * For more: https://glenzac.wordpress.com * License: CC0 1.0 Universal * * For MSP430F5529LP * --------Hardware--------- * LED1 -> P1.0 (Red) * LED2 -> P4.7 (Green) * Button S1 -> P2.1 * Button S2 -> P1.1 * ------------------------- */ #include <msp430.h> void switch1() { if(P2IN & BIT1) P1OUT &= ~BIT0; else P1OUT |= BIT0; } void switch2() { if(P1IN & BIT1) P4OUT &= ~BIT7; else P4OUT |= BIT7; } int main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer P1DIR |= BIT0; // Set P1.0 as OUTPUT P4DIR |= BIT7; // Set P4.7 as OUTPUT P2DIR &= ~BIT1; // Set P2.1 as INPUT P2REN |= BIT1; // Enable P2.1 pull up/down configuration P2OUT |= BIT1; // Set P2.1 as INPUT P1DIR &= ~BIT1; // Set P1.1 as INPUT P1REN |= BIT1; // Enable P1.1 pull up/down configuration P1OUT |= BIT1; // Enable pull up on P1.1 while(1) { switch1(); switch2(); } return 0; }
C
#include "stdlib.h" #include "math.h" #include "driver/i2c.h" #include "esp_log.h" #include "sensor.h" #define ERR_CHECK(f) \ err = f; \ if (err != ESP_OK) \ { \ ESP_LOGE(TAG, "Error: %d, __file__: %s, __line__: %d\n", err, __FILE__, __LINE__); \ goto end; \ } static const char *TAG = __FILE__; hdc1080_device_t *hdc1080_init(hdc1080_config_t config) { hdc1080_device_t *device; esp_err_t err = ESP_OK; if ((device = malloc(sizeof(hdc1080_device_t))) == NULL) { return NULL; } ERR_CHECK(i2c_reg_write(HDC1080_REG_CONF, (uint8_t *)&(config.raw), sizeof(config.raw))); device->config = config; end: return device; } esp_err_t hdc1080_read_sensor(hdc1080_device_t *device) { esp_err_t err = ESP_OK; uint8_t data[4]; uint16_t temperature_raw; uint16_t humidity_raw; assert(device->config.mode == HDC1080_CONF_MODE_1); ERR_CHECK(_hdc1080_reg_read_memory(HDC1080_REG_TEMP, data, 4, DELAY_BOTH_MEASUREMENTS)); temperature_raw = data[0] << 8 | data[1]; humidity_raw = data[2] << 8 | data[3]; device->temperature = _convert_temperature(temperature_raw); device->humidity = _convert_humidity(humidity_raw); ESP_LOGD(TAG, "Temperature: %f", device->temperature); ESP_LOGD(TAG, "Humidity: %f", device->humidity); end: return err; } esp_err_t hdc1080_read_temperature(hdc1080_device_t *device) { esp_err_t err = ESP_OK; uint8_t delay_time; uint8_t data[2]; uint16_t temperature_raw; uint8_t delay_multiplier = 2; assert(device->config.mode == HDC1080_CONF_MODE_0); // Get delay time. First value is specified in datasheet, but it does not seem enough. Multiply by 3 seems to work. switch (device->config.temperature_resolution) { case HDC1080_CONF_TRES_11BIT: delay_time = 3.65 * delay_multiplier; break; case HDC1080_CONF_TRES_14BIT: delay_time = 6.35 * delay_multiplier; break; default: assert(0); break; } ERR_CHECK(i2c_reg_read_memory(HDC1080_REG_TEMP, data, 2, delay_time)); temperature_raw = data[0] << 8 | data[1]; device->temperature = _convert_temperature(temperature_raw); // ESP_LOGD(TAG, "Temperature raw: 0x%02x%02x", data[0], data[1]); ESP_LOGD(TAG, "Temperature: %f", device->temperature); end: return err; } esp_err_t hdc1080_read_humidity(hdc1080_device_t *device) { esp_err_t err = ESP_OK; uint8_t delay_time; uint8_t data[2]; uint16_t humidity_raw; uint8_t delay_multiplier = 2; assert(device->config.mode == HDC1080_CONF_MODE_0); // Get delay time. First value is specified by the datasheet, but it does not seem enough. Multiply by 3 seems to work. switch (device->config.humidity_resolution) { case HDC1080_CONF_HRES_8BIT: delay_time = 2.50 * delay_multiplier; break; case HDC1080_CONF_HRES_11BIT: delay_time = 3.85 * delay_multiplier; break; case HDC1080_CONF_HRES_14BIT: delay_time = 6.50 * delay_multiplier; break; default: assert(0); break; } ERR_CHECK(i2c_reg_read_memory(HDC1080_REG_HUMD, data, 2, delay_time)); humidity_raw = data[0] << 8 | data[1]; device->humidity = _convert_humidity(humidity_raw); ESP_LOGD(TAG, "Humidity: %f", device->humidity); end: return err; } esp_err_t hdc1080_median_temperature(hdc1080_device_t *device, uint8_t repeats) { esp_err_t err = ESP_OK; float *measurements = (float *)malloc(sizeof(float) * repeats); if (measurements == NULL) { err = ESP_ERR_NO_MEM; return err; } for (uint8_t i = 0; i < repeats; i++) { ERR_CHECK(hdc1080_read_temperature(device)); measurements[i] = device->temperature; } qsort(measurements, repeats, sizeof(float), _compare_floats); // Set median temperature, which is the middle item in a sorted list. device->temperature = measurements[(repeats + 1) / 2 - 1]; end: free(measurements); return err; } esp_err_t hdc1080_median_humidity(hdc1080_device_t *device, uint8_t repeats) { esp_err_t err = ESP_OK; float *measurements = (float *)malloc(sizeof(float) * repeats); if (measurements == NULL) { err = ESP_ERR_NO_MEM; return err; } for (uint8_t i = 0; i < repeats; i++) { ERR_CHECK(hdc1080_read_humidity(device)); measurements[i] = device->humidity; } qsort(measurements, repeats, sizeof(float), _compare_floats); // Set median temperature, which is the middle item in a sorted list. device->humidity = measurements[(repeats + 1) / 2 - 1]; end: free(measurements); return err; } float _convert_temperature(uint16_t temperature_raw) { return (temperature_raw / pow(2, 16)) * 165.0 - 40.0; } float _convert_humidity(uint16_t humidity_raw) { return (humidity_raw / pow(2, 16)) * 100; } int _compare_floats(const void *a, const void *b) { float *x = (float *)a; float *y = (float *)b; if (*x < *y) return -1; else if (*x > *y) return 1; return 0; }
C
/* pwm.c - analogWrite implementation for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "wiring_private.h" #include "pins_arduino.h" #include "c_types.h" #include "eagle_soc.h" #include "ets_sys.h" #ifndef F_CPU #define F_CPU 800000000L #endif struct pwm_isr_table { uint8_t len; uint16_t steps[17]; uint32_t masks[17]; }; struct pwm_isr_data { struct pwm_isr_table tables[2]; uint8_t active;//0 or 1, which table is active in ISR }; static struct pwm_isr_data _pwm_isr_data; uint32_t pwm_mask = 0; uint16_t pwm_values[17] = {0,}; uint32_t pwm_freq = 1000; uint32_t pwm_range = PWMRANGE; uint8_t pwm_steps_changed = 0; uint32_t pwm_multiplier = 0; int pwm_sort_array(uint16_t a[], uint16_t al) { uint16_t i, j; for (i = 1; i < al; i++) { uint16_t tmp = a[i]; for (j = i; j >= 1 && tmp < a[j-1]; j--) { a[j] = a[j-1]; } a[j] = tmp; } int bl = 1; for(i = 1; i < al; i++) { if(a[i] != a[i-1]) { a[bl++] = a[i]; } } return bl; } uint32_t pwm_get_mask(uint16_t value) { uint32_t mask = 0; int i; for(i=0; i<17; i++) { if((pwm_mask & (1 << i)) != 0 && pwm_values[i] == value) { mask |= (1 << i); } } return mask; } void prep_pwm_steps() { if(pwm_mask == 0) { return; } int pwm_temp_steps_len = 0; uint16_t pwm_temp_steps[17]; uint32_t pwm_temp_masks[17]; uint32_t range = pwm_range; if((F_CPU / ESP8266_CLOCK) == 1) { range /= 2; } int i; for(i=0; i<17; i++) { if((pwm_mask & (1 << i)) != 0 && pwm_values[i] != 0) { pwm_temp_steps[pwm_temp_steps_len++] = pwm_values[i]; } } pwm_temp_steps[pwm_temp_steps_len++] = range; pwm_temp_steps_len = pwm_sort_array(pwm_temp_steps, pwm_temp_steps_len) - 1; for(i=0; i<pwm_temp_steps_len; i++) { pwm_temp_masks[i] = pwm_get_mask(pwm_temp_steps[i]); } for(i=pwm_temp_steps_len; i>0; i--) { pwm_temp_steps[i] = pwm_temp_steps[i] - pwm_temp_steps[i-1]; } pwm_steps_changed = 0; struct pwm_isr_table *table = &(_pwm_isr_data.tables[!_pwm_isr_data.active]); table->len = pwm_temp_steps_len; ets_memcpy(table->steps, pwm_temp_steps, (pwm_temp_steps_len + 1) * 2); ets_memcpy(table->masks, pwm_temp_masks, pwm_temp_steps_len * 4); pwm_multiplier = ESP8266_CLOCK/(range * pwm_freq); pwm_steps_changed = 1; } void ICACHE_RAM_ATTR pwm_timer_isr() //103-138 { struct pwm_isr_table *table = &(_pwm_isr_data.tables[_pwm_isr_data.active]); static uint8_t current_step = 0; TEIE &= ~TEIE1;//14 T1I = 0;//9 if(current_step < table->len) { //20/21 uint32_t mask = table->masks[current_step] & pwm_mask; if(mask & 0xFFFF) { GPOC = mask & 0xFFFF; //15/21 } if(mask & 0x10000) { GP16O = 0; //6/13 } current_step++;//1 } else { current_step = 0;//1 if(pwm_mask == 0) { //12 table->len = 0; return; } if(pwm_mask & 0xFFFF) { GPOS = pwm_mask & 0xFFFF; //11 } if(pwm_mask & 0x10000) { GP16O = 1; //5/13 } if(pwm_steps_changed) { //12/21 _pwm_isr_data.active = !_pwm_isr_data.active; table = &(_pwm_isr_data.tables[_pwm_isr_data.active]); pwm_steps_changed = 0; } } T1L = (table->steps[current_step] * pwm_multiplier);//23 TEIE |= TEIE1;//13 } void pwm_start_timer() { timer1_disable(); ETS_FRC_TIMER1_INTR_ATTACH(NULL, NULL); ETS_FRC_TIMER1_NMI_INTR_ATTACH(pwm_timer_isr); timer1_enable(TIM_DIV1, TIM_EDGE, TIM_SINGLE); timer1_write(1); } void ICACHE_RAM_ATTR pwm_stop_pin(uint8_t pin) { if(pwm_mask){ pwm_mask &= ~(1 << pin); if(pwm_mask == 0) { ETS_FRC_TIMER1_NMI_INTR_ATTACH(NULL); timer1_disable(); timer1_isr_init(); } } } extern void __analogWrite(uint8_t pin, int value) { bool start_timer = false; if(value == 0) { digitalWrite(pin, LOW); prep_pwm_steps(); return; } if((pwm_mask & (1 << pin)) == 0) { if(pwm_mask == 0) { memset(&_pwm_isr_data, 0, sizeof(_pwm_isr_data)); start_timer = true; } pinMode(pin, OUTPUT); digitalWrite(pin, LOW); pwm_mask |= (1 << pin); } if((F_CPU / ESP8266_CLOCK) == 1) { value = (value+1) / 2; } pwm_values[pin] = value % (pwm_range + 1); prep_pwm_steps(); if(start_timer) { pwm_start_timer(); } } extern void __analogWriteFreq(uint32_t freq) { pwm_freq = freq; prep_pwm_steps(); } extern void __analogWriteRange(uint32_t range) { pwm_range = range; prep_pwm_steps(); } extern void analogWrite(uint8_t pin, int val) __attribute__ ((weak, alias("__analogWrite"))); extern void analogWriteFreq(uint32_t freq) __attribute__ ((weak, alias("__analogWriteFreq"))); extern void analogWriteRange(uint32_t range) __attribute__ ((weak, alias("__analogWriteRange")));
C
/* * Funny Language - a free style programming language. * Copyright (C) 2015 by fanguangping ([email protected]) * math.c */ #include <stdlib.h> #include <math.h> #include <float.h> #include "operator.h" static Num g_zero = { .isFix = 1, {.longValue = 0L} }; static Num g_one = { .isFix = 1, {.longValue = 1L} }; static long num2int(Num n) { return (n.isFix ? (n).longValue : (long) (n).doubleValue); } static double num2float(Num n) { return (!n.isFix ? (n).doubleValue : (double) (n).longValue); } // 两数相加 static Num num_add(Num a, Num b) { Num result; result.isFix = a.isFix && b.isFix; if (result.isFix) { result.longValue = a.longValue + b.longValue; } else { result.doubleValue = num2float(a) + num2float(b); } return result; } // 两数相减 static Num num_sub(Num a, Num b) { Num result; result.isFix = a.isFix && b.isFix; if (result.isFix) { result.longValue = a.longValue - b.longValue; } else { result.doubleValue = num2float(a) - num2float(b); } return result; } // 两数相乘 static Num num_mul(Num a, Num b) { Num result; result.isFix = a.isFix && b.isFix; if (result.isFix) { result.longValue = a.longValue * b.longValue; } else { result.doubleValue = num2float(a) * num2float(b); } return result; } // 两数相除 static Num num_div(Num a, Num b) { Num result; result.isFix = a.isFix && b.isFix && (a.longValue % b.longValue == 0); if (result.isFix) { result.longValue = a.longValue / b.longValue; } else { result.doubleValue = num2float(a) / num2float(b); } return result; } // 两数整除 static Num num_intdiv(Num a, Num b) { Num result; result.isFix = a.isFix && b.isFix; if (result.isFix) { result.longValue = a.longValue / b.longValue; } else { result.doubleValue = num2float(a) / num2float(b); } return result; } // 两数求余 static Num num_rem(Num a, Num b) { long e1 = num2int(a); long e2 = num2int(b); long result = e1 % e2; //余数必须和第一个操作数符号相同 if ((result > 0) && (e1 < 0)) result -= labs(e2); else if ((result < 0) && (e1 > 0)) result += labs(e2); Num r; r.isFix = a.isFix && b.isFix; r.longValue = result; return r; } // 两数求模 static Num num_mod(Num a, Num b) { long e1 = num2int(a); long e2 = num2int(b); long result = e1 % e2; //模数必须和第二个操作数符号相同 if (result * e2 < 0) { result += e2; } Num r; r.isFix = a.isFix && b.isFix; r.longValue = result; return r; } /* Round to nearest. Round to even if midway */ // 将浮点数四舍五入到整数 static double round_per_r5rs(double x) { double fl = floor(x); double ce = ceil(x); double dfl = x - fl; double dce = ce - x; if (dfl > dce) { return ce; } else if (dfl < dce) { return fl; } else { if (fmod(fl, 2.0) == 0.0) { /* I imagine this holds */ return fl; } else { return ce; } } } // 判断一个浮点数是否近似为0 static int is_zero_double(double x) { return x < DBL_MIN && x > -DBL_MIN; } //将一个数字(整型或浮点型)无损的转化为整型 // (inexact->exact x) Cell* op_inexact2exact(Scheme *sc) { Cell* num; double dd; num = first(sc->args); if (num->_num.isFix) { return s_return_helper(sc, num); } else if (modf(num->_num.doubleValue, &dd) == 0.0) { return s_return_helper(sc, make_integer(sc, long_value(num))); } else { return error_helper(sc, "inexact->exact: not integral:", num); } } // (exp x) Cell* op_exp(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, exp(double_value(num)))); } // (log x) Cell* op_log(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, log(double_value(num)))); } // (sin x) Cell* op_sin(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, sin(double_value(num)))); } // (cos x) Cell* op_cos(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, cos(double_value(num)))); } // (tan x) Cell* op_tan(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, tan(double_value(num)))); } // (asin x) Cell* op_asin(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, asin(double_value(num)))); } // (acos x) Cell* op_acos(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, acos(double_value(num)))); } // (atan x) // (atan x y) Cell* op_atan(Scheme *sc) { Cell* x = first(sc->args); if (rest(sc->args) == &g_nil) { return s_return_helper(sc, make_real(sc, atan(double_value(x)))); } else { Cell* y = second(sc->args); return s_return_helper(sc, make_real(sc, atan2(double_value(x), double_value(y)))); } } // (sqrt x) Cell* op_sqrt(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, sqrt(double_value(num)))); } // (expt x y) Cell* op_expt(Scheme *sc) { Cell* x = first(sc->args); Cell* y = second(sc->args); double result; int real_result = TRUE; if (x->_num.isFix && y->_num.isFix) real_result = FALSE; /* This 'if' is an R5RS compatibility fix. */ /* NOTE: Remove this 'if' fix for R6RS. */ if (double_value(x) == 0 && double_value(y) < 0) { result = 0.0; } else { result = pow(double_value(x), double_value(y)); } /* Before returning integer result make sure we can. */ /* If the test fails, result is too big for integer. */ if (!real_result) { long result_as_long = (long) result; //如果result有小数位,必然导致result_as_long和result不相等 if (result != (double) result_as_long) real_result = TRUE; } if (real_result) { return s_return_helper(sc, make_real(sc, result)); } else { return s_return_helper(sc, make_integer(sc, (long) result)); } } // (floor x) Cell* op_floor(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, floor(double_value(num)))); } // (ceiling x) Cell* op_ceiling(Scheme *sc) { Cell* num = first(sc->args); return s_return_helper(sc, make_real(sc, ceil(double_value(num)))); } // (truncate x) Cell* op_truncate(Scheme *sc) { Cell* num = first(sc->args); double doubleValue = double_value(num); if (doubleValue > 0) { return s_return_helper(sc, make_real(sc, floor(doubleValue))); } else { return s_return_helper(sc, make_real(sc, ceil(doubleValue))); } } // (round x) Cell* op_round(Scheme *sc) { Cell* num = first(sc->args); if (num->_num.isFix) return s_return_helper(sc, num); return s_return_helper(sc, make_real(sc, round_per_r5rs(double_value(num)))); } // (+ x y ...) Cell* op_add(Scheme *sc) { Num value = g_zero; Cell* x; for (x = sc->args; x != &g_nil; x = cdr(x)) { value = num_add(value, num_value(car(x))); } return s_return_helper(sc, make_number(sc, value)); } // (* x y ...) Cell* op_mul(Scheme *sc) { Num value = g_one; Cell* x; for (x = sc->args; x != &g_nil; x = cdr(x)) { value = num_mul(value, num_value(car(x))); } return s_return_helper(sc, make_number(sc, value)); } // (- x y ...) Cell* op_sub(Scheme *sc) { Num value; Cell* x; if (cdr(sc->args) == &g_nil) { x = sc->args; value = g_zero; } else { x = cdr(sc->args); value = num_value(car(sc->args)); } for (; x != &g_nil; x = cdr(x)) { value = num_sub(value, num_value(car(x))); } return s_return_helper(sc, make_number(sc, value)); } // (/ x y ...) Cell* op_div(Scheme *sc) { Num value; Cell* x; if (cdr(sc->args) == &g_nil) { x = sc->args; value = g_one; } else { x = cdr(sc->args); value = num_value(car(sc->args)); } for (; x != &g_nil; x = cdr(x)) { if (!is_zero_double(double_value(car(x)))) value = num_div(value, num_value(car(x))); else { return error_helper(sc, "/: division by zero", NULL); } } return s_return_helper(sc, make_number(sc, value)); } // (quotient x y ...) Cell* op_intdiv(Scheme *sc) { Num value; Cell* x; if (cdr(sc->args) == &g_nil) { x = sc->args; value = g_one; } else { x = cdr(sc->args); value = num_value(car(sc->args)); } for (; x != &g_nil; x = cdr(x)) { if (long_value(car(x)) != 0) value = num_intdiv(value, num_value(car(x))); else { return error_helper(sc, "quotient: division by zero", NULL); } } return s_return_helper(sc, make_number(sc, value)); } // (remainder x y) Cell* op_rem(Scheme *sc) { Cell* x = first(sc->args); Cell* y = second(sc->args); Num value = num_value(x); if (long_value(y) != 0) { value = num_rem(value, num_value(y)); return s_return_helper(sc, make_number(sc, value)); } else { return error_helper(sc, "remainder: division by zero", NULL); } } // (modulo x y) Cell* op_mod(Scheme *sc) { Cell* x = first(sc->args); Cell* y = second(sc->args); Num value = num_value(x); if (long_value(y) != 0) { value = num_mod(value, num_value(y)); return s_return_helper(sc, make_number(sc, value)); } else { return error_helper(sc, "modulo: division by zero", NULL); } } void init_math_constants(Scheme *sc) { add_constant(sc, "*PI*", make_real(sc, M_PI)); add_constant(sc, "*E*", make_real(sc, M_E)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* eval_expr.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thduong <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/12 06:34:39 by thduong #+# #+# */ /* Updated: 2021/06/13 20:00:00 by thduong ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef EVAL_EXPR_H # define EVAL_EXPR_H # include <stdlib.h> # include <unistd.h> typedef struct s_stack_int { int *st; int n; } t_stack_int; typedef struct s_stack_char { char *st; int n; } t_stack_char; void ft_putnbr(int nbr); void ft_putchar(char c); int ft_strlen(char *str); int eval_expr(char *str); int is_operator(char o); int is_digit(char c); int precedence(char o); int eval(int a, int b, char operator); #endif
C
/* * AUTHORS : <[email protected]> * VERSION : 1.0.0 * TYPE : Header * LICENSE : MIT */ /* Make guard for this header */ #ifndef FGTL_HEADER_H #define FGTL_HEADER_H /* Include header event * for handle event */ #include "FGTL_Event.h" /* Include header system * for using system on terminal */ #include "FGTL_System.h" /* Include header scree * for manage screen on console */ #include "FGTL_Screen.h" /* * If you see code * #ifdef __cplusplus * extern "C" { * #endif * * This used for, make if you use the c++ compiler, * it will be extern in c language */ #ifdef __cplusplus extern "C" { #endif /* * @parameter { void } * This function for intialize dependencies * like SDL2, this for using features * in dependencies */ void FGTL_Init(void); #ifdef __cplusplus } #endif /* The section to load the header * file in the middle of the init * function and the quit function */ /* This header for load script * function for help in file */ #include "FGTL_File.h" /* This header for load script * function for help in sound */ #include "FGTL_Sound.h" #ifdef __cplusplus extern "C" { #endif /* * @parameter { void } * This function for quit all dependencies */ void FGTL_Close(void); #ifdef __cplusplus } #endif #ifdef __cplusplus extern "C" { #endif /* * @parameter { function<void>(FGTL_Event*) { update } * uint16_t { fps } * } * This function for looping program * this using parameter function and * fps */ void FGTL_Loop(void(*update)(FGTL_Event*), uint16_t fps); #ifdef __cplusplus } #endif #endif /* End of FGTL_HEADER_H */
C
#include <stdio.h> #include <string.h> #include "distance.h" #include "pythagoras.h" #include "nearLine.h" #define StrLen 256 /* * range: * * This function does the actual work of figuring out whether a city * is within the specified range of a set of fronts. The main() function * is just a driver and reporter. * */ int range(double lat, double lon, double d, FILE *in) { float newLat, newLon, oldLat, oldLon; char line[StrLen], oldValid; /* Process the whole file */ while (!feof(in)) { oldValid = 'f'; /* Deal with one front at a time; they're not necessarily connected. */ while ((fgets(line, StrLen, in) != NULL) \ && (strcmp(line, "front\n"))) { /* Read the point. */ (void) sscanf(line, "%f %f", &newLat, &newLon); if (pythagoras(lat - newLat, lon - newLon) <= d) /* The endpoint is close enough; good enough. */ return Close; if (oldValid == 't') { /* Are the points distinct? */ if (pythagoras(newLat - oldLat, newLon - oldLon) > Delta) { /* Yes. Use them. */ if (nearLine(lat, lon, newLat, newLon, oldLat, oldLon) <= d) return Close; } /* No. Do nothing. */ } else { oldLat = newLat; oldLon = newLon; oldValid = 't'; } } } /* No errors, but no front in range. */ return Far; }
C
Name:Change G.L Joshi Subject: engineering #include<stdio.h> #include<conio.h> int main(){ int a; printf("Enter the number or value\n "); scanf("%d",&a); if (a%5==0&&a%11==0) { printf("The value is divisible by 5 and 11 that is %d",a); } else {printf("the value is not divisible",a); } getch (); return 0; }
C
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <strings.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #define MAXLINE2 4096 //size of bytes for the buffer #define LISTENQ 1024 //size of the listening queue of clients int listenfd, connfd,read_size; //the listen and accept file desciptors struct sockaddr_in servaddr; //the server address char buff[MAXLINE2]; //the buffer which reads and sends lines time_t ticks; //ticks variable int port; //server port number FILE *in; //will be used with popen extern FILE *popen(); //will be used with popen /* * This method checks the number of arguments when running * the server. It makes sure the number of arguments does * not exceed 2. An error will be thrown otherwise. */ void numArgs(int argc){ if (argc != 2){ perror("usage: a.out <PORTnumber>\n"); exit(1); } } /* * This method creates a socket on the server. This * is the socket that will be listened on and an error * will be thrown if there is a problem creating * this socket. If no error, the listenfd is returned. */ int createListenSocket(){ listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0){ perror("socket error\n"); exit(1); } return listenfd; } /* * This method initializes the characteristics of the * server and gives it the port number specified by the * user. */ void createServer(const char *portnum){ sscanf(portnum,"%d",&port); //converts portnum to int bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); //sets the port number here } /* * This method binds the port using the listen file * descriptor. If there is an error with this process * an error will be thrown. An error is thrown if that * port is being used for other purposes. */ void bindServer(int listenfd){ int bindID = bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); if (bindID < 0){ perror("bind error\n"); exit(1); } } /* * This method listend forever waiting for clients to connect * to this server. When a client is connected it is added * to the listen queue. An error is thrown otherwise. */ void listenServer(int listenfd){ int listenID = listen(listenfd, LISTENQ); //the listen queue is LISTENQ if (listenID < 0){ perror("listen error\n"); exit(1); } } /* * This method uses the accept system call which finds a diff * port on the server for the client to communicate with. * This is to allow other clients to communicate with the * server's port while the original client can still communicate * with the server. An error is thrown if a problem occurs. */ int acceptServer(int listenfd){ connfd = accept(listenfd, (struct sockaddr *) NULL, NULL); if (connfd < 0){ perror("accept error\n"); exit(1); } return connfd; } /* * This method is the main meat of this program. It has an * infinite while loop, that will continuously read input from * the client and execute those commands that were sent to it. * It does so by using the popen system call which basically * opens a file and inputs the execution into it which later * gets sent to a buffer. This buffer is then sent to the client * who prints the output onto the screen. */ void readWriteServer(int connfd, int listenfd){ while( (read_size = recv(connfd , buff , MAXLINE2 , 0)) > 0 ) { //makes it possible to put the buffer //into a file. popen executes the command //that the client gives to it. if (!(in = popen(buff, "r"))) { perror("Not able to read stream"); exit(1); } //this int value will be used to ensure that //that fgets doesnt get called twice when only is //supposed to get called once int x = 0; //if user enters nothing or for other cases like //that, the if else send a message called //"empty" back to the client if(fgets(buff,sizeof(buff), in) == NULL){ if(strncmp(buff,"exit",4) == 0){ sprintf(buff,"exit"); write(connfd,buff,strlen(buff)); bzero(buff,MAXLINE2); x = 1; }else{ sprintf(buff,"empty"); write(connfd, buff, strlen(buff)); bzero(buff,MAXLINE2); x = 1; } }else{ printf("%s", buff); write(connfd , buff , strlen(buff)); bzero(buff,MAXLINE2); } //this while loop continually reads from the "in" //and puts in the results of popen, line by line //into the buffer which gets sent back to the client while (fgets(buff, sizeof(buff), in) != NULL) { printf("%s", buff); write(connfd , buff , strlen(buff)); bzero(buff,MAXLINE2); } //this if statement sends a final message to the client //letting it know its done sending messages and allows the //client to type a new command if((fgets(buff,sizeof(buff), in) == NULL) && (x==0)){ bzero(buff,MAXLINE2); sprintf(buff,"empty"); write(connfd, buff, strlen(buff)); bzero(buff,MAXLINE2); } pclose(in); bzero(buff,MAXLINE2); //zeroes/resets the buffer } //this is for when the client is done sending //its messages to the server. The client disconnects. if(read_size == 0) { close(connfd); //closes the file descriptor returned by accept } else if(read_size < 0) { perror("recv failed on server\n"); } } /* * This method allows the connection to the server to happen * for the client with the accept system call. It then calls * the main meat of this program, readWriteServer which is * a method that is briefly explained above. There is a while * loop to ensure that when the client exits, a new connection * can be established with the server. */ void acceptReadWriteServer(int listenfd){ while(1){ int connfd = acceptServer(listenfd); readWriteServer(connfd, listenfd); //contains code for receiving and sending data } } /* * This is the class's main which gets executed when this * program is run. */ int main(int argc, char **argv) { numArgs(argc); int listenfd = createListenSocket(); //the file desriptor for the socket on server createServer(argv[1]); bindServer(listenfd); listenServer(listenfd); acceptReadWriteServer(listenfd); return 0; }
C
static inline void swap_uchar(unsigned char *b1, unsigned char *b2) { unsigned char t = *b1; *b1 = *b2; *b2 = t; } bool us_rc4_setup_s(us_rc4 o, unsigned char* key, size_t length) { bool res = 1; o->idx1 = 0; o->idx2 = 0; o->S = malloc(256); res = (o->S != NULL); if(res) { // first set all the S to the identity for(int i = 0; i < 256; i++) { o->S[i] = (unsigned char)i; } // now randomise this data based on the key unsigned char j = 0; for(int i = 0; i < 256; i++) { j = (unsigned char)(j + o->S[i] + key[i % length]); swap_uchar(&o->S[i], &o->S[j]); } } return res; } unsigned char us_rc4_crypt_s(us_rc4 o, unsigned char c) { unsigned char res = 0; o->idx1++; o->idx2 += o->S[o->idx1]; swap_uchar(&o->S[o->idx1], &o->S[o->idx2]); res = (c ^ ((unsigned char)(o->S[o->idx1] + o->S[o->idx2]))); return res; } unsigned char *us_rc4_crypt_string_s(us_rc4 o, unsigned char* s, size_t length) { unsigned char *res = malloc(length); if(o->S == NULL || res == NULL) { res = NULL; } else { for(int i = 0; i < length; i++) { o->idx1++; o->idx2 += o->S[o->idx1]; swap_uchar(&o->S[o->idx1], &o->S[o->idx2]); res[i] = (s[i] ^ ((unsigned char)(o->S[o->idx1] + o->S[o->idx2]))); } } return res; }
C
#include "I2C.h" #include "io430.h" //Inicia I2C en USCI, falta pulir, ideal seria usar vectores de interrupción //Basado en ejemplo de TI void Init_I2C_USCI(unsigned char addr) { P1SEL |= BIT6 + BIT7; //Asigna la funcion de I2C a los pines SCL > P1.6, SDA > 1.7 Pag 49 msp430g2553 datasheet P1SEL2 |= BIT6 + BIT7; //Asigna la funcion de I2C a los pines SCL > P1.6, SDA > 1.7 UCB0CTL1 |= UCSWRST; // Detiene USCI UCB0CTL0 = UCMST+UCMODE_3+UCSYNC; // Modo maestro sincrono UCB0CTL1 = UCSSEL_2+UCSWRST; // Usa SMCLK 2Mhz en este caso y mantiene detenido el modulo UCB0BR0 = 20; // Preescaler para velocidad de SCL SMCLK/100kHz >> 2Mhz/100Khz = ~20 UCB0BR1 = 0; UCB0I2CSA = addr; // Direccion del esclavo MPU6050 en este caso UCB0CTL1 &= ~UCSWRST; // Inicia USCI __bis_SR_register(GIE); // Habilita interrupciones } //Establece la dirección del dispositivo a comunicar void Set_Address(unsigned char addr) { UCB0CTL1 |= UCSWRST; //Detiene USCI UCB0I2CSA = addr; // Guarda Direccion UCB0CTL1 &= ~UCSWRST; // Inicia USCI } //Lee un byte int ByteRead_I2C_USCI(unsigned char address) { while (UCB0CTL1 & UCTXSTP); //Si se esta ocupado espera hasta que termine ( In master receiver mode the STOP condition is preceded by a NACK. UCTXSTP is automatically cleared after STOP is generated.) UCB0CTL1 |= UCTR + UCTXSTT; //Modo transmision y envia condicion de inicio y direccion de esclavo ( In master receiver mode a repeated START condition is preceded by a NACK. UCTXSTT is automatically cleared after START condition andaddress information is transmitted.) while (!(IFG2&UCB0TXIFG)); //Espera a que termine UCB0TXBUF = address; //Envía la dirección del registro a leer while (!(IFG2&UCB0TXIFG)); //Espera a que termine UCB0CTL1 &= ~UCTR; // Cambia a modo recepción UCB0CTL1 |= UCTXSTT; // Envia condicion de inicio IFG2 &= ~UCB0TXIFG; // Limpia bandera de interrupcion while (UCB0CTL1 & UCTXSTT); //Espera a STT UCB0CTL1 |= UCTXSTP; //Envia condicion de stop return UCB0RXBUF; //Devuelve el valor del buffer (recepcion) } unsigned char ByteWrite_I2C_USCI(unsigned char address, unsigned char data) { while (UCB0CTL1 & UCTXSTP); // Si esta ocupado espera UCB0CTL1 |= UCTR + UCTXSTT; // Modo transmision y envia condicion de inicio y direccion de esclavo while (!(IFG2&UCB0TXIFG)); //Espera a que termine UCB0TXBUF = address; //Envía dirección de registro while (!(IFG2&UCB0TXIFG)); // Espera a que termine transmision de direccion UCB0TXBUF = data; // Envía byte a escribir while (!(IFG2&UCB0TXIFG)); // Espera a que termine transmision de datos UCB0CTL1 |= UCTXSTP; // Envía condicion de stop IFG2 &= ~UCB0TXIFG; // Limpia bandera de interrupcion return 0; }
C
#ifndef __RAYTRACER_H #define __RAYTRACER_H #include "vector.h" // color struct, RGB typedef struct color { float r; float g; float b; } COLOR; // define different shader model enums enum shader_model { LAMBERT_MODEL, PHONG_MODEL }; // define different geometry types enum geometry_type { SPHERE_GEO, PLANE_GEO }; // define different light types enum light_type { AREA_LIGHT, POINT_LIGHT }; // define a shader typedef struct shader { shader_model model; // what model COLOR diffuse; // diffuse color COLOR specular; // specular color (PHONG only) float power; // shininess (PHONG only) } SHADER; // define a triangle typedef struct triangle { VECTOR a; // corners VECTOR b; VECTOR c; VECTOR normal; // normal direction } TRIANGLE; // define geometry typedef struct geometry { geometry_type geo; // what type SHADER shader; // what shader does it use VECTOR pos; // (sphere) position float rad; // (sphere) radius float tri_count; // how many triangles TRIANGLE *triangles; // list of triangles } GEOMETRY; // define light typedef struct light { light_type type; // type VECTOR pos; // position COLOR intensity; // color } LIGHT; // orthogonal view space typedef struct view { VECTOR normal; // view normal float dist; // camera to plane float width; float height; float left; float right; float bottom; float top; float near; float far; } VIEW; // define camera typedef struct camera { VECTOR pos; // position of camera VECTOR forward; // forward direction VECTOR up; // up direction VIEW v; // a camera view space } CAMERA; #endif