language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* di.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rreedy <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/14 21:30:20 by rreedy #+# #+# */ /* Updated: 2018/12/14 21:40:31 by rreedy ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static void zeros_di(t_sub *sub) { int i; i = (FLAGS & 0x2 && PREC == -1) ? 1 : 0; while (S && S[i] == ' ') S[i++] = '0'; if (i && (S[i] == '-' || S[i] == '+')) { S[0] = S[i]; S[i] = '0'; } } static void precision_di(t_sub *sub) { if (S[0] != '-' && (size_t)PREC > ft_strlen(S)) S = ft_shift(&S, PREC - ft_strlen(S), PREC); else if (S[0] == '-' && (size_t)PREC >= ft_strlen(S)) S = ft_shift(&S, PREC - ft_strlen(S) + 1, PREC + 1); zeros_di(sub); } static void flags_di(t_sub *sub) { S = ft_shift(&S, 1, ft_strlen(S) + 1); if (FLAGS & 0x4) S[0] = '+'; } static void width_di(t_sub *sub) { if ((size_t)JUST > (size_t)WIDTH - LEN) JUST = WIDTH - LEN; if (!(FLAGS & 0x30)) JUST = WIDTH - JUST - LEN; else if ((FLAGS & 0x30) == 0x30) JUST = (WIDTH - LEN) / 2; else if (FLAGS & 0x20) JUST = ((WIDTH - LEN) / 2) + (((WIDTH - LEN) % 2) ? 1 : 0); S = ft_shift(&S, JUST, WIDTH); LEN = ft_strlen(S); } char *crop_di(t_sub *sub) { if (ft_strequ(S, "0") && FLAGS & 0x4) FLAGS = FLAGS ^ 0x6; if (PREC >= 0) precision_di(sub); if (FLAGS & 0x6 && S[0] != '-') flags_di(sub); LEN = ft_strlen(S); if ((size_t)WIDTH > LEN) width_di(sub); if (FLAGS & 0x8 && !(FLAGS & 0x10) && PREC == -1) zeros_di(sub); return (S); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <assert.h> #include<fcntl.h> #include<errno.h> #include<wait.h> #include<sys/select.h> #include<sys/time.h> //select的使用 int main() { int fd = 0;//stdin键盘输入 while(1) { fd_set fdset;//声明文件描述符集合 FD_ZERO(&fdset);//清空 FD_SET(fd, &fdset);//在文件描述符集合中增加一个新的文件描述符 struct timeval tv = {5, 0}; int n = select(fd+1, &fdset,NULL,NULL,&tv); if (n == -1) break; else if(n == 0) { printf("time out\n"); } else { char buff[128] = {0}; if( FD_ISSET(fd,&fdset)) { read(fd,buff,127); printf("buff = %s\n",buff); } } } }
C
#include <stdio.h> int num[1000500]={0},y[1000500]; int main(void){ int n,m,dx,dy,a,b,temp; long long int i; scanf("%d%d%d%d",&n,&m,&dx,&dy); y[0] = 0; for(i=0;i<n;i++){ y[(i*dx) % n] = (i*dy) % n; } for(i=0;i<m;i++){ scanf("%d%d",&a,&b); temp = b -y[a]>=0?b-y[a]:b+n-y[a]; num[temp]++; } temp = 0; for(i=1;i<n;i++){ temp = num[temp]>num[i]?temp:i;} printf("0 %d\n",temp); //getchar(); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> //Global variables //No. of items int n = 0; //Capacity of Knapsack int capacity = 0; int *profitArray, *weightArray, *bestset, *include; float maxprofit = 0; int num = 0; int newN; //Function declarations void readFile(char *filePath); void Knapsack(); void knapsack(int i, float profit, int weight); int promising(int i, int weight, float profit); float kwf4(int i, int weight, float profit, int weightArray[], int profitArray[], int C, int n); void sort(); void freeMemory(); int main(int argc, char *argv[]) { //Check if the file is passed as an argument if(argc != 2) { printf("Invalid number of arguments\n"); exit(1); } //Reading the contents of file readFile(argv[1]); //Sorting the items in non-ascending order of profit/weight ratio sort(); //Knapsack function call Knapsack(); //Freeing the memory freeMemory(); printf("\n"); return 0; } //Function for reading the file void readFile(char *filePath) { char str[100]; char *token; //File pointer FILE *fp = NULL; fp = fopen(filePath, "r"); //Check if the file is open if(fp != NULL) { //Get the number of items fgets(str, 100, fp); n = atoi(str); newN = n + 1; printf("Number of items %d", n); //Get the capacity of the knapsack fgets(str, 100, fp); capacity = atoi(str); printf("\nKnapsack capacity %d", capacity); //Allocate the profit, weight, bestset and include arrays on heap profitArray = malloc(sizeof(int) * newN); weightArray = malloc(sizeof(int) * newN); bestset = malloc(sizeof(int) * newN); include = malloc(sizeof(int) * newN); //Get the profits fgets(str, 100, fp); //Process the profits for(int i = 0; i < n; i++) { if(i == 0) { token = strtok(str, ","); profitArray[i + 1] = atoi(token); } else { token = strtok(NULL, ","); profitArray[i + 1] = atoi(token); } } //Get the weights fgets(str, 100, fp); //Process the weights for(int i = 0; i < n; i++) { if(i == 0) { token = strtok(str, ","); weightArray[i + 1] = atoi(token); } else { token = strtok(NULL, ","); weightArray[i + 1] = atoi(token); } } //Init to 0 profitArray[0] = 0; weightArray[0] = 0; for(int i = 0; i < newN; i++) { bestset[0] = 0; } include[0] = 0; } else { printf("Error: Cannot open file !\n"); exit(1); } //Closing the file pointer if(fp != NULL) fclose(fp); } //Knapsack function void Knapsack() { int num = 0; maxprofit = 0; knapsack(0, 0, 0); //Printing the final solution int wt = 0, pt = 0; printf("\n\nSelected items,"); printf("\nProfit\tWeight"); printf("\n================="); for (int i = 1; i <= n; i++) { if(bestset[i] == 1) { printf("\n%d\t%d ", profitArray[i], weightArray[i]); wt += weightArray[i]; pt += profitArray[i]; } } printf("\nMaximum profit %d", pt); printf("\nMaximum weight %d", wt); } //Recursive function for including items in the Knapsack void knapsack(int i, float profit, int weight) { if(weight <= capacity && profit > maxprofit) { //Save the solution maxprofit = profit; num = i; for(int j = 0; j <= n; j++) { bestset[j] = include[j]; } } if(promising(i, weight, profit)) { include[i + 1] = 1; knapsack(i + 1, profit + (profitArray[i + 1]), weight + (weightArray[i + 1])); include[i + 1] = 0; knapsack(i + 1, profit, weight); } } //Promising function int promising(int i, int weight, float profit) { if(weight >= capacity) return 0; int bound = kwf4(i+1, weight, profit, weightArray, profitArray, capacity, n); return bound > maxprofit; } //Function for calculating the upper bound float kwf4(int i, int weight, float profit, int weightArray[], int profitArray[], int C, int n) { float bound = profit; float *x = malloc(sizeof(float) * newN); for(int j = 0; j < n; j++) x[j] = 0; while(weight < C && i <= n) { if(weight + weightArray[i] <= C) { x[i] = 1; weight = weight + weightArray[i]; bound = bound + profitArray[i]; } else { x[i] = (C - weight) / weightArray[i]; weight = C; bound = bound + profitArray[i] * x[i]; } i++; } //Free memory free(x); return bound; } //Function for sorting the items in non-ascending order of profit/weight ratio using bubble sort void sort() { float *ratio = malloc(sizeof(float) * newN); for(int i = 0; i < newN; i++) { ratio[i] = (float) profitArray[i] / weightArray[i]; } for(int j = 0; j < newN; j++) { for(int i = 1; i < newN; i++) { if(ratio[i - 1] < ratio[i]) { int temp = ratio[i - 1]; ratio[i - 1] = ratio[i]; ratio[i] = temp; temp = profitArray[i - 1]; profitArray[i - 1] = profitArray[i]; profitArray[i] = temp; temp = weightArray[i - 1]; weightArray[i - 1] = weightArray[i]; weightArray[i] = temp; } } } //Free the memory free(ratio); } //Function for freeing the dynamically allocated memory void freeMemory() { free(profitArray); free(weightArray); free(bestset); free(include); }
C
#include<stdio.h> void main() { int i,j; i=8,j=10; printf("%d,%d,%d%,%d\n",i,j,++i,j++); }
C
#include <stdio.h> #include <pthread.h> #include <stdint.h> #include <unistd.h> #include <stdlib.h> #define PHILOSOPHERS 5 #define DAYS 10000 static const char* names[] = { "Enryo", "Socrates", "Platon", "Aristoteles", "Kant" }; int fork_status[PHILOSOPHERS]= {0, 0, 0, 0, 0}; // 0: available, 1: taken pthread_t philosophers[PHILOSOPHERS]; pthread_mutex_t fork_mutex; pthread_cond_t cond; // Condition that at least 2 forks are available (which means the statement "at least 4 forks are taken" is wrong) static void eat(int phil, int fork1, int fork2) { printf("%s: \"Yummy!\"\n", names[phil]); } int number_of_taken_forks(int *fork_status){ int taken= 0; for (int i= 0; i < 5; i++){ if (fork_status[i]) taken++; } return taken; } void* philosopher_thread(void* arg) { int phil = (int)(intptr_t)arg; unsigned int r = (phil << 16) + time(NULL); int left = phil; int right = (phil+1) % PHILOSOPHERS; int i; usleep(rand_r(&r) % 1000); for (i = 0; i < DAYS; i++) { /* Think for a while */ printf("Day: %d\n", i); usleep(rand_r(&r) % 100); // Condition handling while(number_of_taken_forks(fork_status) >= 4){ pthread_cond_wait(&cond, &fork_mutex); } /* Staring to eat */ pthread_mutex_lock(&fork_mutex); if (fork_status[left] == 0){ fork_status[left]= 1; printf("%s picked up fork on the left\n", names[phil]); if (fork_status[right] == 0){ fork_status[left]= 1; printf("%s picked up fork on the right\n", names[phil]); eat(phil, left, right); fork_status[right]= 0; printf("%s returned fork on the right\n", names[phil]); } fork_status[left]= 0; printf("%s returned fork on the left\n", names[phil]); pthread_cond_broadcast(&cond); } pthread_mutex_unlock(&fork_mutex); } return NULL; } int main() { int er, i; void* ret; for (i = 0; i < PHILOSOPHERS; i++) { er = pthread_mutex_init(&fork_mutex, NULL); if (er != 0) goto error; } er = pthread_cond_init(&cond, NULL); if (er != 0) goto error; for (i = 0; i < PHILOSOPHERS; i++) { er = pthread_create(&philosophers[i], NULL, philosopher_thread, (void*)(intptr_t)i); if (er != 0) goto error; } for (i = 0; i < PHILOSOPHERS; i++) { pthread_join(philosophers[i], &ret); } printf("finished\n"); return 0; error: fprintf(stderr, "ERROR\n"); return -1; }
C
/* comms.c * * Author: Michael Bossner * * comms.c contains functions related to communication */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "comms.h" #include "lib.h" /////////////////////////////////// Defines /////////////////////////////////// #define ZERO 48 #define NINE 57 #define SEVEN 55 #define FLAGGED 1 #define BASE 10 ////////////////////////////////// Functions ////////////////////////////////// char* rec_message(FILE* stream, int* streamEnd) { int next; int messageSize = 0; char* message = malloc(sizeof(char) * 1); *streamEnd = 0; FOREVER { next = fgetc(stream); switch (next) { case EOF: if (messageSize != 0) { // there is a message but EOF was found *streamEnd = FLAGGED; message[messageSize] = '\0'; return message; } else { free(message); return NULL; } case '\n': message[messageSize] = '\0'; return message; default: message = realloc(message, sizeof(char) * messageSize + 2); message[messageSize] = next; messageSize++; } } } bool is_valid_purchase(long* tokens, char* mesIndex, int* boardIndex) { if (mesIndex[0] < ZERO || mesIndex[0] > SEVEN || mesIndex[1] != ':') { return false; } *boardIndex = (mesIndex[0] - ZERO); mesIndex = &mesIndex[2]; // also checks wild unlike is_valid_take() for (int i = 0; i <= MAX_TOKEN_COLOUR; i++) { // for each colour if (mesIndex[0] < ZERO || mesIndex[0] > NINE) { // not a number return false; } else { tokens[i] = strtol(&mesIndex[0], &mesIndex, BASE); } if (((mesIndex[0] != ',') && (i < MAX_TOKEN_COLOUR)) || ((mesIndex[0] != '\0') && (i == MAX_TOKEN_COLOUR))) { return false; } else if (i < MAX_TOKEN_COLOUR) { // set index to skip to next num mesIndex = &mesIndex[1]; } } return true; } bool is_valid_take(long* tokens, char* mesIndex) { for (int i = 0; i < MAX_TOKEN_COLOUR; i++) { if (mesIndex[0] < ZERO || mesIndex[0] > NINE) { return false; } else { tokens[i] = strtol(mesIndex, &mesIndex, BASE); } if (((mesIndex[0] != ',') && (i < MAX_TOKEN_COLOUR - 1)) || ((mesIndex[0] != '\0') && (i == (MAX_TOKEN_COLOUR - 1)))) { return false; } else if (i < (MAX_TOKEN_COLOUR - 1)) { mesIndex = &mesIndex[1]; } } return true; } void print_winners(GameState* state, char* message, FILE* stream) { long highest = 0; int count = 0; fprintf(stream, "%s", message); fflush(stream); for (int i = 0; i < state->player.count; i++) { // checks the highest score if (highest < state->player.scoreCard[i]) { highest = state->player.scoreCard[i]; count = 1; } else if (state->player.scoreCard[i] == highest) { // more than 1 count++; } } for (int i = 0; i < state->player.count; i++) { // prints all winners if (state->player.scoreCard[i] == highest) { if (count > 1) { fprintf(stream, "%c,", player_int_to_char(i)); fflush(stream); count--; } else { fprintf(stream, "%c\n", player_int_to_char(i)); fflush(stream); } } } }
C
#include "main.h" char* load_path(char* path) { FILE *fp; if ((fp = fopen(*path, "r")) != NULL) { fprintf(stderr, "file open error!\n"); return 1; } char line[2][128]; int cnt = 0; while (memset(line[cnt], 0, sizeof(line[cnt])), fgets(line, sizeof(line[cnt]), fp) != EOF) { line[cnt++][strlen(line[cnt]) - 1] = '\0'; } return line; fclose(fp); }
C
#ifndef __TEMPERATURE_H #define __TEMPERATURE_H /* Definitions and Macros */ // in degrees celcius #define MIN_TEMP 10 // req 28: "The default minimum temperature shall be 10C." #define MAX_TEMP 100 // req 27: "The default maximum temperature shall be 100C." #define ROOM_TEMP 20 #define DEFAULT_MIN_TARGET_TEMP 70 #define DEFAULT_MAX_TARGET_TEMP 80 /* Type, enum, and struct definitions */ typedef enum temp_state_e { TEMP_CRIT_LOW = 0, TEMP_LOW, TEMP_IN_TARGET, TEMP_HIGH, TEMP_CRIT_HIGH, TEMP_ERROR } temp_state_t; typedef struct temp_sensor_s { temp_state_t previous_state; temp_state_t current_state; int temp; } temp_sensor_t; /* Function prototyes */ void TEMP_Init(void); void TEMP_TaskInit(void); void TEMP_SetMin(int new_min_temp); void TEMP_SetMax(int new_max_temp); /* Test Cases */ void TEMP_TestCritLowTemp(void); void TEMP_TestLowTemp(void); void TEMP_TestHighTemp(void); void TEMP_TestCritHighTemp(void); #endif
C
#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { int c; int oa = 0; int ob = 0; int oc = 0; while((c = getopt(argc, argv, "a:bc")) != -1) { switch(c) { case 'a': oa = 1; break; case 'b': ob = 1; break; case 'c': oc = 1; break; case '?': // printf("Unknown option: %c\n", optopt); // if (optopt == 'a') { // printf("Option -a needs more arguments\n"); // } break; default: printf("Unknown option!\n"); break; } } printf("oa: %d, ob: %d, oc: %d\n", oa, ob, oc); return 0; }
C
/** 1 byte 00 : unk : free 01 : 64b : linked mem 02...... 07 : 4kb : linked mem User Data : 8b : 3b size, 4b Ref to user data User Data Int : 8b : 7b int User Data TinyUTF8: 8b : 7b string Large Dict : 8b : 1b nparents, 2b nslots, 4b Ref to ext || parents guaranteed to be in the first block Large List : 8b : 1b nparents, 2b nitems, 4b Ref to ext || parents in first block, max 64k array elements Small Dict : 128b: 1b[2B nparents, 6B nslots], 2b??, 12b parents, 112b slots (max 14) Small List : 64b: 1b[2B nparents, 6B nitems], 2b??, 60b els (max 15) 0: free objects 1: omem interal 2: generic small object 2: generic medium object 3: generic large object 128~: double */ #ifndef OBJ_C #define OBJ_C #define TYPE_FREE 0 #define TYPE_OMEM 1 #define TYPE_LIST_IMBAL 2 #define TYPE_LIST_BAL 3 #define TYPE_LIST_END 4 #define TYPE_REDIRECT 5 #include "omem.c" #include "intstr.c" void obj_init(uint32_t npages); void obj_fini(void); void obj_new(ORef parent); ORef obj_get_utf8(ORef obj, const char *key_utf8); ORef obj_set_utf8(ORef obj, const char *key_utf8, ORef val); ORef obj_get_idx(ORef obj, int idx); ORef obj_set_idx(ORef obj, int idx, ORef val); ORef obj_ins_idx(ORef obj, int idx, ORef val); ORef obj_get_istr(ORef obj, IStr key_istr); ORef obj_set_istr(ORef obj, IStr key_istr, ORef val); void *obj_get_data(ORef obj); void obj_set_data(ORef obj, void *data_ptr); uint32_t obj_get_length(ORef obj); #if __INCLUDE_LEVEL__ == 0 #include "logging.c" void obj_init(uint32_t npages) { omem_init(npages); is_init(); // Setup default set of objects } void obj_fini(void) { is_fini(); omem_fini(); } #endif #endif
C
/* Chapter 3 programming projects */ #include <stdio.h> int main (void) { //Question 1. int day, month, year; printf("Enter a date (dd/mm/yyyy): "); scanf("%d/%d/%d", &day, &month, &year); printf("You entered the date %4.4d%2.2d%2.2d\n", year, month, day); //Question 2. int in; float up; printf("Enter item number: "); scanf("%d", &in); printf("Enter unit price: "); scanf("%f", &up); printf("Enter a date (dd/mm/yyyy): "); scanf("%d/%d/%d", &day, &month, &year); printf("Item\t\tUnit\t\tPurchase\n\t\tPrice\t\tDate\n%d\t\t$%7.2f\t%2.2d/%2.2d/%4.4d\n", in, up, day, month, year); //Question 3. int gsiPre, grpId, pubCode, itemNum, checkDig; printf("Enter ISBN: "); scanf("%d - %d - %d - %d - %d", &gsiPre, &grpId, &pubCode, &itemNum, &checkDig); printf("GSI Prefix: %d\nGroup Identifier: %d\nPublisher Code: %d\nItem Number: %d\nCheck digit: %d\n", gsiPre, grpId, pubCode, itemNum, checkDig); //Question 4. int fdig, sdig, tdig; printf("Enter phone number [(xxx) xxx - xxxx]: "); scanf("(%d) %d - %d", &fdig, &sdig, &tdig); printf("%d.%d.%d\n", fdig, sdig, tdig); //Question 5. int one, two, three, four, five, six, seven, eight, nine; printf("Enter the numbers from 1 to 9 in any order: "); scanf("%d%d%d%d%d%d%d%d%d", &one, &two, &three, &four, &five, &six, &seven, &eight, &nine); printf("%d %d %d\n", one, two, three); printf("%d %d %d\n", four, five, six); printf("%d %d %d\n", seven, eight, nine); printf("Sum of rows: %d %d %d\n", (one + two + three), (four + five + six), (seven + eight + nine)); printf("Sum of columns: %d %d %d\n", (one + four + seven), (two + five + eight), (three + six + nine)); printf("Sum of diagnals: %d %d\n", (one + five + nine), (three + five + seven)); //Question 6. int num1, denom1, num2, denom2; printf("Enter equation: "); scanf("%d/%d + %d/%d", &num1, &denom1, &num2, &denom2); printf("The sum is %d/%d\n", (num1 * denom2 + num2 * denom1), (denom1 * denom2)); return 0; }
C
/******** Excercise on using math, if else prep. Found on page 53 of the Cheng book. PimentaDriverTest .c Jenna Pimenta C Programming *******/ #include <stdio.h> #include <math.h> //for macro M_PI int main() { double r; (4.0/3)*3.14*r*r*r; (9.0/5)* c + 32; (4.0/3)*3.14*r*r*r; (9.0/5)*c+32; return 0; }
C
#include <stdio.h> #include <string.h> /* copy at most n characters of string ct to s ; return s . Pad with '\0' characters if ct has fewer than n characters. */ char *strncpy2(char *s, char *ct, int n); char *strncpy2(char *s, char *ct, int n) { while (*s++ = *ct++ && n-- > 0) ; while (*ct++) *s++ = '\0'; } main() { char s[] = "abcd"; char ct[] = "efg"; int n = 2; printf("efcd ? %s\n", strncpy(s, ct, n)); char s2[] = "abcdef"; char ct2[] = "hi"; int n2 = 4; char *res = strncpy(s2, ct2, n2); printf("hi???? ? %s\n", res); /* while (*res) { printf("res: %d\n", res); ++res; } */ char s3[] = "test3abc"; char ct3[] = "hii"; int n3 = 2; char *res3 = strncpy(s3, ct3, n3); printf("hist3abc ? %s\n", res3); }
C
#include"../stacks.h" void coinpre(stack *s) { //infix to prefix printf("\n Enter the infix expression : "); scanf(" %s",aa); int len=strlen(aa); int c[30]; int j=0; int count=0; printf("\n Length of above expression is : %d \n",len); printf("\n The prefix expression is :\t"); for(i=len-1,p1=0; i>=0; i--) { b[p1]=aa[i]; p1++; } for(i=0; i<len; i++) { if(check(b[i])==0) c[j++]=b[i]; else if(b[i]==')') { pushp(s,')'); count+=2; } else { if(b[i]=='(') while(top_p(s)!=')') c[j++]=popp(s); else //meaning operator { while(prec(b[i])<=prec(top_p(s)) && !empty(s)) { xx=popp(s); c[j++]=xx; } pushp(s,b[i]); } } } while(!empty(s)) { xx=popp(s); c[j++]=xx; } if(count==2) p2=1; if(count==4) p2=2; if(count==6) p2=3; for(i=len-count-p2; i>=0; i--) { if(c[i]!=')' || c[i]!='(') printf("%c",c[i]); } printf("\n\n"); options_p(s); }
C
/* * File: SerialLED.c * Author: junmo * * Created on 2019/10/21, 14:07 */ #include<xc.h> #include"SerialLED_PIC18F25K22.h" void OUT_NONE(unsigned char LED_POWER) { OUT_CHECK(0); OUT_CHECK(0); OUT_CHECK(0); } void OUT_RED(unsigned char LED_POWER) { OUT_CHECK(LED_POWER); OUT_CHECK(0); OUT_CHECK(0); } void OUT_GREEN(unsigned char LED_POWER) { OUT_CHECK(0); OUT_CHECK(LED_POWER); OUT_CHECK(0); } void OUT_BLUE(unsigned char LED_POWER) { OUT_CHECK(0); OUT_CHECK(0); OUT_CHECK(LED_POWER); } void OUT_WHITE(unsigned char LED_POWER) { OUT_CHECK(LED_POWER>>1); OUT_CHECK(LED_POWER>>1); OUT_CHECK(LED_POWER>>1); } void OUT_YELLOW(unsigned char LED_POWER) { OUT_CHECK(LED_POWER>>1); OUT_CHECK(LED_POWER>>1); OUT_CHECK(0); } void OUT_ORANGE(unsigned char LED_POWER) { OUT_CHECK(LED_POWER); OUT_CHECK(LED_POWER>>1); OUT_CHECK(0); } void OUT_HIGH(void) { LEDOUT = 1; asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); LEDOUT = 0; asm("nop"); asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); } void OUT_LOW(void) { LEDOUT = 1; asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); LEDOUT = 0; asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); } void LED_RET(void) { LEDOUT = 0; for (int i = 0; i < 10000; i++) asm("nop"); } void OUT_LED_ARRAY(unsigned char LED_COLOR_ARRAY_2D[LED_ARRAY_X][LED_ARRAY_Y], unsigned char LED_POWER) { unsigned char LED_COLOR_ARRAY[LED_ARRAY_SIZE]; for(unsigned int j=0;j<LED_ARRAY_X;j++){ for(unsigned int i=0;i<LED_ARRAY_Y;i++){ LED_COLOR_ARRAY[j*LED_ARRAY_Y+i]=LED_COLOR_ARRAY_2D[j][i]; } } for (unsigned int i = 0; i < LED_ARRAY_SIZE; i++) { (*LED_COLOR[LED_COLOR_ARRAY[i]])(LED_POWER); } LED_RET(); } void OUT_CHECK(unsigned char LED_POWER) { for (int i = 0; i < 8; i++) { if ((LED_POWER & 0x80) == 0x80) {//ŏʃrbgHIGHȂ OUT_HIGH();//HIGHVOiM } else {//Ⴆ OUT_LOW();//LOWVOiM } LED_POWER <<= 1;//1bitVtg } }
C
/* * File: LED.h * Purpose: Routines for the LEDs * * Notes: * */ //Preprocessor Directives #ifndef LED_H #define LED_H /* Includes */ #include <stdint.h> //stdint.h is a header file in the C standard library introduced in the C99 standard library section 7.18 to allow programmers to write more portable code by providing a set of typedefs that specify exact-width integer types, together with the defined minimum and maximum allowable values for each type, using macros[1] . This header is particularly useful for embedded programming which often involves considerable manipulation of hardware specific I/O registers requiring integer data of fixed widths, specific locations and exact alignments /* Definitions */ /* Macros */ /* example // LED macros #define LED1_ON LED1_GPIO_PORT->BSRRL = LED1_GPIO_PIN #define LED1_OFF LED1_GPIO_PORT->BSRRH = LED1_GPIO_PIN #define LED2_ON LED2_GPIO_PORT->BSRRL = LED2_GPIO_PIN #define LED2_OFF LED2_GPIO_PORT->BSRRH = LED2_GPIO_PIN #define LED3_ON LED3_GPIO_PORT->BSRRL = LED3_GPIO_PIN #define LED3_OFF LED3_GPIO_PORT->BSRRH = LED3_GPIO_PIN #define LED4_ON LED4_GPIO_PORT->BSRRL = LED4_GPIO_PIN #define LED4_OFF LED4_GPIO_PORT->BSRRH = LED4_GPIO_PIN */ /* Public functions */ void LEDInit(void); /* Private functions */ /* Public variables */ /* Private variables */ /* Type Definitions */ /* Special type definitions */ #endif /* LED_H */
C
//Write a program to copy one binary tree to another binary tree #include<stdio.h> #include<stdlib.h> struct Node{ int num; struct Node *left; struct Node *right; }; struct Node *tree = NULL; struct Node *insert(struct Node *tree, int digit); void *exchange(struct Node *tree); struct Node *temp; int selection(); void main(){ struct Node *tree = NULL; int choice; int digit; do { choice = selection(); switch (choice) { case 1 : puts("Enter integer : To quit enter 0"); scanf("%d", &digit); while (digit != 0) { tree = insert(tree, digit); scanf("%d", &digit); } continue; case 2 : printf("%d\n", tree->num); exchange(tree); continue; case 3 : exit(0); } } while(choice != 3); } int selection(){ int selection; do { puts("1 : Insert a node"); puts("2 : Exchange subtrees"); puts("3 : End"); puts("Enter your choice: "); scanf("%d", &selection); if ((selection < 1) || (selection > 3)) { puts("Wrong choice : Try again"); getchar(); } } while((selection < 1) || (selection > 3)); return selection; } struct Node *insert(struct Node *tree, int digit){ if(tree == NULL){ tree = (struct Node *) malloc(sizeof (struct Node)); tree -> left = tree -> right = NULL; tree -> num = digit; }else if(digit < tree -> num){ tree -> left = insert(tree -> left, digit); }else if(digit > tree -> num){ tree -> right = insert(tree -> right, digit); }else if(digit == tree -> num){ puts("Duplicates nodes : program exited"); exit(0); } return tree; } void *exchange(struct Node *tree){ if((tree -> left -> num != 0) && (tree -> right -> num != 0)){ temp = tree -> left; tree -> left = tree -> right; tree -> right = temp; printf("%d\n", tree -> left -> num); printf("%d\n", tree -> right -> num); exchange(tree -> left); exchange(tree -> right); } }
C
#include <minix/drivers.h> #include <minix/com.h> #include "test4.h" static int proc_args(int argc, char *argv[]); static unsigned long parse_ulong(char *str, int base); static long parse_long(char *str, int base); static void print_usage(char *argv[]); // *argc = number of arguments written. // For example, in: service run <directory> [-args "<function> <arg1> <arg2>"] // <directory>, <function>, <arg1> and <arg2> are considered arguments // **argv = pointer to array of chars containing strings corresponding to arguments*/ int main(int argc, char **argv) { /* Initialize service */ sef_startup(); /* Enable IO-sensitive operations for ourselves */ sys_enable_iop(SELF); if ( argc == 1 ) { print_usage(argv); return 0; } else { proc_args(argc, argv); } return 0; } /*In each line specify the way the user shall write the functions and arguments*/ /*argv[0] is the string (%s) containing the directory*/ static void print_usage(char *argv[]) { printf("Usage: one of the following:\n" "\t service run %s -args \"packet <cnt>\" \n" "\t service run %s -args \"async <idle_time> \" \n" "\t service run %s -args \"config\" \n" "\t service run %s -args \"gesture <length> <tolerance>\" \n" ,argv[0], argv[0], argv[0]); } static int proc_args(int argc, char *argv[]) { /*Initialization of the arguments used in each function*/ unsigned short cnt, idle_time, tolerance; short length; /* check the function to test: if the first characters match, accept it */ if (strncmp(argv[1], "packet", strlen("packet")) == 0) { // argv[1] contains the function's name. strncmp returns 0 if argv[1] == "test_scan" if( argc != 3 ) { printf("Wrong number of arguments for test of test_packet() \n"); return 1; } if ((cnt = parse_ulong (argv[3], 10)) == USHRT_MAX) // parse_ulong (string, n) converts a string to an integer with base n. return 1; // If this exceeds USHRT_MAX , return error. printf ("test_packet(%hu)\n", cnt); // Asked function with parameter return test_packet(cnt); // Return function value } else if (strncmp(argv[1], "async", strlen("async")) == 0) { if( argc != 3 ) { printf("Wrong no of arguments for test of test_async() \n"); return 1; } if( (idle_time = parse_ulong(argv[2], 10)) == USHRT_MAX) // if n exceeds ULONG_MAX return 1; printf ("test_async()\n"); return test_async(idle_time); } else if (strncmp(argv[1], "config", strlen("config")) == 0) { if( argc != 2 ) { printf("Wrong no of arguments for test of test_config() \n"); return 1; } printf ("test_config()\n"); return test_config(); } else if (strncmp(argv[1], "gesture", strlen("gesture")) == 0) { if( argc != 4 ) { printf("Wrong no of arguments for test of test_gesture() \n"); return 1; } if( (length = parse_ulong(argv[2], 10)) == SHRT_MAX) // if n exceeds SHRT_MAX return 1; if( (tolerance = parse_ulong(argv[2], 10)) == USHRT_MAX) // if n exceeds SHRT_MAX return 1; printf ("test_gesture(%h, %hu)\n", length, tolerance); return test_gesture(length, tolerance); } else // if no function corresponds { printf ("Invalid function \n"); return 1; } } static unsigned long parse_ulong(char *str, int base) { char *endptr; unsigned long val; val = strtoul(str, &endptr, base); if ((errno == ERANGE && val == ULONG_MAX ) || (errno != 0 && val == 0)) { perror("strtol"); return ULONG_MAX; } if (endptr == str) { printf("mouse: parse_ulong: no digits were found in %s \n", str); return ULONG_MAX; } /* Successful conversion */ return val; } static long parse_long(char *str, int base) { char *endptr; unsigned long val; val = strtol(str, &endptr, base); if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { perror("strtol"); return LONG_MAX; } if (endptr == str) { printf("mouse: parse_long: no digits were found in %s \n", str); return LONG_MAX; } /* Successful conversion */ return val; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> //include "list.h" #include "list1.h" #include "sort.h" int main() {srand(time(NULL)); int *list; int a=1; list=(int*)malloc( 44 ); list[0]=0; max=10; char act[3]; while(1) { menu(); printf("\nChoose point: "); scanf("%s",act); if(act[0]=='1') { int n; char x[3]; printf("How much elements do you need?\n"); scanf("%d",&n); printf("Fill it automaticaly?[Y/n]\n"); scanf("%s",x); if(x[0]=='y' || x[0]=='Y') { list=create( n,1); } else list=create(n,0); printf("\nPrint list?[Y/n]\n"); scanf("%s",x); if(x[0]=='Y' || x[0]=='y') { printf("\n"); print(list); } } if(act[0]=='2') { /*if(a) { printf("You didn't create list, create it firstly.\n"); continue; }*/ int n; printf("How much elements do you want to add?\n"); scanf("%d",&n); printf("Make values random?[Y/n]\n"); char x[3]; int flag; scanf("%s",x); if(x[0]=='Y' || x[0]=='y') flag=1; else flag=0; for(int i=0;i<n;i++) { int val; printf("Choose position: "); int p; scanf("%d",&p); if(flag) val=rand()%25; else {printf("Enter value: "); scanf("%d",&val);} insert(list,val,p); printf("\nPrint list?[Y/n]\n"); scanf("%s",x); if(x[0]=='Y' || x[0]=='y') { printf("\n"); print(list); } } } if(act[0]=='3') { int res; char x[3]; printf("Enter position to delete: "); scanf("%d",&res); res=del(list,res); printf("\nPrint list?[Y/n]\n"); scanf("%s",x); if(x[0]=='Y' || x[0]=='y') { printf("\n"); print(list); } } if(act[0]=='4') { print(list); } if(act[0]=='5') { insert_sort(list); printf("\nPrint list?[Y/n]\n"); char x[3]; scanf("%s",x); if(x[0]=='Y' || x[0]=='y') { printf("\n"); print(list); } } if(act[0]=='6') { list=(int*)realloc(list,44); list[0]=0; } if(act[0]=='7') {printf("\nBye!\n");return 0;} a=0; } }
C
/* The 50-30-20 strategy is a simple way to budget, which involves spending 50% of after-tax income on needs, 30% after tax income on wants, and 20% after-tax income on savings or paying off debt. Given the after-tax income as ati, what you are supposed to do is to make a function that will return an object that shows how much a person needs to spend on needs, wants, and savings. Examples fiftyThirtyTwenty(10000) ➞ { "Needs": 5000, "Wants": 3000, "Savings": 2000 } fiftyThirtyTwenty(50000) ➞ { "Needs": 25000, "Wants": 15000, "Savings": 10000 } fiftyThirtyTwenty(13450) ➞ { "Needs": 6725, "Wants": 4035, "Savings": 2690 } Notes N/A */ #include <assert.h> #include <string.h> void strategy(unsigned m, unsigned r[3]) { r[0] = m * 0.5; r[1] = m * 0.3; r[2] = m * 0.2; } void test(unsigned m, unsigned r[3]) { unsigned p[3]; strategy(m, p); assert(memcmp(r, p, sizeof(p)) == 0); } int main(void) { test(10000, (unsigned[3]){5000, 3000, 2000}); test(50000, (unsigned[3]){25000, 15000, 10000}); test(13450, (unsigned[3]){6725, 4035, 2690}); test(27800, (unsigned[3]){13900, 8340, 5560}); test(19000, (unsigned[3]){9500, 5700, 3800}); test(17610, (unsigned[3]){8805, 5283, 3522}); test(25000, (unsigned[3]){12500, 7500, 5000}); test(100000, (unsigned[3]){50000, 30000, 20000}); test(347100, (unsigned[3]){173550, 104130, 69420}); return 0; }
C
/* getenv(3) * * Author: Terrence W. Holm Aug. 1988 */ #define NULL (char *) 0 extern char **environ; char *getenv( name ) char *name; { char **v; register char *n; register char *p; if ( environ == (char **) NULL || name == NULL ) return(NULL); for ( v = environ; *v != NULL; ++v ) { n = name; p = *v; while ( *n == *p && *n != '\0' ) ++n, ++p; if ( *n == '\0' && *p == '=' ) return( p + 1 ); } return(NULL); }
C
/* AUTHOR : SACHIN V B, SACHIN R DESCRIPTION: PROGRAM FOR SIGN UP BY TAKING USER_NAME, PASSWORD AND NAME. */ #include<unistd.h> #include<stdio.h> #include<string.h> #include<time.h> char* date() { time_t t; time(&t); return (ctime(&t)); } main(int argc,char **argv) { char *filename=NULL; char *log_file=NULL; int c; while((c=getopt(argc,argv,"f:l:"))!=-1) switch(c) { case 'f': filename=optarg; break; case 'l': log_file=optarg; break; default: printf("Please enter as -f <file_name> -l <log_file> followed by your argument\n"); return 1; } FILE *fp, *fp1; fp1=fopen(log_file, "w"); fp=fopen(filename, "r"); if(fp==NULL) { printf("File couldnt be opened. \nPlease make sure filename passed exists(login.txt/or any other file being passed. \n"); return; } if(fp1==NULL) { printf("Log file is not included. \n "); return; } char user_name[100], password[100], name[100]; int flag=0, flag1=0; while(flag==0) { printf("Enter user_name :"); scanf("%s", user_name); while(strlen(user_name)<3 || strlen(user_name)>21) { printf("User_name should have 3-20 characters\n"); printf("Enter user_name : "); scanf("%s", user_name); } while(1) { char str[100]; char user[100]; int i=0; if(feof(fp)) break; fscanf(fp, "%s", str); while(str[i]!=',' && str[i]!=EOF) { user[i]=str[i]; i++; } user[i]='\0'; i++; while(str[i]!='\0') i++; if(strcmp(user_name,user)==0) { printf("SELECTED USER NAME ALREADY EXISTS.\nPLEASE SELECT OTHER USER_NAME \n\n"); flag1=1; break; } } if(flag1==1) flag=0; else flag=1; flag1=0; fseek(fp, 0, SEEK_SET); } fclose(fp); fprintf(fp1, "%s Entered user_name :%s\n",date(), user_name ); flag=0; fp=fopen(filename, "a"); if(flag!=1) { printf("Enter password :"); scanf("%s",password); while(strlen(password)<3 || strlen(password)>16) { printf("Password should have 3-15 characters\n"); printf("Enter password :"); scanf("%s",password); } fprintf(fp1, "%s Entered password :%s\n",date(),password); } printf("Enter your Name :"); scanf("%s", name); if(strlen(name)<1) { printf("Enter your Name :"); scanf("%s", name); } fprintf(fp1, "%s Entered Name :%s\n",date(),name); fprintf(fp, "%s,%s,%s\n", user_name,password,name); printf("\nSUCESSFULLY SUBMITTED\n"); fprintf(fp1, "%sOutput displayed : SUCCESSFULLY SUBMITTED\n",date()); fclose(fp); fclose(fp1); }
C
/* * @lc app=leetcode.cn id=122 lang=c * * [122] 买卖股票的最佳时机 II */ // @lc code=start int maxProfit(int* prices, int pricesSize) { int i, buy, sell, sum; // 单调栈,反序递增减,当5出现时,弹出 如果是3 < 6直接弹出6-3, // 1 < 5 , 弹出5 - 1 = 4 // 7,4 // 左侧最小值 i = 0; sum = 0; while (i < pricesSize - 1) { // 找右边最小的点 while (i < pricesSize - 1 && prices[i+1] <= prices[i]) { i++; } buy = prices[i]; while (i < pricesSize -1 && prices[i+1] > prices[i]) { i++; } sell = prices[i]; sum += sell - buy; } return sum; } // @lc code=end
C
#include "framestack.h" #include "memoryinspect.h" Frame* newFrame(JavaClass* jc, method_info* method) { Frame* frame = (Frame*)malloc(sizeof(Frame)); if (frame) { attribute_info* codeAttribute = getAttributeByType(method->attributes, method->attributes_count, ATTR_Code); att_Code_info* code; if (codeAttribute) { code = (att_Code_info*)codeAttribute->info; frame->code = code->code; frame->code_length = code->code_length; if (code->max_locals > 0) frame->localVariables = (int32_t*)malloc(code->max_locals * sizeof(int32_t)); else frame->localVariables = NULL; #ifdef DEBUG frame->max_locals = code->max_locals; #endif // DEBUG } else { frame->code = NULL; frame->code_length = 0; frame->localVariables = NULL; } frame->operands = NULL; frame->jc = jc; frame->pc = 0; frame->fp_strict = (method->access_flags & ACC_STRICT) != 0; } return frame; } void freeFrame(Frame* frame) { if (frame->localVariables) free(frame->localVariables); if (frame->operands) freeOperandStack(&frame->operands); free(frame); } uint8_t pushFrame(FrameStack** fs, Frame* frame) { FrameStack* node = (FrameStack*)malloc(sizeof(FrameStack)); if (node) { node->frame = frame; node->next = *fs; *fs = node; } return fs != NULL; } uint8_t popFrame(FrameStack** fs, Frame* outPtr) { FrameStack* node = *fs; if (node) { if (outPtr) *outPtr = *node->frame; *fs = node->next; free(node); } return node != NULL; } void freeFrameStack(FrameStack** fs) { FrameStack* node = *fs; FrameStack* tmp; while (node) { tmp = node; node = node->next; freeFrame(tmp->frame); free(tmp); } *fs = NULL; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main() { int idade; setlocale(LC_ALL, "Portuguese"); printf("Digite a idade em anos do nadador: "); scanf("%d", &idade); if (idade < 5) printf("\nNadador no se encaixa em nenhuma categoria!\n"); else if (idade >= 5 && idade <= 7) printf("\nNadador se encaixa na categoria Infantil A!\n"); else if (idade >= 8 && idade <= 10) printf("\nNadador se encaixa na categoria Infantil B!\n"); else if (idade >= 11 && idade <= 13) printf("\nNadador se encaixa na categoria Juvenil A!\n"); else if (idade >= 14 && idade <= 17) printf("\nNadador se encaixa na categoria Juvenil B!\n"); else if (idade > 17) printf("\nNadador se encaixa na categoria Adulto!\n"); }
C
/* Convert letters to upper case */ #include "stdio.h" #include "string.h" #include "ctype.h" main() { char str[80]; int i; strcpy(str, "this is a test"); for(i=0; str[i]; i++) str[i] = toupper(str[i]); printf("%s", str); }
C
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *left, *right; }; struct node *create() { int x; struct node *newNode; newNode = (struct newnode *)malloc(sizeof(struct node)); printf("enter data(-1 for no node)\n"); scanf("%d", &x); if (x == -1) { return NULL; } newNode->data = x; printf("left child of %d\n", x); newNode->left = create(); printf("right child of %d\n", x); newNode->right = create(); return newNode; } void inorder(struct node *root) { if (root == 0) return; inorder(root->left); printf("%d\n", root->data); inorder(root->right); } void postorder(struct node *root) { if (root == 0) return; postorder(root->left); postorder(root->right); printf("%d\n", root->data); } void preorder(struct node *root) { if (root == 0) return; printf("%d\n", root->data); preorder(root->left); preorder(root->right); } int main() { struct node *root; root = create(); int d; printf("enter 1 for preorder\nEnter 2 for inorder\nEnter 3 for post order\n"); scanf("%d", &d); switch (d) { case 1: { printf("preorder:\n"); preorder(root); break; } case 2: { printf("inorder:\n"); inorder(root); break; } case 3: { printf("postorder:\n"); postorder(root); break; } } }
C
// Emanuel Fonseca // CSC 255 C AND UNIX #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> void Lowercase(char letter); void Uppercase(char letter); int TotalVowel(void); void number(int num); int Lowercounter=0; int Uppercounter=0; int vowelCounter=0; char new[20]; char new2[20]; int num; int main() { int i; char letter; char string[21]; printf("enter a string \n"); fgets(string,sizeof(string), stdin); for(i=0; i<21; i++){ int temp= (int)string[i]; if(temp>96 && temp<122) // if the character is lower case ascII table { Lowercase(string[i]); } if(temp<96 && temp>64) // if the character is upper case ascII table { Uppercase(string[i]); } if((string[i]=='a') || (string[i]=='A')|| (string[i]=='E')|| (string[i]=='e')|| (string[i]=='I')|| (string[i]=='i')|| (string[i]=='O')|| (string[i]=='o')|| (string[i]=='U')|| (string[i]=='u')) { TotalVowel(); } if(isdigit(string[i])) // if the character is a number { num=atoi(&string[i]); // change to number number(num); } } printf("Lowercase letters: \n"); printf(" %s \n",new); printf("Uppercase letters: \n"); printf(" %s \n",new2); puts("Number of Vowels: \n"); printf(" %d \n",vowelCounter); printf("Number * 12= %d \n", num); return 0; } void Lowercase(char letter) { char tmp=letter; new[Lowercounter]=tmp; ++Lowercounter; } void Uppercase(char letter) { char tmp2=letter; int number=Uppercounter; new2[Uppercounter]=tmp2; ++Uppercounter; } int TotalVowel(void) { vowelCounter++; return 0; } void number(int Num) { num *=12; }
C
extern int yylineno; #include <stdio.h> #include <stdlib.h> #include <string.h> #include "table.h" struct treenode { struct treenode* bro; struct treenode* chd; char* type; char* content; int lineno; int is_token; int _type; int dim; struct struct_node* st; }; struct treenode* new_node(char* type, int lineno, char* text){ struct treenode* node =(struct treenode*)malloc(sizeof(struct treenode)); node->type=type; node->chd=NULL; node->bro=NULL; node->lineno=lineno; int len=strlen(text); node->content=(char*) malloc(sizeof(char)*len); strcpy(node->content,text); node->is_token=1; return node; } struct treenode* new_tree(struct treenode* n[],int t_num,char* type){ struct treenode* node =(struct treenode*)malloc(sizeof(struct treenode)); node->chd=n[0]; node->bro=NULL; for (int i = 0; i < t_num-1; ++i){ n[i]->bro=n[i+1]; } node->type=type; node->lineno=yylineno; node->is_token=0; return node; } void tree_display(struct treenode* rt,int dep){ if(rt==NULL) return ; if(strcmp(rt->type,"null")!=0){ int i=0; for(i=0;i<dep;i++){ printf(" "); } if(strcmp(rt->type,"TYPE")==0){ printf("TYPE: %s\n",rt->content); } else if(strcmp(rt->type,"ID")==0){ printf("ID: %s\n",rt->content); } else if(strcmp(rt->type,"FLOAT")==0){ printf("FLOAT: %s\n",rt->content); } else if(strcmp(rt->type,"INT")==0){ printf("INT: %s\n", rt->content); } else if(rt->is_token){ printf("%s\n",rt->type); } else{ printf("%s (%d)\n",rt->type,rt->lineno); } } if(rt->chd!=NULL){ tree_display(rt->chd,dep+1); } if(rt->bro!=NULL){ tree_display(rt->bro,dep); } }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <conio.h> #include <time.h> #include <windows.h> #include <stdlib.h> /* һ⣺ö define 峣 ʲô 1#define ij Խе 2defineıʶ öپ Ŀöٻ оϢ ַ 1ӡַʹøʽ%s.Ҫע⣺%sӡʱ ԭ\0ֹͣӡ 2strlen(); ַij:ǰַַĸ ԭ\0ֹͣ */ #if 0 int main() { int year = 0; for(year = 1000; year <= 2019; year++) { //1ܱ4Dzܱ100 //2ܱ400 if((year%4 == 0 && year%100 != 0) || (year % 400 == 0) ) { printf("%d\n",year); } } return 0; } int main() { int i = 0; int j = 0; for(i = 1;i <= 9;i++) { for(j = 1;j <= i;j++) { printf("%d*%d=%d ",i,j,i*j); } printf("\n"); } return 0; } //8 int main() { int i = 0; int j = 0; int count = 0;// for(i = 101;i <= 200;i += 2)// i = 5 { for(j = 2;j <= sqrt((double)i);j++)// 2-4 { if(i % j == 0) { break;//ǰѭ } } if(j > sqrt((double)i)) // { count++; printf("%d\n",i); } } printf("count == %d\n",count); return 0; } // int main() { int i = 0; int j = 0; int count = 0;// for(i = 100;i <= 200;i++)// i = 5 { for(j = 2;j <= i/2;j++)// 2-4 { if(i % j == 0) { break;//ǰѭ } } if(j > i/2) // { count++; printf("%d\n",i); } } printf("count == %d\n",count); return 0; } //Գ int main() { int i = 0; int j = 0; int count = 0;// for(i = 100;i <= 200;i++)// i = 5 { for(j = 2;j < i;j++)// 2-4 { if(i % j == 0) { break;//ǰѭ } } if(j == i) // { count++; printf("%d\n",i); } } printf("count == %d\n",count); return 0; } //תַ int main() { //printf("%d\n",strlen("c:\e") ); //printf("%s\n","c:\est"); //char *str1 = "hello"; //printf("%d\n",strlen(str1));//ַȵ /*printf("%d\n", strlen("c:\est"));*/ //printf("%c\n",'\32'); //printf("%d\n",'\x123'); return 0; } // int main() { printf("Ǻ˧ÿɰ"); printf("\r"); printf("ĺ˧ÿɰ\n"); /*printf("%s\n","\"hello\""); printf("%s\n","c:\\code\\test.c"); printf("%s\n"," \' ");*/ return 0; } int main() { //ַ ˫һݣ //\0β ־ı־ char *str1 = "hello"; //str2 һַ char str2[] = "bit"; //ַ char str3[4] = {'a','b','c','d'}; char ch2 = 'g'; printf("%s\n",str1); printf("%s\n",str2); printf("%s\n",str3); return 0; } enum Day { MON = 1, THU = 4, WED //...... }; int main() { //int a = 10; //Day day = 1; //Day day2 = MON; /*printf("%d\n",MON); printf("%d\n",THU); printf("%d\n",WED);*/ //const int a = 10; //printf("%d\n",SIZE); return 0; } #endif
C
/*============================================================================= * Copyright (c) 2019, Eric Pernia <ericpernia@gmail.com> * All rights reserved. * License: bsd-3-clause (see LICENSE.txt) * Date: 2019/05/03 * Version: 1.0.0 *===========================================================================*/ /*=====[Inclusions of function dependencies]=================================*/ #include "sapi.h" /*=====[Definition macros of private constants]==============================*/ /*=====[Definitions of extern global variables]==============================*/ /*=====[Definitions of public global variables]==============================*/ /*=====[Definitions of private global variables]=============================*/ typedef enum{ UART_MODO_NORMAL, UART_MODO_ECHO, UART_MODO_ASCII, UART_MODO_CASE, }fsmUartState_t; fsmUartState_t fsmUartState; // Variable de estado void fsmUartInit( void ); void fsmUartUpdate( void ); /*=====[Main function, program entry point after power on or reset]==========*/ int main( void ) { // ----- Setup ----------------------------------- fsmUartInit(); // ----- Repeat for ever ------------------------- while( true ) { fsmUartUpdate(); } // YOU NEVER REACH HERE, because this program runs directly or on a // microcontroller and is not called by any Operating System, as in the // case of a PC program. return 0; } void fsmUartInit( void ){ boardInit(); fsmUartState = UART_MODO_NORMAL; uartWriteString( UART_USB, "UART_MODO_NORMAL\r\n" ); } void fsmUartUpdate( void ){ uint8_t data = 0; switch( fsmUartState ){ case UART_MODO_NORMAL: if( uartReadByte( UART_USB, &data ) ){ if( data == '3' ){ fsmUartState = UART_MODO_ECHO; uartWriteString( UART_USB, "UART_MODO_ECHO\r\n" ); } if( data == '4' ){ fsmUartState = UART_MODO_ASCII; uartWriteString( UART_USB, "UART_MODO_ASCII\r\n" ); } if( data == '5' ){ fsmUartState = UART_MODO_CASE; uartWriteString( UART_USB, "UART_MODO_CASE\r\n" ); } } break; case UART_MODO_ECHO: if( uartReadByte( UART_USB, &data ) ){ if( data == '3' ){ fsmUartState = UART_MODO_NORMAL; uartWriteString( UART_USB, "UART_MODO_NORMAL\r\n" ); } else { uartWriteByte( UART_USB, data ); } } break; case UART_MODO_ASCII: if( uartReadByte( UART_USB, &data ) ){ if( data == '4' ){ fsmUartState = UART_MODO_NORMAL; uartWriteString( UART_USB, "UART_MODO_NORMAL\r\n" ); } else { uartWriteString( UART_USB, intToStringGlobal(data) ); uartWriteString( UART_USB, "\r\n" ); } } break; case UART_MODO_CASE: if( uartReadByte( UART_USB, &data ) ){ if( data == '5' ){ fsmUartState = UART_MODO_NORMAL; uartWriteString( UART_USB, "UART_MODO_NORMAL\r\n" ); } else { if( (data >= 'a') && (data <= 'z') ){ // Convertir a mayuscula. 'a'-'A' == 32 uartWriteByte( UART_USB, data - ('a'-'A') ); } else{ if( (data >= 'A') && (data <= 'Z') ){ // Convertir a minuscula uartWriteByte( UART_USB, data + ('a'-'A') ); } else{ uartWriteByte( UART_USB, data ); } } } } // Recordar que: // 'a' != "a" // "a" == { 'a', '\0' } // "hola" == { 'h', 'o', 'l', 'a', 0 } break; default: fsmUartState = UART_MODO_NORMAL; uartWriteString( UART_USB, "Hubo un error, volviendo a MODO_NORMAL\r\n" ); break; } } /* #include <stdio.h> int main() { char vec[20]; scanf( "%s", vec ); printf( "%s\r\n", vec ); return 0; } */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "empleados.h" //datos del empleado struct empleadoE{ char nombre[30]; }; //almaceno datos empleado crearEmpleado(char nombre[]){ empleado e = malloc(sizeof(struct empleadoE)); strcpy(e->nombre,nombre); return e; } //cargo datos y los retorno a funcion crearEmpleado empleado crearEmpleadoPorTeclado(){ char nombre[30]; printf("INGRESE NOMBRE EMPLEADO :"); fflush(stdin); gets(nombre); return crearEmpleado(nombre); } //GET char * getNombreEmpleado(empleado e){ return e->nombre; } //SET void setNombreEmpleado(empleado e,char nombre[]){ strcpy(e->nombre,nombre); } //MOSTRAR void mostrarEmpleado(empleado e){ printf("NOMBRE EMPLEADO : %s\n",e->nombre); }
C
/* A fork of CanonicalArduinoRead by Chris Heydrick www.chrisheydrick.com */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <fcntl.h> #include <termios.h> #include <errno.h> #include <sys/ioctl.h> #define DEBUG 1 int setup(int * pfd, char * tty_dev, int baud){ struct termios toptions; /* open serial port */ *pfd = open(tty_dev, O_RDWR | O_NOCTTY); printf("%s opened as %i\n", tty_dev, *pfd); /* wait for the Arduino to reboot */ usleep(3500000); /* Choose the right baud rate identifier */ speed_t br; switch (baud) { case 9600: br = B9600; break; case 19200: br = B19200; break; case 38400: br = B38400; break; case 57600: br = B57600; break; case 115200: br = B115200; break; default: printf("Unknown baud rate\n"); printf("Using default of 9600\n"); br = B9600; break; } printf("Baud rate %d\n", baud); /* get current serial port settings */ tcgetattr(*pfd, &toptions); /* set baud rate both ways */ cfsetispeed(&toptions, br); cfsetospeed(&toptions, br); /* 8 bits, no parity, no stop bits */ toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; /* Canonical mode */ /* i.e. line buffering - chars will not come through until a \n is sent */ // toptions.c_lflag |= ICANON; /* Non-canonical mode */ toptions.c_lflag &= ~ICANON; /* commit the serial port settings */ tcsetattr(*pfd, TCSANOW, &toptions); } int available(const int fd){ int n = 0; ioctl(fd, FIONREAD, &n); return n; } int main(int argc, char *argv[]){ int fd, n, i; char buf[64] = "temp text"; if(argc < 3){ printf("Usage: %s <tty> <baudrate>\n", argv[0]); return 0; } setup(&fd, argv[1], atoi(argv[2])); //Send initial character to begin back-and-forth write(fd, "Z", 1); //The arduino will respond with the next character //of the alphabet (wrapped) while(1){ if(available(fd)){ n = read(fd, buf, 63); //read up to 63 chars buf[n] = 0; //set null terminator printf("%d bytes: %s\n", n, buf); write(fd, buf, 1); } } return 0; }
C
//program do ktorego podajemy z klawiatury ciagi znakow a on umieszcza je w tablicy dwuwymiarowej #include <stdio.h> #include <string.h> void dane(char tab[][12], int j) { printf("Wprowadz wyraz: "); scanf("%s", &tab[j]); } int main(void) { int i, j, min, char_int1, char_int2; char tmp; char tablica[5][12]; for(i=0;i<5;++i) { dane(tablica, i); } //od przodu for(i=0;i<5;++i) { printf("%s ", tablica[i]); } printf("\n"); //od tylu for(i=4;i>=0;--i) { printf("%s ", tablica[i]); } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> #include<ctype.h> #include<fcntl.h> #define MAXCHAR 10000 #define MAXCOMMANDS 1000 int tokenize_at_pipes(char input[MAXCHAR],char tokens[MAXCOMMANDS][MAXCOMMANDS]); int redirectionCheck(char* command); void execute(char **argv); void tokenize_at_spaces(char cmd[MAXCOMMANDS]); void redirection(char *input, int state); void call_pipe(char **in, int *pcount, int i); void strip(char *str){ int begin = 0,end = strlen(str) - 1; while (isspace((unsigned char) str[begin])) begin++; while ((end >= begin) && isspace((unsigned char) str[end])) end--; int i; for (i = begin; i <= end; i++) str[i - begin] = str[i]; str[i - begin] = '\0'; } int main(){ while(1){ char cwd[1024] = {}; getcwd(cwd,1024); printf("%s%s%s", "Shell@sanchit:~",cwd,"$ "); char input[MAXCHAR]={}; char commands[MAXCOMMANDS][MAXCOMMANDS]={{}}; fgets(input,MAXCHAR,stdin); strtok(input,"\n");strtok(input,"\n"); if (input[0] == '\n'|| input[0]==00){ continue; } if(strcmp(input,"exit")==0){ exit(0); } if(fork()==0){//In child for(int i = 0; i < MAXCOMMANDS; i++){ commands[i][0] = '\0'; } int pipe_count = tokenize_at_pipes(input,commands); if (pipe_count == 0){ int x = 0; if ((x = redirectionCheck(commands[0]))<0){ tokenize_at_spaces(commands[0]); } else{ redirection(commands[0],x); } } else{ for(int i = 0; i <= pipe_count; i++){ strip(commands[i]); } int counter = pipe_count+1; call_pipe(commands, &counter, 0); } } else{ wait(NULL); } } } int tokenize_at_pipes(char input[MAXCHAR],char tokens[MAXCOMMANDS][MAXCOMMANDS]){ char* ptr = strtok(input,"|"); int i = 0; while (ptr!=NULL){ strcpy(tokens[i], ptr); i++; ptr = strtok(NULL,"|"); } return (i-1); } void tokenize_at_spaces(char cmd[MAXCOMMANDS]){ if (cmd[0] == '\0') return; char *args[MAXCOMMANDS]; for (int i=0;i<MAXCOMMANDS;i++) args[i] = NULL; char *p = strtok(cmd," \t"); int i = 0; while (p != NULL){ args[i] = p; i++; p = strtok(NULL," \t"); } if (strcmp(args[0],"exit")==0){ exit(0); } else if(strcmp(args[0],"cd")==0){ chdir(args[1]); } else{ if (args[0] != NULL) execute(args); } } void execute(char **argv){ if (execvp(argv[0], argv) < 0) { // execute the command printf("ERROR: execution failed\n"); exit(1); } } //checks for redirection and returns the case int redirectionCheck(char *command){ char *out = strstr(command, ">"); char *in = strstr(command, "<"); char *append = strstr(command,">>"); if((append!=NULL) && (in!=NULL)){ return 5;//both append and input redirection }else if((out != NULL) && (in != NULL)){ return 4;//both input and output redirection }else if(append!=NULL){ return 3;//append redirection only }else if(out != NULL){ return 2;//output redirection only }else if(in != NULL){ return 1;//input redirection only }else{ return -1; } } void call_pipe(char **in, int *pcount, int i){ if(i == *pcount - 1){ //final process char cpy[MAXCOMMANDS]; strcpy(cpy, in[i]); char *args[MAXCOMMANDS]; for (int i=0;i<MAXCOMMANDS;i++) args[i] = NULL; char *p = strtok(cpy," \t"); int i = 0; while (p != NULL){ args[i] = p; i++; p = strtok(NULL," \t"); } int x; if((x = redirectionCheck(in[i])) < 0){ execute(args); } else{ redirection(in[i], x); } } if(i < *pcount){ int fd[2]; pid_t pid; char cpy[MAXCOMMANDS]; char *args[MAXCOMMANDS]; if(pipe(fd) < 0){ printf("pipe failed"); exit(1); } pid = fork(); if(pid < 0){ printf("fork failed"); exit(1); } if(pid != 0){ dup2(fd[1], 1); close(fd[0]); in[i+1] = NULL; strcpy(cpy,in[i]); for (int i=0;i<MAXCOMMANDS;i++) args[i] = NULL; char *p = strtok(cpy," \t"); int i = 0; while (p != NULL){ args[i] = p; i++; p = strtok(NULL," \t"); } int x; if((x = redirectionCheck(in[i])) < 0){ execute(args); } else{ redirection(in[i], x);} wait(NULL); } else{ if(i != *pcount-1){ dup2(fd[0], 0); } close(fd[1]); i++; call_pipe(in, pcount, i); } } } //implements redirection void redirection(char *input, int cond){ char cpy[MAXCOMMANDS],cmd[MAXCOMMANDS],filename[MAXCOMMANDS]; int fd; strcpy(cpy,input); char *temp; temp = strtok(cpy, " "); strcpy(cpy,input); if(cond == 1){ temp = strtok(cpy, "<"); temp[strlen(temp) - 1] = '\0'; strcpy(cmd, temp); temp = strtok(NULL, "\0"); strcpy(filename,temp); strip(filename); if((fd = open(filename, O_RDONLY, 0644)) < 0){ printf("Error opening file"); } dup2(fd, 0); close(fd); tokenize_at_spaces(cmd); } else if(cond == 2){ char*p = strstr(cpy,">"); temp = strtok(cpy,">"); temp[strlen(temp) - 1] = '\0'; strcpy(cmd,temp); temp = strtok(NULL, "\0"); strcpy(filename,temp); strip(filename); if((fd = creat(filename , 0644)) < 0){ printf("Error opening file"); } if((p-1)[0]=='1'){ dup2(fd,1); } else if((p-1)[0]=='2'){ dup2(fd,2); } else if((p+1)[0]=='&'){ dup2(2,1); close(2); } else{ dup2(fd,1); } close(fd); tokenize_at_spaces(cmd); } else if(cond == 3){ char *p = strstr(cpy,">>"); strcpy(p,p+1); temp = strtok(cpy,">"); temp[strlen(temp) - 1] = '\0'; strcpy(cmd,temp); temp = strtok(NULL, "\0"); strcpy(filename,temp); strip(filename); if((fd = open(input, O_WRONLY | O_APPEND)) < 0){ printf("Error opening file"); } dup2(fd, 1); close(fd); tokenize_at_spaces(cmd); } else if(cond == 4){ char filename2[MAXCOMMANDS]; int fd2; temp = strtok(cpy, "<"); temp[strlen(temp) - 1] = '\0'; strcpy(cmd,temp); temp = strtok(NULL, ">"); strcpy(filename,temp); filename[strlen(filename) - 1] = '\0'; temp[strlen(temp) - 1] = '\0'; temp = strtok(NULL, "\0"); strcpy(filename2,temp); strip(filename); strip(filename2); if((fd = open(filename, O_RDONLY, 0644)) < 0){ printf("Error opening file"); } if((fd2 = creat(filename2 , 0644)) < 0){ printf("Error opening file"); } dup2(fd, 0); close(fd); dup2(fd2, 1); close(fd2); tokenize_at_spaces(cmd); } else if (cond == 5){ char filename2[MAXCOMMANDS]; int fd2; temp = strtok(cpy, "<"); temp[strlen(temp) - 1] = '\0'; strcpy(cmd,temp); char *p = strstr(cpy,">>"); strcpy(p,p+1); temp = strtok(NULL, ">"); strcpy(filename,temp); filename[strlen(filename) - 1] = '\0'; temp[strlen(temp) - 1] = '\0'; temp = strtok(NULL, "\0"); strcpy(filename2,temp); strip(filename); strip(filename2); if((fd = open(filename, O_RDONLY, 0644)) < 0){ printf("Error opening file"); } if((fd2 = open(input, O_WRONLY | O_APPEND)) < 0){ printf("Error opening file"); } dup2(fd, 0); close(fd); dup2(fd2, 1); close(fd2); tokenize_at_spaces(cmd); } }
C
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define MSGSZ 256 /* * Declare the message structure. */ typedef struct msgbuf { long mtype; char mtext[MSGSZ]; }message_buf; int sendMessage(){ //printf("*********In Send Message*************\n"); int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ key = 1200; //key = ftok("dup.c", 'z'); //(void) fprintf(stderr, "\nmsgget: Calling msgget(%#lx,\%#o)\n",key, msgflg); if ((msqid = msgget(key, msgflg )) < 0) { perror("msgget"); return 1; } /* else (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); */ /* * We'll send message type 1 */ sbuf.mtype = getpid(); //(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); printf("\nInsert message to send to the server: "); scanf("%[^\n]",sbuf.mtext); //(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); buf_length = strlen(sbuf.mtext) + 1 ; /* * Send a message. */ if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { //printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd"); return 1; } else printf("Message: \"%s\" Sent\n", sbuf.mtext); if(!strcmp(sbuf.mtext,"KILL")){ return 2; } //cprintf("*********Exit Send Message*************\n"); return 0; } int receiveMessage(){ //printf("*********In Receive Message*************\n"); int msqid; key_t key; message_buf rbuf; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ //printf("ERROR"); //key = ftok("dup.c", 'b'); key = 1000; //printf("ERROR"); if ((msqid = msgget(key, 0666)) < 0) { //printf("ERROR"); perror("msgget"); return 1; } /* * Receive an answer of message type 1. */ if (msgrcv(msqid, &rbuf, MSGSZ, getpid(), 0) < 0) { perror("msgrcv"); return 1; } /* * Print the answer. */ printf("\nMessage received at client end: %s\n", rbuf.mtext); //printf("*********Exit Receive Message*************\n"); return 0; } int main() { while(1) { if(sendMessage() == 2){ return 0; } printf("press any key to receive message: "); getchar(); getchar(); receiveMessage(); } }
C
/****************************************** * * mincsubvol * * Cuts down the minc file size by taking only * a subvolume of the entire data * * Johnathon Walls, 2006 * ******************************************/ #include "fdr.h" int isverbose=1; int main(int argc, char *argv[]) { int result; long n3,n2,n1; long m3,m2,m1; int s0, s1, s2, c0, c1, c2; unsigned long start[3],count[3]; float *data1 = NULL; if(argc!=5) { fprintf(stderr, "What are you doing? I need a start, a count, an input file and an output file!\n"); return 1; } if(! sscanf(argv[1], "%d,%d,%d",&s0,&s1,&s2)) { fprintf(stderr, "Start is improperly formatted! (%s%)\n", argv[1]); return 0; } if(! sscanf(argv[2],"%d,%d,%d",&c0,&c1,&c2)) { fprintf(stderr, "Count is improperly formatted! (%s%)\n", argv[2]); return 0; } fprintf(stdout, "Ok! %s=%d-%d-%d %s=%d-%d-%d\n", argv[1], s0,s1,s2,argv[2],c0,c1,c2); start[0] = s0; start[1] = s1; start[2] = s2; count[0] = c0; count[1] = c1; count[2] = c2; result = get_minc_subvol(argv[3], start, count, &n3, &n2, &n1, &data1, REAL_AS_REAL); if(!result) { free(data1); return 1; } if(isverbose) fprintf(stdout, "Loaded subvolume from minc file 1\n"); result = write_minc_file(argv[4], count[0], count[1], count[2], data1, REAL_AS_REAL); if(isverbose) fprintf(stdout, "Wrote minc file\n"); free(data1); return 0; }
C
/** * hilla halevi 208953083 */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <wait.h> #include <memory.h> #define MAX_COMMAND 1024 #define MAX_COMMAND_ARGS 512 #define MAX_BACKGROUND_PROCESSES 512 #define PRINT_ERROR fprintf(stderr, "Error in system call"); #define UPDATE_WD strcpy(previousPwd,currentPwd); #define PRINT_PROMPT_SIGN printf("> "); #define NOT_SET "not set" #define HOME "HOME" #define EXIT "/bin/exit" #define CD "/bin/cd" #define JOBS "/bin/jobs" #define MAN "/bin/man" /*Process struct contains pid and cmd the process do*/ typedef struct Process { pid_t pid; char cmd[MAX_COMMAND]; } Process; typedef struct CommandInfo { char *cmd; char *command; char *argv[MAX_COMMAND_ARGS + 1]; int lastArgIndex; int backgroundFlag; } CommandInfo; /** * use strcmp to see if 2 strings r eql * @param a * @param b * @return true/ false */ bool equal(char *a, char *b) { if (strcmp(a, b) == 0) { return true; } return false; } /** * separate the command line into an array of commands and returns the amount * of args in total * @param cmd_args the array to store the arguments * @param cmdLine the command line to separate * @return number of arguments */ int separate(char cmd_args[MAX_COMMAND_ARGS][MAX_COMMAND], char *cmdLine) { char cmd_copy[MAX_COMMAND]; strcpy(cmd_copy, cmdLine); /* adding the right format for command*/ char first[MAX_COMMAND] = "/bin/"; char *arg = strtok(cmd_copy, " "); arg = strcat(first, arg); int numOfArgs = 0; while (arg != NULL) { stpcpy(cmd_args[numOfArgs], arg); arg = strtok(NULL, " "); numOfArgs++; } return numOfArgs; } /** * set the Parms info according to the right format and the command * @param cmdLine command line * @param info the parms info */ void setArgs(char *cmdLine, CommandInfo *info) { // cmdArgs is an array of strings so it contains the command name and then the args following char cmdArgs[MAX_COMMAND_ARGS][MAX_COMMAND]; int argsNum = separate(cmdArgs, cmdLine); //add null at the end for the execv format info->backgroundFlag = 0; info->command = cmdArgs[0]; info->cmd = cmdLine; int i; for (i = 0; i < argsNum; i++) { if (i == argsNum - 1 && equal(cmdArgs[i], "&")) { info->backgroundFlag = 1; break; } info->argv[i] = cmdArgs[i]; } info->argv[i] = NULL; // index of last real arg info->lastArgIndex = i - 1; } /** * clear intake of the command * @param command_line */ void intake(char *command_line) { scanf(" "); fgets(command_line, MAX_COMMAND - 1, stdin); command_line[strlen(command_line) - 1] = '\0'; } /** * try chdir to specific path * @param path * @param previousPwd * @param currentPwd */ void chdirTry(char *path, char *previousPwd, char *currentPwd) { if (chdir(path) == -1) { PRINT_ERROR } else { UPDATE_WD } } /** * split a command by specific char * @param commandInfo * @param c */ void splitByChar(CommandInfo *commandInfo, char c) { char cmd_copy[MAX_COMMAND]; strcpy(cmd_copy, commandInfo->cmd); /* adding the right format for command*/ char *token; int cmd_args_counter = 0; token = strtok(cmd_copy, &c); // split command and append tokens to array arguments while (token != NULL) { strcpy(commandInfo->argv[cmd_args_counter], token); token = strtok(NULL, &c); cmd_args_counter++; } strcpy(commandInfo->argv[0], CD); } /** * fix the path to the right format, no quotation marks * connect tokens to a legit path * @param commandInfo */ void pathOrganizer(CommandInfo *commandInfo) { if (commandInfo->lastArgIndex < 1) { //no path return; } char cmd_copy[MAX_COMMAND]; strcpy(cmd_copy, commandInfo->cmd); /* adding the right format for command*/ if (strchr(cmd_copy, '\'') != NULL) { splitByChar(commandInfo,'\''); } else if (strchr(cmd_copy, '\"') != NULL) { splitByChar(commandInfo,'\"'); } } /** * CD act * @param commandInfo */ void actCD(CommandInfo *commandInfo, char *previousPwd) { pid_t currPID = getpid(); printf("%d\n", currPID); pathOrganizer(commandInfo); char currentPwd[MAX_COMMAND]; if (getcwd(currentPwd, MAX_COMMAND) == NULL) { PRINT_ERROR } // global path: cd/cd~ if (equal(commandInfo->argv[commandInfo->lastArgIndex], CD) || equal(commandInfo->argv[1], "~")) { //try set working directory to HOME chdirTry(getenv(HOME), previousPwd, currentPwd); } else if (equal(commandInfo->argv[1], "-")) { if (!equal(previousPwd, NOT_SET)) { // go to previous folder if (chdir(previousPwd) == -1) { PRINT_ERROR } else { printf("%s\n", previousPwd); UPDATE_WD } } else { //OLDWD not set fprintf(stderr, "cd: OLDWD not set\n"); } } else { chdirTry(commandInfo->argv[1], previousPwd, currentPwd); } } /** * remove all dead processes from the array * @param jobsArr * @param processCounter * @return number of living processes */ int updateJobArr(Process jobsArr[], int processCounter) { Process livingProcessesArr[processCounter]; int livingProcesses = 0; int i = 0; for (i = 0; i < processCounter; i++) { if (waitpid(jobsArr[i].pid, NULL, WNOHANG) == 0) { // pid alive, save it to the temp array livingProcessesArr[livingProcesses] = jobsArr[i]; livingProcesses++; } } // temp process arr now holds only active processes-copy back to jobs arr for (i = 0; i < livingProcesses; i++) { jobsArr[i] = livingProcessesArr[i]; } return livingProcesses; } /** * update the jobs array and prints all living processes * @param jobs_arr * @param processCounter */ int actJOBS(Process jobs_arr[], int processCounter) { processCounter = updateJobArr(jobs_arr, processCounter); int i; // prints active processes for (i = 0; i < processCounter; i++) { printf("%ld ", (long) jobs_arr[i].pid); // clear the "&" if exists char *cmd; cmd = strtok(jobs_arr[i].cmd, "&"); printf("%s\n", cmd); } return processCounter; } /** * EXIT act, kill all the background processes and exit * @param jobsArr * @param numOfJobs */ void actEXIT(Process jobsArr[], int numOfJobs) { pid_t currPID = getpid(); printf("%d\n", currPID); int k = 0; for (k = 0; k < numOfJobs; k++) { kill(jobsArr[k].pid, SIGTERM); } } /** * child process * @param commandInfo */ void actChild(CommandInfo *commandInfo) { if (equal(commandInfo->command, MAN)) { //man requires special treatment commandInfo->command = "man"; execvp("man", commandInfo->argv); } else { execv(commandInfo->command, commandInfo->argv); } //not supposed to happened PRINT_ERROR } /** * parent shell process * @param commandInfo * @param jobsArr * @param counter * @param pid * @return the counter updated */ int actParent(CommandInfo *commandInfo, Process jobsArr[], int counter, pid_t pid) { printf("%d\n", pid); //childes pid if (commandInfo->backgroundFlag) { // the background flag is on Process currProcess; currProcess.pid = pid; strcpy(currProcess.cmd, commandInfo->cmd); jobsArr[counter] = currProcess; counter++; } else { // foreground process, wait for child while (waitpid(pid, NULL, WNOHANG) == 0) { } } return counter; } int main() { // stores background processes Process jobsArr[MAX_BACKGROUND_PROCESSES]; char previousPwd[MAX_COMMAND] = NOT_SET; int processNum = 0; while (1) { /*************intake*********/ PRINT_PROMPT_SIGN char cmdLine[MAX_COMMAND]; intake(cmdLine); CommandInfo commandInfo; setArgs(cmdLine, &commandInfo); /**********actions*************/ if (equal(commandInfo.command, EXIT)) { actEXIT(jobsArr, processNum); exit(0); } else if (equal(commandInfo.command, CD)) { actCD(&commandInfo, previousPwd); } else if (equal(commandInfo.command, JOBS)) { processNum = actJOBS(jobsArr, processNum); } /*************standard command*********/ else { pid_t pid = fork(); // create process for this command switch (pid) { case -1: { perror("fork error"); } break; case 0: { actChild(&commandInfo); } break; default: { processNum = actParent(&commandInfo, jobsArr, processNum, pid); } } } } }
C
#include <stdio.h> #include <stdlib.h> int main() { char s[20]; int dig=0, vow=0, i=0; printf("\t VOWELS AND DIGITS\n"); printf("Enter a String:"); gets(s); while(s[i]!='\0') { switch(s[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': dig++; break; case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': vow++; break; } i++; } printf("\nDigits\tVowels\n"); printf("%d\t%d", dig, vow); return 0; }
C
#include <ctype.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "date.h" #include "file.h" #include "list.h" #include "todo.h" struct todo_item* new_todo_item(void) { return (struct todo_item*) calloc(1, sizeof(struct todo_item)); } void free_todo_item(struct todo_item* todo) { free(todo); } int parse_todo_item(char* buffer, struct todo_item* todo) { int position = 0; int description_length; if (buffer[position] == 'x' && buffer[position+1] == ' ') { todo->done = true; position += 2; } if (buffer[position] == '(' && buffer[position+2] == ')' && buffer[position+3] == ' ') { todo->priority = buffer[position+1]; position += 4; } if (isdigit(buffer[position])) { if (todo->done) { if (read_date(buffer+position, &todo->completion_tm)) return -1; // move to the possible creation date position += 11; } if (read_date(buffer+position, &todo->creation_tm)) MAKE_DATE_INVALID(&todo->creation_tm); else position += 11; } description_length = strlen(buffer+position); todo->description = (char*) malloc((description_length+1)*sizeof(char)); if (todo->description == NULL) return -ENOMEM; memcpy(todo->description, buffer+position, description_length-1); todo->description[description_length-1] = '\0'; return 0; } void insert_todo_item(struct todo_item* head, struct todo_item* new) { if (!new->priority) { // put it to the end of the list while (head->next) head = head->next; insert_after(head, new); return; } while (head->priority && head->priority <= new->priority) { if (!head->next) { insert_after(head, new); return; } head = head->next; } insert_before(head, new); return; } struct todo_item* load_todo_items(void) { char* line; struct todo_item *head_todo = NULL, *iter_todo = NULL, *old_todo; bool inconsistent = false; FILE* file = open_todo_file(); if (!file) return NULL; iter_todo = head_todo; while ((line = read_line(file))) { old_todo = iter_todo; iter_todo = new_todo_item(); if (!iter_todo) { close_todo_file(file); return NULL; } if (parse_todo_item(line, iter_todo)) { inconsistent = true; free_todo_item(iter_todo); continue; } if (!head_todo) { head_todo = iter_todo; continue; } insert_after(old_todo, iter_todo); } close_todo_file(file); if (inconsistent) puts("Warning! Some todo.txt entries are invalid. Check them before quitting."); return head_todo; } char* todo_item_to_str(struct todo_item* todo) { static char* buffer; char* new_buffer; static size_t buffer_size; int position = 0; int bytes_written; if (!buffer) { buffer_size = 128; buffer = (char*) malloc(buffer_size*sizeof(char)); if (!buffer) return NULL; } if (todo->done) { buffer[position++] = 'x'; buffer[position++] = ' '; } if (todo->priority) { buffer[position++] = '('; buffer[position++] = todo->priority; buffer[position++] = ')'; buffer[position++] = ' '; } if (!IS_DATE_INVALID(&todo->completion_tm)){ bytes_written = strftime(buffer+position, buffer_size-position, "%Y-%m-%d ", &todo->completion_tm); if (!bytes_written) return NULL; position += bytes_written; } if (!IS_DATE_INVALID(&todo->creation_tm)){ bytes_written = strftime(buffer+position, buffer_size-position, "%Y-%m-%d ", &todo->creation_tm); if (!bytes_written) return NULL; position += bytes_written; } while ((strlen(todo->description) + position + 1) > buffer_size) { new_buffer = (char*) realloc(buffer, buffer_size*2*sizeof(char)); if (new_buffer == NULL) return NULL; buffer_size *= 2; buffer = new_buffer; } memcpy(buffer+position, todo->description, strlen(todo->description)+1); return buffer; } int save_todo_items(struct todo_item* head) { char* buffer; struct todo_item* iter; FILE* todo_file = open_todo_file_for_writing(); if (!todo_file) return -1; iter = head; while (iter) { buffer = todo_item_to_str(iter); if (!buffer) { close_todo_file_for_writing(todo_file); return -1; } if (write_line(todo_file, buffer)) return -1; iter = iter->next; } close_todo_file_for_writing(todo_file); return 0; }
C
/** *@brief スタックにデータを積む関数pushとデータを取り出す関数popを作る。 * * *@version 1.0.0 * */ #include <stdio.h> #define MAXSIZE 100 /* スタックサイズ */ int stack[MAXSIZE]; /* スタック */ int stack_p = 0; /* スタックポインタ */ //int push(int n); //int pop(int *n); void main(void) { int c; int n; while (printf("]"),(c == getchar()) != EOF){ rewind(stdin); if (c == 'i' || c == 'I'){ printf("data--> "); scanf("%d", &n);rewind(stdin); if (push(n) == -1){ printf("スタックが一杯です。\n"); } } if (c == 'o' || c == 'O'){ if (pop(&n) == -1) printf("スタックは空です。\n"); else printf("stack data --> %d\n", n); } } // return 0; } int push(int n) { if (stack_p < MAXSIZE){ stack[stack_p] = n; stack_p++; return (0); } else return (-1); } int pop(int *n) { if (stack_p > 0){ stack_p--; *n = stack[stack_p]; return (0); } else return (-1); }
C
#include<stdio.h> struct node { int data; struct node *next; }; struct node *head = NULL; struct node* createNode() { struct node *temp; temp = (struct node*)malloc(sizeof(struct node)); return temp; } void insertFront(struct node *ptr,int data) { ptr->data = data; ptr->next = head; head = ptr; } void insertRear(struct node *ptr,int data) { ptr->data = data; ptr->next = NULL; if(head == NULL) { head = ptr; } struct node *temp = head; while(temp->next != NULL) { temp = temp->next; } temp->next = ptr; } void insertPos(struct node *ptr, int data,int pos) { int i; ptr->data = data; struct node *temp = head; if(pos == 1) { head = ptr; } else{ for(i=1; i<pos-1; i++) { temp = temp->next; } ptr->next = temp->next; temp->next = ptr; } } void display() { struct node *temp; temp = head; printf("\n"); while(temp != NULL) { printf("%d ",temp->data); temp = temp->next; } } void sort() { int i,j, n=0; struct node *temp; temp = head; while(temp != NULL) { temp = temp->next; n++; } printf("\n%d no. of elements sorted in ascending order\n",n); temp = head; int x; struct node *first; for(i=1; i<n; i++) { temp = head; for(j=i+1; j<=n; j++) { first = temp; temp = temp->next; if(temp->data < first->data) { x = first->data; first->data = temp->data; temp->data = x; } } } } void insertInSorted(struct node *ptr,int data) { sort(); struct node *temp; temp = head; if(data <= temp->data) { ptr->data = data; ptr->next = head; head = ptr; return; } while(temp->next != NULL) { if(data <= temp->next->data) break; temp = temp->next; } ptr->data = data; ptr->next = temp->next; temp->next = ptr; } int main(){ int ele; int choice; int pos; printf("\n1.Insert at front\n2.Insert at Rear\n3.Insert at position\n4.Sort the list\n5.Insert in sorted list\n6.Display\n7.Exit\n"); do { printf("\nEnter your choice\n"); scanf("%d", &choice); switch(choice) { case 1: { printf("\nEnter data to be inserted\n"); scanf("%d", &ele); struct node *temp; temp = createNode(); insertFront(temp,ele); break; } case 2: { printf("\nEnter data to be inserted\n"); scanf("%d", &ele); struct node *temp; temp = createNode(); insertRear(temp,ele); break; } case 3: { printf("\nEnter data to be inserted\n"); scanf("%d", &ele); printf("\nEnter position for insertion\n"); scanf("%d", &pos); struct node *temp; temp = createNode(); insertPos(temp,ele,pos); break; } case 4: { sort(); break; } case 5: { printf("\nEnter data to be inserted\n"); scanf("%d", &ele); struct node *temp; temp = createNode(); insertInSorted(temp,ele); break; } case 6: { display(); break; } } } while(choice != 7); return 0; }
C
/* Hello World Parallel for program with illustarion to dynamic schedule clause */ #include <stdio.h> #include <omp.h> // Header file for OpenMP int main () { /* Serial Section */ int i, j; /*******************/ /* Parallel Section */ // #pragma omp parallel for private(i) schedule(dynamic) #pragma omp parallel for private(i) schedule(static) for (j=0; j<20; j++) { i=omp_get_thread_num(); printf("Hello World from thread %d, Iteration %d\n",i,j); } /*******************/ /* Serial Section */ return 0; /*******************/ }
C
#define _CRT_SECURE_NO_WARNINGS /*ֹʹscanf()Ⱥʱ*/ /* Ҫʵһʽı ӿڶ壺 int Length( List L ); Listṹ£ typedef struct LNode *PtrToLNode; struct LNode { ElementType Data; PtrToLNode Next; }; typedef PtrToLNode List; LǸLengthҪʽijȡ 1 3 4 5 2 -1 5 */ #include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct LNode* PtrToLNode; struct LNode { ElementType Data; PtrToLNode Next; }; typedef PtrToLNode List; List Read(); int Length(List L); int main() { List L = Read(); printf("%d\n", Length(L)); return 0; } List Read() { List head = NULL, tail = NULL, p; ElementType Data; scanf("%d", &Data); while (Data != -1) { p = (List) malloc(sizeof(List)); p->Data = Data; p->Next = NULL; if (head == NULL) head = p; else tail->Next = p; tail = p; scanf("%d", &Data); } return head; } int Length(List L) { int length = 0; for (List p = L; p != NULL; p = p->Next) { length++; } return length; }
C
// Use AES-based RNG #include "aes-rng.h" #ifdef __AES__ struct RNG_state *init_aesrand_r(uint32_t seed1, uint32_t seed2) { // Internal state: count + t struct RNG_state *rng = (struct RNG_state *) malloc(sizeof(struct RNG_state)); assert(rng); rng->count = _mm_setr_epi32(seed1, seed2, 0, 0); rng->k = _mm_setr_epi32(0, 0, seed1, seed2); rng->next = 0; return rng; } uint32_t aesrand_int32_r(struct RNG_state *rng) { switch (rng->next++) { case 0: // Increment counter rng->count = _mm_add_epi64(rng->count, _mm_setr_epi32(0, 0, 1, 0)); // 6 AES rounds rng->t = rng->count; rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); return (uint32_t) _mm_extract_epi32(rng->t, 0); case 1: return (uint32_t) _mm_extract_epi32(rng->t, 1); case 2: return (uint32_t) _mm_extract_epi32(rng->t, 2); case 3: rng->next = 0; return (uint32_t) _mm_extract_epi32(rng->t, 3); default: assert(0); } } uint64_t aesrand_int64_r(struct RNG_state *rng) { switch (rng->next++) { case 0: // Increment counter rng->count = _mm_add_epi64(rng->count, _mm_setr_epi32(0, 0, 1, 0)); // 6 AES rounds rng->t = rng->count; rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); return (uint64_t) _mm_extract_epi64(rng->t, 0); case 1: rng->next = 0; return (uint64_t) _mm_extract_epi64(rng->t, 1); default: assert(0); } } uint8_t aesrand_int8_r(struct RNG_state *rng) { switch (rng->next++) { case 0: // Increment counter rng->count = _mm_add_epi64(rng->count, _mm_setr_epi32(0, 0, 1, 0)); // 6 AES rounds rng->t = rng->count; rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); rng->t = _mm_aesenc_si128(rng->t, rng->k); return (uint8_t) _mm_extract_epi8(rng->t, 0); case 1: return (uint8_t) _mm_extract_epi8(rng->t, 1); case 2: return (uint8_t) _mm_extract_epi8(rng->t, 2); case 3: return (uint8_t) _mm_extract_epi8(rng->t, 3); case 4: return (uint8_t) _mm_extract_epi8(rng->t, 4); case 5: return (uint8_t) _mm_extract_epi8(rng->t, 5); case 6: return (uint8_t) _mm_extract_epi8(rng->t, 6); case 7: return (uint8_t) _mm_extract_epi8(rng->t, 7); case 8: return (uint8_t) _mm_extract_epi8(rng->t, 8); case 9: return (uint8_t) _mm_extract_epi8(rng->t, 9); case 10: return (uint8_t) _mm_extract_epi8(rng->t, 10); case 11: return (uint8_t) _mm_extract_epi8(rng->t, 11); case 12: return (uint8_t) _mm_extract_epi8(rng->t, 12); case 13: return (uint8_t) _mm_extract_epi8(rng->t, 13); case 14: return (uint8_t) _mm_extract_epi8(rng->t, 14); case 15: rng->next = 0; return (uint8_t) _mm_extract_epi8(rng->t, 15); default: assert(0); } } #else struct RNG_state* init_aesrand_r(uint32_t seed1, uint32_t seed2) { die ("AES-NI support not enabled!\n"); } uint32_t aesrand_int32_r(struct RNG_state* rng) { die ("AES-NI support not enabled!\n"); } uint64_t aesrand_int64_r(struct RNG_state* rng) { die ("AES-NI support not enabled!\n"); } uint8_t aesrand_int8_r(struct RNG_state* rng) { die ("AES-NI support not enabled!\n"); } #endif
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int demo(void) { int i; printf("-----------------ͻϢ-----------------\n"); printf(" 1 \n"); printf(" 2 \n"); printf(" 3 ɾ \n"); printf(" 4 \n"); printf(" 5 \n"); printf(" ѡ(1-5)"); //scanf("%c", &i); scanf("%d", &i); //getchar(i); printf("%d\n", i); if (i==1) { //printf("Ҫӵĸ"); //scanf("%d", &j); add(); } else if (i==2) { xiugai(); } else if (i==3) { remov(); } else if (i==4) { look(); } else if (i==5) { } else { printf("벻1-5Χڣ˳\n"); } return 0; } int main() { demo(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rotate.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cpaquet <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/13 15:22:17 by cpaquet #+# #+# */ /* Updated: 2019/08/21 11:52:57 by cpaquet ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" #define DATA_MAP ((t_point*)map->content) static void rotate_x(float *new_coord, int *key, int *rotation_x) { double tab[3]; *key == 91 ? (*rotation_x)++ : 0; *key == 84 ? (*rotation_x)-- : 0; *key == 91 || *key == 84 ? *key = 0 : 0; ft_bzero(&tab, sizeof(tab)); *rotation_x = *rotation_x == 181 ? 1 : *rotation_x; *rotation_x = *rotation_x == -1 ? 179 : *rotation_x; tab[0] = new_coord[0]; tab[1] = 0 + cos((PI / 180) * *rotation_x) * new_coord[1] - sin((PI / 180) * *rotation_x) * new_coord[2]; tab[2] = 0 + sin((PI / 180) * *rotation_x) * new_coord[1] + cos((PI / 180) * *rotation_x) * new_coord[2]; new_coord[0] = tab[0]; new_coord[1] = tab[1]; new_coord[2] = tab[2]; } static void rotate_y(float *new_coord, int *key, int *rotation_y) { double tab[3]; *key == 88 ? (*rotation_y)++ : 0; *key == 86 ? (*rotation_y)-- : 0; *key == 88 || *key == 86 ? *key = 0 : 0; ft_bzero(&tab, sizeof(tab)); *rotation_y = *rotation_y == 181 ? 1 : *rotation_y; *rotation_y = *rotation_y == -1 ? 179 : *rotation_y; tab[0] = cos((PI / 180) * *rotation_y) * new_coord[0] + sin((PI / 180) * *rotation_y) * new_coord[2]; tab[1] = new_coord[1]; tab[2] = -sin((PI / 180) * *rotation_y) * new_coord[0] + cos((PI / 180) * *rotation_y) * new_coord[2]; new_coord[0] = tab[0]; new_coord[1] = tab[1]; new_coord[2] = tab[2]; } static void rotate_z(float *new_coord, int *key, int *rotation_z) { float tab[3]; *key == 92 ? (*rotation_z)++ : 0; *key == 89 ? (*rotation_z)-- : 0; *key == 92 || *key == 89 ? *key = 0 : 0; ft_bzero(&tab, sizeof(tab)); *rotation_z = *rotation_z == 181 ? 1 : *rotation_z; *rotation_z = *rotation_z == -1 ? 179 : *rotation_z; tab[0] = cos((PI / 180) * *rotation_z) * new_coord[0] - sin((PI / 180) * *rotation_z) * new_coord[1]; tab[1] = sin((PI / 180) * *rotation_z) * new_coord[0] + cos((PI / 180) * *rotation_z) * new_coord[1]; tab[2] = new_coord[2]; new_coord[0] = tab[0]; new_coord[1] = tab[1]; new_coord[2] = tab[2]; } static void copy_coord(t_list *point, float *new_coord, char code, t_data *data) { if (code == 1) { new_coord[0] = ((t_point*)point->content)->x - data->center_rotat_x; new_coord[1] = ((t_point*)point->content)->y - data->center_rotat_y; new_coord[2] = ((t_point*)point->content)->z; } else if (code == 2) { ((t_point*)point->content)->new_x = new_coord[0] + data->center_rotat_x; ((t_point*)point->content)->new_y = new_coord[1] + data->center_rotat_y; ((t_point*)point->content)->new_z = new_coord[2]; } } void rotate(t_data *data, int *key) { t_list *map; float *coord; coord = NULL; map = data->map; if (!(coord = (float*)malloc(sizeof(float) * 3))) ft_error(data, "Error system in rotate function"); while (map) { ft_bzero(coord, sizeof(float) * 3); copy_coord(map, coord, 1, data); rotate_x(coord, key, &(data->rotation_x)); rotate_y(coord, key, &(data->rotation_y)); rotate_z(coord, key, &(data->rotation_z)); copy_coord(map, coord, 2, data); map = map->next; } if (coord) free(coord); }
C
#ifndef REGISTRY_H #define REGISTRY_H #ifdef FEOS #include <feos.h> #else #define FEOS_EXPORT #endif #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef enum { KEY_VOID, /* NULL data */ KEY_NUMBER, /* 64-bit int, signed or unsigned (user keeps track of signedness) */ KEY_STRING, /* string data */ KEY_RAW, /* binary data */ } KeyType; typedef struct { char *name; /* key name */ KeyType type; /* key type */ size_t length; /* length of data */ union { uint64_t number; /* if type == KEY_NUMBER */ char *string; /* if type == KEY_STRING */ void *raw; /* if type == KEY_RAW */ }; } KeyPair; /* open/close registry. returns 0 for success, -1 for failure all failures will set errno */ FEOS_EXPORT int regOpen (void); FEOS_EXPORT int regClose(void); /* path: in format /path/to/key '/' is not a valid key (it is the special root key that cannot be accessed) value: the data to insert length: length of the data (for raw; string length is calculated via strlen()) returns 0 for success, -1 for failure all failures will set errno */ FEOS_EXPORT int regDelKey (const char *path); FEOS_EXPORT int regSetVoid (const char *path); FEOS_EXPORT int regSetNumber(const char *path, uint64_t value); FEOS_EXPORT int regSetString(const char *path, const char *value); FEOS_EXPORT int regSetRaw (const char *path, const void *value, size_t length); /* path: same as above returns KeyPair* for success, NULL for failure all failures will set errno */ FEOS_EXPORT KeyPair* regGetKeyPair(const char *path); /* path: same as above returns 0 for success, -1 for failure all failures will set errno */ FEOS_EXPORT int regFreeKeyPair(KeyPair *kp); #ifdef __cplusplus } #endif #endif /* REGISTRY_H */
C
#include <stdbool.h> #include "audio.h" #ifndef __BEAT_H__ #define __BEAT_H__ msec_t beat_to_msec(float bpm,float beat); typedef void (*drum_f)(track_t *t, float vol); #define MAX_SUBTRACKS 32 typedef struct beatloop_s{ float bpm; float beatCount; /* length of the loop in beats*/ int drumCount; /* total amount of drums in the loop*/ float *drumTime; /* [drumCount] time where the drum is hit in the loop*/ float *drumVol; /* [drumCount] volume of the related drum */ drum_f *drums; /* [drumCount] the drums */ int *drumSubtrack; /* [drumCount] subtrack of the related drum */ int subtrackCount; /*total amount of subtracks in the beatloop */ char mixmode[MAX_SUBTRACKS]; /*[subtrackCount]*/ float subtrackVol[MAX_SUBTRACKS]; /*[subtrackCount]*/ track_t *subtrack[MAX_SUBTRACKS]; /* [subtrackCount]*/ track_t *track; }beatloop_t; beatloop_t *beatloopNew(int beatcount); /*eg 140bpm, 4 beatcount for techno*/ /* adds a drum sample to the beat loop at "beat" time. * beat starts at 1 and finishes at beatcount, fractional beats are ok */ #define MIXMODE_MIX 0 #define MIXMODE_CUT 1 int subtrack(beatloop_t *bl, int mixmode, float volume); void drum(beatloop_t*bl, int subtrack, drum_f drum, float beat, float vol); /* mix the beatloop on the track at "beat", in bpm unit. */ void beatloopMix(track_t *t,beatloop_t *bl,int beat,float bpm,float vol); typedef struct beatTrack_s{ float bpm; int measure; track_t *track; struct beatTrack_s *next; }btrack_t; btrack_t *btrackNew(float bpm, int measure,int measure_count); void btrackAdd( btrack_t *bt, beatloop_t*bl, int measure_start, int measure_end, /* if <= 0 -> until the end*/ bool fill_measure, /*if beatloop is shorter than measure, it will repeat to fill the measure, if longer, it will be cut */ float vol); /* puts the btrack to be mixed after dst. * if insert is true, it will be inserted just * after b void btrackAppend(btrack_t *dst,btrack_t *src, bool insert);*/ #endif
C
#include <stdio.h> #include <conio.h> void main() { int a, b; for(a = 1 ; a <= 7 ; a++) { b = a; while(b <= 7) { printf("* "); b++; } printf("\n"); } getch(); }
C
#include "holberton.h" /** * _isalpha - checks for alphabet characters * @c: c argument has character value in ASCII * Return: 1/0 character is alphabet/not alpha * */ int _isalpha(int c) { if ((c >= 97 && c < 123) || (c >= 65 && c < 91)) { return (1); } else { return (0); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_texture_lock.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jblack-b <jblack-b@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/25 19:00:59 by jblack-b #+# #+# */ /* Updated: 2019/05/16 19:25:19 by jblack-b ### ########.fr */ /* */ /* ************************************************************************** */ #include "libsdl.h" /* * Fucntion: used when writing to texture is needed * - use it to get pointer, array of pixel that texture consist of * Parameters: sdl, texture * Return: pointer to array of pixel that texture consist of */ Uint32 *ft_texture_lock(t_sdl *sdl, t_texture *texture) { //SDL_LockTexture(texture->sdl_texture, NULL, (void **)texture->pixels, &texture->pitch); SDL_LockTexture(texture->sdl_texture, NULL, (void **)&texture->pixels, &texture->pitch); return (texture->pixels); }
C
#include <stdio.h> // 排列組合 // 照順序排列 // 組合 // 每個字元輪流當首位,往後做排序 // list all permulations of an array // @data array of chars to permulate // @n length of array void swap(char data[], int x, int y) { char tmp = data[x]; data[x] = data[y]; data[y] = tmp; } // n為陣列長度 // m為想取的組合個數 // from為目前處理到哪個位置 // got為已經取了幾個 void comb2(char data[], int n, int m, int from, int got) { int i; if(m == got) { for(i = 0; i < m; i++) { printf("%c", data[i]); } printf("\n"); return; } // 試圖選擇第 i個元素 for(i = from; i < n; i++) { // 選 i,並把此值存到前面去 swap(data, i, got); // 遞迴處理剩下的資料 // 從 i+1而非從 from開始選,是為避免重複選到相同的組合 comb2(data, n, m, i + 1, got + 1); // 回復原值 swap(data, i, got); } } void comb(char data[], int n, int m) { comb2(data, n, m, 0, 0); } void main() { char s[] = {'A', 'B', 'C', 'D'}; comb(s, 4, 2); }
C
#include "stc89c51_tim.h" /* * brief : Initial TIM0 and TIM1 * param_1: TIM0TIM1 * param_2: Timing_500usTiming_1msTiming_10msTiming_50ms * param_3: TIM0_TimeBase_Mode_1TIM0_TimeBase_Mode_2TIM0_MeasrePW_ModeTIM0_PusCnt_Mode * TIM1_TimeBase_Mode_1TIM1_TimeBase_Mode_2TIM1_MeasrePW_ModeTIM1_PusCnt_Mode */ void TIM_Init(uchar TIMx, uint16 TIM_Reload, uchar TIM_Mode) { /* ʱΪ16λװģʽ */ if ((TIM_Mode == TIM0_TimeBase_Mode_1) && ((TIM_Mode == TIM1_TimeBase_Mode_1))) { if (TIMx == TIM0) { TH0 = TIM_Reload >> 8; TL0 = (uchar)TIM_Reload; } else { TH1 = TIM_Reload >> 8; TL1 = (uchar)TIM_Reload; } } /* ʱΪԶģʽ(8Ϊģʽ) */ else if ((TIM_Mode == TIM0_TimeBase_Mode_2) && ((TIM_Mode == TIM1_TimeBase_Mode_2))) { if (TIMx == TIM0) { TL0 = (uchar)TIM_Reload; TH0 = (uchar)TIM_Reload; } else { TL1 = (uchar)TIM_Reload; TH1 = (uchar)TIM_Reload; } } else /* ʱΪģʽ */ { /* Ҫװֵ */ } TMOD |= TIM_Mode; } /* * brief : Initial TIM2 * param_1: Timing_500usTiming_1msTiming_10msTiming_50ms * param_2: TIM2_TimeBase_Mode_1TIM2_Capture_ModeTIM2_PusCnt_Mode */ void TIM2_Init(uint16 TIM_Reload, uchar TIM_Mode) { if (TIM_Mode == TIM2_TimeBase_Mode_1) { TH2 = TIM_Reload >> 8; RCAP2H = TIM_Reload >> 8; TL2 = (uchar)TIM_Reload; RCAP2L = (uchar)TIM_Reload; } /* ģʽҪװֵ */ T2CON = TIM_Mode; } /* * brief: ȡֵֵ * ͵ƽĸȲP3.2P3.3ߵƽʱ䣬͵ƽֹͣ * * param: TIM0TIM1TIM2 */ uint16 GET_PulCnt_PW_Val(uchar TIMx) { uint16 value; if (TIMx == TIM0) { value = TH0; value = (value << 8) | TL0; } else if (TIMx == TIM1) { value = TH1; value = (value << 8) | TL1; } else { value = TH2; value = (value << 8) | TL2; } return (value); } /* * brief: ȡֵ͵ƽ */ uint16 TIM2_GET_CaptureVal(void) { uint16 value; value = RCAP2H; value = (value << 8) | RCAP2L; return (value); } /* * brief : Change Timer Priority * parame: TIM0_Priority_0TIM0_Priority_1TIM0_Priority_2TIM0_Priority_3 * TIM1_Priority_0TIM1_Priority_1TIM1_Priority_2TIM1_Priority_3 * TIM2_Priority_0TIM2_Priority_1 */ void TIM_PrioChange(uint16 Priority) { IPH |= Priority >> 8; IP |= (uchar)Priority; } /* * brief : öʱװֵжϷ * param_1: TIM0TIM1 * param_2: Timing_500usTiming_1msTiming_10msTiming_50ms */ void TIM_SetReLoad(uchar TIMx, uint16 TIM_Reload) { if (TIM0 == TIMx) { TH0 = TIM_Reload >> 8; TL0 = (uchar)TIM_Reload; } else { TH1 = TIM_Reload >> 8; TL1 = (uchar)TIM_Reload; } } /*-------------------------------------- End Of File ------------------------------------------------------*/
C
# /* * Copyright c. John Hallam <sw@j.hallam.dk> 2015. * * This program is free software licensed under the terms of the GNU General * Public License, either version 3 of the License, or (at your option) any * later version. See http://www.gnu.org/licenses/gpl.txt for details. */ #include "general.h" #include <stdlib.h> #include "assert.h" #include "queue.h" /* * Implements a doubly-linked queue in ring form. * * Invariant: every q structure is doubly-linked; new structures are singletons. */ public queue *init_queue(queue *p) { if( p == NULL ) { p = (queue *)calloc(1, sizeof(queue)); assertv(p != NULL, "Queue alocation failure\n"); } p->q_next = p->q_prev = p; return p; } /* * Remove p from its queue and make it a singleton. You cannot detach * a singleton from its queue. */ public queue *de_queue(queue *p) { if( p->q_next == p ) return NULL; p->q_prev->q_next = p->q_next; p->q_next->q_prev = p->q_prev; p->q_next = p->q_prev = p; return p; } /* * Splice q and p together so that p immediately follows q and the * next and prev chains continue in the correct senses */ public queue *splice_queue(queue *q, queue *p) { queue *qn, *pp; qn = q->q_next; q->q_next = p; pp = p->q_prev; p->q_prev = q; qn->q_prev = pp; pp->q_next = qn; return q; } /* * Unsplice a queue: cut the ring at start and end and relink. Also * join start and end. */ /* public queue *unsplice_queue(queue *start, queue *end) { } */ /* * Apply a function to each queue member in [start,end). The function * is called with arg as its first argument and the queue structure * pointer as its second. The first function, map_queue_nxt, * traverses the segment "forward" while the second goes "backward". * * If start == end or end is not in the list (e.g. end is NULL) the * functions traverse the whole list visiting each node exactly once. */ public void map_queue_nxt(queue *start, queue *end, void (*fn)(void *, queue *), void *arg) { for_nxt_in_Q(queue *p, start, end) (*fn)(arg, p); end_for_nxt; } public void map_queue_prv(queue *start, queue *end, void (*fn)(void *, queue *), void *arg) { for_prv_in_Q(queue *p, start, end) (*fn)(arg, p); end_for_prv; }
C
#include <stdio.h> int main() { printf("size of char: %ld byte(s)\n", sizeof(char) ); printf("size of unchar: %ld byte(s)\n", sizeof(unsigned char) ); printf("size of short: %ld byte(s)\n", sizeof(short) ); printf("size of unshort: %ld byte(s)\n", sizeof(unsigned short) ); printf("size of int: %ld byte(s)\n", sizeof(int) ); printf("size of unint: %ld byte(s)\n", sizeof(unsigned int) ); printf("size of float: %ld byte(s)\n", sizeof(float) ); return 0; }
C
#ifndef FitFunctions_h #define FitFunctions_h #include <math.h> Double_t fitfunction(Double_t *x, Double_t *par){ Double_t value, value_th, value_0; if (x[0]<par[2]) { value = par[0] + par[1]*sqrt(x[0]) + par[3]*x[0]*sqrt(x[0]); // x^1/2 + x^3/2 } else { value_th = par[0] + par[1]*sqrt(par[2]) + par[3]*par[2]*sqrt(par[2]); value_0 = value_th - par[4]*par[2]; value = value_0 + par[4]*x[0]; // pol1 } //else { value=0; TF1::RejectPoint();} return value; } Double_t fitfunction2(Double_t *x, Double_t *par){ Double_t value, value_th, value_0; if (x[0]<par[2]) { value = par[0]/(1+exp(-1*par[1]*(x[0]+par[3]))); // sigmoid } else { value_th = par[0]/(1+exp(-1*par[1]*(par[2]+par[3]))); value_0 = value_th - par[4]*par[2]; value = value_0 + par[4]*x[0]; // pol1 } //else { value=0; TF1::RejectPoint();} return value; } Double_t fitfunction3(Double_t *x, Double_t *par){ Double_t value, value_th, value_0; if (x[0]<par[2]) { value = par[0] + par[1]*atan(x[0]); // atan } else { value_th = par[0] + par[1]*atan(par[2]); value_0 = value_th - par[3]*par[2]; value = value_0 + par[3]*x[0]; // pol1 } //else { value=0; TF1::RejectPoint();} return value; } Double_t fitfunctionderiv(Double_t *x, Double_t *par){ Double_t value, value_th, value_0; if (x[0]<par[2]) { value = par[0] + par[1]*exp(-1*par[3]*x[0]); } else { value_th = par[0] + par[1]*exp(-1*par[3]*par[2]); value_0 = value_th - par[4]*par[2]; value = value_0 + par[4]*x[0]; // pol1 } //else { value=0; TF1::RejectPoint();} return value; } Double_t fitfunctionderiv2(Double_t *x, Double_t *par){ Double_t value, value_th, value_0; if (x[0]<par[2]) { value = par[0] + par[1]*x[0]; } else { value_th = par[0] + par[1]*par[2]; value_0 = value_th - par[3]*par[2]; value = value_0 + par[3]*x[0]; // pol1 } return value; } #endif
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_check_viewport.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: bnoyer <bnoyer@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/09/10 16:11:27 by bnoyer #+# ## ## #+# */ /* Updated: 2018/12/07 02:54:03 by bnoyer ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "rtv1.h" static int ft_check_height(char *src, int l) { int er; char *tmp; er = 0; if (!ft_strnstr(src, "\t\t\theight = ", ft_strlen(src))) er |= ft_ferr(l, I_LINE); tmp = ft_strtrim(src); if (ft_str_is_number(&(tmp[ft_strlen("height = ")])) != 1) er |= ft_ferr(l, I_ARG); free(tmp); return (er); } static int ft_check_width(char *src, int l) { int er; char *tmp; er = 0; if (!ft_strnstr(src, "\t\t\twidth = ", ft_strlen(src))) er |= ft_ferr(l, I_LINE); tmp = ft_strtrim(src); if (ft_str_is_number(&(tmp[ft_strlen("width = ")])) != 1) er |= ft_ferr(l, I_ARG); free(tmp); return (er); } int ft_check_viewport(char **f, int *l) { int er; er = 0; er |= ft_strcmp(f[*l], "\t\tviewport :") ? ft_ferr(*l, I_LINE) : 0; er |= ft_strcmp(f[++*l], "\t\t{") ? ft_ferr(*l, CBL_EXP) : 0; *l = ft_skip_com(f, *l + 1, &er); er |= ft_check_height(f[*l], *l); *l = ft_skip_com(f, *l + 1, &er); er |= ft_check_width(f[*l], *l); *l = ft_skip_com(f, *l + 1, &er); er |= ft_strcmp(f[*l], "\t\t}") ? ft_ferr(*l, CBR_EXP) : 0; return (er); }
C
// // Triplet_text.c // dataStructure // // Created by 程传翔 on 2020/12/31. // #include "Triplet_text.h" #include "Triplet.h" #include "../predefined/predefined.h" #include <stdio.h> #include <stdlib.h> void Triplet_text(void){ Triplet *T = InitTriplet(1, 2, 3); print(T); int e = 0; Get(T, 2, &e); printf("Get(T, 2, &e): %d\n",e); if(IsAscending(T)){ printf("IsAscending\n"); } Put(T, 2, 5); Get(T, 2, &e); printf("Put(T, 2, 5)\nGet(T, 2, &e): %d\n",e); Put(T, 1, 6); Put(T, 3, 4);; printf("Put(T, 1, 6)\nPut(T, 3, 4);\n"); print(T); if(IsDescending(T)){ printf("IsDescending\n"); } Max(T, &e); printf("Max(T, e): %d\n", e); Min(T, &e); printf("MIn(T, e): %d\n", e); T = DestroyTriplet(T); if(T == NULL){ printf("Memory released successfully\n"); } }
C
/*----------------------------monta_matriz.c---------------------------------*/ /* Este arquivo contem a funcao monta_mat que e responsavel por construir a matriz B' e B'' Ela utiliza as seguintes subfuncoes: 1) preench -> reenche as matrizes jacobianas B' e B'' 2) elim -> Elimina as colunas e linhas referentes a barra slack para ce(B') Elimina as colunas e linhas referentes as barras slacks e PV para cle(B") ----------------------------------------------------------------------------------*/ /*----------------- arquivos incluidos ------------------*/ #include<stdlib.h> #include "global.h" /*--------------prototipo de funcoes usadas ------------*/ void preench(int,int,double,double[]); void elim(double valores[],int nn); /*----------------------Inicio da Funcao monta_mat------------ */ void monta_mat(double ce[],double cle[]){ int i,ki,k,l; double xbl; /*--------------------------------- Inicializar vetores "ce" e "cle" -------------------------------*/ for(i=0; i<maxnzero; i++) { ce[i] = 0.e0; // B' cle[i] = 0.e0; // B'' } /*-------------------------------------------------------- Construir vetor com a ordem de fatoracao da coluna "ki" -------------------------------------------------------*/ for(i=0; i<nb; i++) { ki = nseq[i]; lrd[ki] = i; } /*------------------------------------------------------------------- Constroi as matrizes B' e B'', fazendo a eliminacao da barra slack --------------------------------------------------------------------*/ for(i=0; i<nl; i++) { k = ni[i]; l = nf[i]; /*---------------------------------------------------- construir a matirz B' ( substitui a funcao matb1) --------------------------------------------------*/ ce[k] = ce[k]-b1kl[i]; ce[l] = ce[l]-b1kl[i]; preench(k,l,b1kl[i],ce); /*-------------------------------------------------- construir a matriz B'' (substitui a funcao matb2) -------------------------------------------------*/ cle[k] = cle[k]-b2kl[i]; cle[l] = cle[l]-b2kl[i]; preench(k,l,b2kl[i],cle); } for(i=0; i<nb; i++) { xbl = -2.e0*shu[i]; // shu[i] e o shunt total preench(i,i,xbl,cle); } /*----------------------- Eliminar a linha slack ----------------------*/ elim(ce,1); /*------------------------------ Eliminar as linhas slack e PV -----------------------------*/ elim(cle,0); return; } /*--------------------------- Fim da funcao monta_mat------------------------*/ /*-----------------------Inicio da funcao preench---------------------------*/ void preench(int k,int l,double custo,double valores[]) { int p1,p2,lc,le; p1 = lrd[k]; /* indice da coluna de ordem "k" de execucao */ p2 = lrd[l]; /* indice da coluna de ordem "l" de execucao */ if(p1 == p2) { le = k; lc = lcol[k]; } else if(p1 < p2) { le = l; lc = lcol[k]; } else { lc = lcol[l]; le = k; } while(lc>=0 && le>itag[lc]) lc = lnxt[lc]; if(le == itag[lc]) valores[lc] = custo+valores[lc]; return; } /*-----------------------------Fim da funcao preench---------------------------------*/ /*-------------------------Inicio da funcao elim-------------------------------------*/ /* Elimina a linha e coluna referente a barra Slack de ce e da cle elimina linha e coluna referentes as barras Slack e PV */ void elim(double valores[],int nn) { int i = 0; while( i < nb ) { if((itipo[i] != 0 && nn == 0) || (itipo[i] == 2 && nn == 1)) valores[i] = 1.e20; //Atribui um valor grande para eliminar linha e coluna i++; } return; } /*---------------------------- Fim da funcao elim-------------------------------------*/ //Data de atualizacao:02/06/03
C
/* * RandomMinute.c * * Created on: 07.03.2012 * Author: maersk */ #include "RandomMinute.h" #include <stdlib.h> static int b; void RandomMinute_Create(int bound) { b = bound; srand(10); } int RandomMinute_GetImpl(void) { // return (rand() % (2 * b + 1)) - b; return b - rand() % (b * 2 + 1); } int (*RandomMinute_Get)(void) = RandomMinute_GetImpl;
C
#include "io_poll.h" #include "io_poll_impl.h" #if defined(HAVE_EPOLL) #include <corelib/bin.h> #include <corelib/close.h> #include <corelib/error.h> #include <sys/epoll.h> /* iop->pd_in unused * iop->pd_out used to hold epollfd structured returned from epoll_wait() */ static int iop_epoll_init(struct io_poll *iop) { struct array ep_ofds; int efd = -1; int es = 0; array_zero(&ep_ofds); efd = epoll_create(16); if (efd == -1) { es = errno; goto FAIL; } if (!array_init(&ep_ofds, 16, sizeof(struct epoll_event))) { es = errno; goto FAIL; } array_zero(&iop->pd_in); iop->pd_out = ep_ofds; iop->pfd = efd; return 1; FAIL: if (array_data(&ep_ofds)) array_free(&ep_ofds); if (efd != -1) close(efd); errno = es; return 0; } static int iop_epoll_free(struct io_poll *iop) { array_free(&iop->pd_out); return (close(iop->pfd) != -1); } static int iop_epoll_add(struct io_poll *iop, const struct io_pollfd *pfd) { struct epoll_event ev; struct io_pollfd dummy_pfd; struct io_pollfd *ifd = 0; unsigned long ind; unsigned long len; int es; int r; dummy_pfd.fd = -1; dummy_pfd.events = 0; bin_zero(&ev, sizeof(struct epoll_event)); /* if necessary, allocate extra space on arrays to hold structures */ len = array_size(&iop->fds); if (!io_poll_find_unused(&iop->fds, &ind)) { if (!array_cat(&iop->fds, &dummy_pfd)) { es = errno; goto FAIL; } if (!array_cat(&iop->rfds, &dummy_pfd)) { es = errno; goto FAIL; } if (!array_cat(&iop->pd_out, &ev)) { es = errno; goto FAIL; } ind = len; } ifd = array_index(&iop->fds, ind); ifd->fd = pfd->fd; ifd->events = pfd->events; if (ifd->events & IO_POLL_READ) ev.events |= EPOLLIN; if (ifd->events & IO_POLL_WRITE) ev.events |= EPOLLOUT; ev.data.fd = ifd->fd; r = epoll_ctl(iop->pfd, EPOLL_CTL_ADD, ifd->fd, &ev); if (r == -1) { es = errno; goto FAIL; } return 1; FAIL: if (ifd) ifd->fd = -1; errno = es; return 0; } static int iop_epoll_del(struct io_poll *iop, int fd) { struct epoll_event ev; struct io_pollfd *ifd = 0; unsigned long ind; int sfd; if (!io_poll_find(&iop->fds, fd, &ind)) return 0; ifd = array_index(&iop->fds, ind); sfd = ifd->fd; ifd->fd = -1; ifd->events = 0; /* ev is ignored but in kernels < 2.6.9, ev must be non-null */ return epoll_ctl(iop->pfd, EPOLL_CTL_DEL, sfd, &ev) != -1; } static int iop_epoll_wait(struct io_poll *iop, int64 t) { struct epoll_event *ep_out; struct io_pollfd rfd; int max; int ind; int r; max = array_size(&iop->pd_out); ep_out = (struct epoll_event *) array_data(&iop->pd_out); r = epoll_wait(iop->pfd, ep_out, max, t); if (r == -1) return 0; array_trunc(&iop->rfds); for (ind = 0; ind < r; ++ind) { rfd.fd = ep_out[ind].data.fd; rfd.events = 0; if (ep_out[ind].events & EPOLLIN) rfd.events |= IO_POLL_READ; if (ep_out[ind].events & EPOLLOUT) rfd.events |= IO_POLL_WRITE; if (ep_out[ind].events & EPOLLERR) rfd.events |= IO_POLL_ERROR; if (ep_out[ind].events & EPOLLHUP) rfd.events |= IO_POLL_EOF; if (!array_cat(&iop->rfds, &rfd)) return -1; /* impossible */ } return 1; } static const struct io_poll_core iop_core_epoll = { &iop_epoll_init, &iop_epoll_free, &iop_epoll_add, &iop_epoll_del, &iop_epoll_wait, }; const struct io_poll_core *io_poll_core_epoll = &iop_core_epoll; #else const struct io_poll_core *io_poll_core_epoll = 0; #endif
C
#include <cs50.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s key\n", argv[0]); return 1; } string key = argv[1]; if (strlen(key) != 26) { printf("Key must contain 26 characters.\n"); return 1; } for (int i = 'A'; i <= 'Z';i++) { int f = 0; for (int j = 0, len = strlen(key); j < len; j++) { if (key[j] == i || key[j] == i + ('a' - 'A')) { f = 1; break; } } if (!f) { printf("Key must contain 26 characters.\n"); return 1; } } string plain = get_string("plaintext: "); printf("ciphertext: "); for (int i = 0, len = strlen(plain); i < len; i++) { char c = plain[i]; if (islower(c)) { printf("%c", tolower(key[c - 'a'])); } else if (isupper(c)) { printf("%c", toupper(key[c - 'A'])); } else { printf("%c", c); } } printf("\n"); return 0; }
C
#pragma once struct TreeNode { int value; TreeNode *left; TreeNode *right; }; struct Tree { TreeNode *root; }; Tree *createTree(); void add(Tree *root, int value); bool exists(Tree *root, int value); void remove(Tree *&root, int value); void printSymmetrically(Tree *tree); void printAntiSymmetrically(Tree *tree); void deleteBst (Tree *tree);
C
#include "avl.h" // Todas as funções implementadas por Janaine Rodrigues noLista* buscaAVL(avl *r, unsigned long naochave) { if(r == NULL) return NULL; if(naochave == r->naochave) return r->regs; if(naochave < r->naochave) return buscaAVL(r->esq, naochave); else return buscaAVL(r->dir, naochave); } int insereAVL(avl **r, unsigned long naochave, unsigned long bloco, unsigned short int registro) { if((*r) == NULL){ //arvore vazia cria novo nó *r = criaNoAVL(naochave, bloco, registro); return 1; //retorna 1 para informar que a subarvore cresceu. } int temp = 0; if(naochave == (*r)->naochave){ /* printf("naochave repetido: %lu\n", naochave); */ insereNoLista(&((*r)->regs), naochave, bloco, registro); } if(naochave < (*r)->naochave) temp -= insereAVL(&((*r)->esq), naochave, bloco, registro); //Cresce para a esquerda else temp = insereAVL(&((*r)->dir), naochave, bloco, registro); //Cresce para a direita if(temp){//Se houve crescimento (*r)->fb += temp; //Atualiza fb do no return balanceamento(r); //Realiza balanceamento da arvore } return 0; } avl *criaNoAVL(unsigned long naochave, unsigned long bloco, unsigned short int registro) { avl *newNode = malloc(sizeof(avl)); newNode->naochave = naochave; newNode->regs = NULL; insereNoLista(&(newNode->regs), naochave, bloco, registro); newNode->dir = NULL; newNode->esq = NULL; newNode->fb = 0; return newNode; } int balanceamento(avl **r) { if((*r)->fb == 2){ if(((*r)->dir)->fb == -1){ rotacaoDir(&((*r)->dir)); } rotacaoEsq(r); }else{ if((*r)->fb == -2){ if(((*r)->esq)->fb > 0) rotacaoEsq(&((*r)->esq)); rotacaoDir(r); }else{ if((*r)->fb != 0) return 1; } } return 0; } void rotacaoEsq(avl **r) { if((*r) == NULL) return; avl *aux = (*r)->dir; (*r)->dir = aux->esq; aux->esq = *r; if ((*r)->fb == 2) {//Rotacao simples if (aux->fb == 2) { (*r)->fb = -1; aux->fb = 0; }else if (aux->fb == 1) { (*r)->fb = 0; aux->fb = 0; }else{ (*r)->fb = 1; aux->fb = -1; } }else{ //Rotacao dupla if (aux->fb == -1) { (*r)->fb = 0; aux->fb = -2; }else if (aux->fb == 1){ (*r)->fb = -1; aux->fb = -1; }else{ (*r)->fb = 0; aux->fb = -1; } } (*r) = aux; } void rotacaoDir(avl **r) { if((*r) == NULL) return; avl *aux = (*r)->esq; (*r)->esq = aux->dir; aux->dir = *r; if ((*r)->fb == -2) { //Rotacao simples if (aux->fb == -2){ (*r)->fb = 1; aux->fb = 0; }else if (aux->fb == -1) { (*r)->fb = 0; aux->fb = 0; }else{ (*r)->fb = -1; aux->fb = 1; } }else{ //Rotacao dupla if (aux->fb == 1) { (*r)->fb = 0; aux->fb = 2; }else if (aux->fb == -1) { (*r)->fb = 1; aux->fb = 1; }else{ (*r)->fb = 0; aux->fb = 1; } } (*r) = aux; }
C
/* Exercise 3-1. Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time. Version: 1 Date: April 19, 2018 Author: BornTuft */ #include <stdio.h> int binsearchExercise (int x, int v[], int n); int binsearchOriginal (int x, int v[], int n); int main (void) { int x = 9; int n = 9; int v[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; printf("%d", binsearchExercise(x, v, n)); return 0; } int binsearchExercise (int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low+high) / 2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else return mid; /* found match */ } return -1; /* no match */ } int binsearch (int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low+high) / 2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else return mid; /* found match */ } return -1; /* no match */ }
C
/******************************************************************************/ /******************************************************************************/ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <inttypes.h> /* qsort() u64s numerically */ static int u64cmp (const void * left, const void * right) { if (*(const uint64_t *)left > *(const uint64_t *)right) return 1; if (*(const uint64_t *)left < *(const uint64_t *)right) return -1; return 0; } /* Generate summary statistics from a list of u64s */ static void summarize(uint64_t *list, int n, uint64_t *count, uint64_t *avg, uint64_t *median, uint64_t *stddev, uint64_t *variance) { qsort(list, n, sizeof(uint64_t), u64cmp); uint64_t p25 = list[ n / 4 ]; uint64_t p50 = list[ n / 2 ]; uint64_t p75 = list[ n - (n / 4)]; uint64_t iqr = p75 - p25; /* Use the standard interquartile range rule for outlier detection */ int64_t low = p25 - (iqr * 1.5); if (iqr > p25) { low = 0; } *avg = low; int64_t hi = p75 + (iqr * 1.5); /* Ignore overflow as we have plenty of room at the top */ *count = 0; uint64_t sum = 0; uint64_t sum_squares = 0; uint64_t min = 0xFFFFFFFF; uint64_t max = 0; int i; for (i = 0; i < n; i++) { int64_t value = list[ i ]; if (value < low || value > hi) { continue; } (*count)++; sum += value; sum_squares += value * value; if (value < min) { min = value; } if (value > max) { max = value; } } *variance = sum_squares - (sum * sum); *median = p50; if (*count == 0) { *avg = 0; } else { *avg = sum / *count; } if (*count <= 1) { *stddev = 0; } else { *stddev = sqrt((*count * *variance) / (*count * (*count - 1))); } } inline static uint64_t rdtsc(){ unsigned int bot, top; __asm__ __volatile__ ("rdtsc" : "=a" (bot), "=d" (top)); return ((uint64_t) top << 32) | bot; } /******************************************************************************/ /******************************************************************************/
C
/* ** EPITECH PROJECT, 2019 ** my_sort_int_array.c ** File description: ** task06 */ void my_sort_int_array(int *array, int size) { int storage; for (int o = 0; o < size - 1; o++) { if (array[o + 1] < array[o]) { storage = array[o + 1]; array[o + 1] = array[o]; array[o] = storage; o = -1; } } }
C
#include <stdio.h> int main() { double total_pembelian, discount = 0; printf ("Total Pembelian = Rp "); scanf("%lf",&total_pembelian); if (total_pembelian >= 100000) { discount = 0.05 * total_pembelian; printf("Besarnya discount =Rp %.2lf\n",discount ); } else if (total_pembelian < 100000) { printf("Mohon maaf anda tidak mendapatkan discount\n"); } }
C
/*---------------------------------------------------------------------------- * Author: Eshwar * Created on 4 September, 2017, 8:37 PM * Description: Linear queue *----------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #define M 20 // queue size void enQue(int data); // enqueue at rear int deQue(); // dequeue from front int isFull(); int isEmpty(); void display(); int queue[M], front=0, rear=0,data; void enQue(int data) { if(isFull()) { printf("\nQueue full!"); return; } else { queue[rear]=data; rear++; } } int deQue() { data=queue[front]; front++; return data; } void display() { int i; printf("\nQUEUE :"); for(i=front;i<rear;i++) printf(" %d",queue[i]); } int isFull() { if(rear==M) return 1; return 0; } int isEmpty() { if(front==rear) return 1; return 0; }
C
/********************************************************************************* * * problem_ten.h * Author: Mohamed Mostafa Abdel Karim * Mohamed Hassan * ********************************************************************************/ /****************************[Problem Description]**************************************************** * * Given a number "N" find four integer numbers a, b, c and d such that b, c and d are prime numbers, * and a & N are odd knowing that a^3 + b^3 + c^3 + d^3 = N and a <= b <= c <= d * * Sample Input: N = 161 * Sample Output: Numbers are 1, 2, 3 and 5 * * @return: Array containing a, b, c and d respectively that satisfy the equation * * Note: 1 <= N <= 10^18 * *******************************************************************************************************/ #include <stdio.h> #include "problem_nine.h" static unsigned long prime_numbers[4]= {1,2,0,0}; int CheckPrimeNumber(unsigned long num) { unsigned long k=2; for(k = 2 ; k<=num-1; k++) { if(num%k == 0) { return 0; } } return 1; } int* findPrimeNumbers(int N) { unsigned long d=5; unsigned long c=3; unsigned long c_temp; unsigned short end_flag=0; N-=9; /* Guessing d number */ while( (d*d*d) < N ) { do { d+=2; } while( !(CheckPrimeNumber(d)) ); } do { d-=2; } while( !(CheckPrimeNumber(d)) ); /* Guessing c number */ while( (c*c*c) <= (N - (d*d*d)) ) { do { c+=2; } while( !(CheckPrimeNumber(c)) ); } do { c-=2; } while( !(CheckPrimeNumber(c)) ); /* Get the true c and d numbers */ if(!(((c * c * c) + (d*d*d) ) == N) ) { while(d>3) { c_temp=c; do { d-=2; } while( !(CheckPrimeNumber(d)) ); while ( c_temp <= d ) { if( ( (c_temp * c_temp * c_temp) + (d*d*d) ) == N) { prime_numbers[2]=c_temp; prime_numbers[3]=d; end_flag=1; break; } else { do { c_temp+=2; } while( !(CheckPrimeNumber(c)) ); } } if(end_flag == 1) { break; } } } else{ prime_numbers[2]=c; prime_numbers[3]=d; end_flag=1; } if(end_flag==0) { printf("N is Wrong Number\n"); } return &prime_numbers; } int main(void) { int* ptrToPrimes = findPrimeNumbers(924849); printf("The numbers are: %d, %d, %d and %d\n",ptrToPrimes[0],ptrToPrimes[1],ptrToPrimes[2],ptrToPrimes[3]); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* is_correct.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gaida <gaida@student.42tokyo.jp> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/20 02:50:21 by gaida #+# #+# */ /* Updated: 2020/09/20 16:25:44 by hnohara ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdbool.h> int count_from_front(int pat[]) { int i; int count; int max_number; i = 0; count = 0; max_number = 0; while (i < 4) { if (pat[i] > max_number) { max_number = pat[i]; count++; } i++; } return (count); } int count_from_back(int pat[]) { int i; int count; int max_number; i = 3; count = 0; max_number = 0; while (i >= 0) { if (pat[i] > max_number) { max_number = pat[i]; count++; } i--; } return (count); } bool is_correct_line(int pat[], int front, int back) { int front_cnt; int back_cnt; front_cnt = count_from_front(pat); back_cnt = count_from_back(pat); if (front_cnt == front && back_cnt == back) return (true); else return (false); } bool is_correct(int pat[][4], int input[]) { int i; int arr[4]; i = 0; while (i < 4) { arr[0] = pat[0][i]; arr[1] = pat[1][i]; arr[2] = pat[2][i]; arr[3] = pat[3][i]; if (!is_correct_line(arr, input[i], input[i + 4])) return (false); i++; } i = 0; while (i < 4) { if (!is_correct_line(pat[i], input[i + 8], input[i + 12])) return (false); i++; } return (true); }
C
#include "ft_strlen.c" #include <stdio.h> int main() { char a[13] = "Hello World!"; int b; b = ft_strlen(a); printf("%d",b); }
C
#define _CRT_SECURE_NO_WARNINGS 1 //дһ 1 100 гֶٸ9 //#include <stdio.h> // //int main() //{ // int m = 0; // int n = 0; // int i = 0; // int count = 0; // for (i = 1; i <= 100; i++) // { // m = i / 10; // n = i % 10; // if (m > 8 && m < 10) // { // printf("%d ", i); // count++; // } // if (n > 8 && n < 10) // { // printf("%d ", i); // count++; // } // } // printf("\ncount=%d\n", count); // // return 0; //} //1 / 1 - 1 / 2 + 1 / 3 - 1 / 4 + 1 / 5 + 1 / 99 - 1 / 100 ֵӡ #include <stdio.h> int main() { int i = 0; int j = 0; double sum1 = 0; double sum2 = 0; double sum = 0; for (i = 1; i <= 100; i+=2) { sum1 += 1.0 / i; } for (j = 2; j <= 100; j+=2) { sum2 += 1.0 / j; } sum = sum1 - sum2; printf("%f\n", sum); return 0; }
C
#include<stdio.h> void main() { int n; printf("Enter number limit:"); scanf("%d", &n); for(int i=2; i<=n; i++){ if(i==2||i==3||i==5||i==7) { printf("\n%d\n", i); } else{ if(i%2!=0&&i%3!=0&&i%4!=0&&i%5!=0&&i%6!=0&&i%7!=0&&i%8!=0&&i%9!=0){ printf("\n\n%d\n", i); } } } }
C
#define _CRT_SECURE_NO_WARNINGS # include<stdio.h> # include <math.h> # include<stdlib.h> # include<time.h> #define ROW 3 #define COL 3 char g_board[ROW][COL]; void Init()//ʼ { srand((unsigned int)time(0)); for (int row = 0; row < ROW; row++) { for (int col = 0; col < COL; col++) { g_board[row][col] = ' '; } } } void print()//ӡ { for (int row = 0; row < ROW; row++) { printf("%c |%c |%c |", g_board[row][0], g_board[row][1], g_board[row][2]); printf("\n"); if (row < ROW) { printf("|||"); printf("\n"); } if (row == 2) { printf(" | | "); } /*printf(" - - -\n"); printf(" | | |\n"); */ } } void playermove() { printf("ӣ\n"); while (1) { printf("(row col)\n"); int row; int col; scanf("%d%d", &row, &col); if (row < 0 || row >= ROW || col < 0 || col >= COL) { printf("\n"); continue; } if (g_board[row][col] != ' ') { printf("ǰλѾ\n"); continue; } g_board[row][col] = '*';// break; } } void computermove() { printf("ӣ\n"); while (1) {//ӲѭõͬĽΪʱ̫ˣӦ÷ڳʼĿʼ int row = rand() % ROW; int col = rand() % COL; if (g_board[row][col] != ' ') { printf("\n"); continue; } g_board[row][col] = 'o'; break; } } char judgewinner() { for (int row = 0; row < ROW; row++) { if (g_board[row][0] == g_board[row][1] && g_board[row][1] == g_board[row][2] && g_board[row][0] != ' ') { return g_board[row][0];//ȶұ֤ǿո } } for (int col = 0; col < COL; col++) { if (g_board[0][col] == g_board[1][col] && g_board[1][col] == g_board[2][col] && g_board[0][col] != ' ') { return g_board[0][col]; } } if (g_board[0][0] == g_board[1][1] && g_board[1][1] == g_board[2][2] && g_board[0][0] != ' ') { return g_board[0][0]; } if (g_board[2][0] == g_board[1][1] && g_board[1][1] == g_board[0][2] && g_board[2][0] != ' ') { return g_board[2][0]; } if (isfull()){ return 'q'; } return ' '; } int isfull() { for (int row = 0; row < ROW; row++){ for (int col = 0; col < COL; col++){ if (g_board[row][col] == ' '){ return 0; } } } return 1; } int main() { Init(); char winner; while (1) { print(); playermove(); winner = judgewinner(); if (winner != ' ') { break;//ѭʤѾ } computermove(); winner = judgewinner(); if (winner != ' ') { break; } } if (winner == '*') { printf("ʤ\n"); } else if (winner == 'o') { printf("ʤ\n"); } else if (winner == 'q') { printf(""); } system("pause"); return 0; }
C
#include<stdio.h> //void pokaz(void (* fw)(char *), char * lan); void map( int(*pfn)(int) ,int tab[],int size); int add4(int val); int main(){ int tab[10] = {0,1,2,3,4,5,6,7,8,9}; map(add4,tab,sizeof(tab)/sizeof(int)); puts("Wyswietl elementy po modyfikacji"); for(int i=0;i<sizeof(tab)/sizeof(int); i++){ printf("%i ",tab[i]); } } //Przyklad jak zrobic map w c void map( int(*pfn)(int) ,int tab[],int size){ for (int i = 0; i<size ; i++){ tab[i] = pfn(tab[i]); } } int add4(int val){ return val + 4; }
C
/* * profile.c -- For timing and event counting. * * ********************************************** * CMU ARPA Speech Project * * Copyright (c) 1996 Carnegie Mellon University. * ALL RIGHTS RESERVED. * ********************************************** * * HISTORY * * 01-Aug-96 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Changed timer_ names to cyctimer_ (for cycle counter). * Added timing_ structures and functions using system calls for timing. * * 13-Dec-95 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Added ifdefs around cyctimer_print_all and cyctimer_print_all_norm. * * 27-Nov-95 M K Ravishankar (rkm@cs.cmu.edu) at Carnegie Mellon University * Created from Sphinx-II version. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #if (! WIN32) #include <sys/time.h> #include <sys/resource.h> #else #include <windows.h> #include <time.h> #endif #include "profile.h" #include "err.h" #include "ckd_alloc.h" #if (ALPHA_OSF1) extern uint32 rpcc(); /* On an alpha, use the RPCC instruction */ static int32 mhz = 0; /* Guess regarding clock rate on machine (in MHz) */ #endif typedef struct { char *name; uint32 start_time; float accum_time; } cyctimer_t; static cyctimer_t *timer = NULL; static int32 n_timer = 0; #define MAX_TIMER 30 #define ACCUM_SCALE 0.001 typedef struct { char *name; uint32 count; } ctr_t; static ctr_t *ctr = NULL; static int32 n_ctr = 0; #define MAX_CTR 30 int32 counter_new (char *name) { if (! ctr) ctr = (ctr_t *) ckd_calloc (MAX_CTR, sizeof(ctr_t)); if (n_ctr >= MAX_CTR) { E_WARN("#counters (%d) exceeded\n", MAX_CTR); return -1; } ctr[n_ctr].name = (char *) ckd_salloc (name); ctr[n_ctr].count = 0; return (n_ctr++); } void counter_increment (int32 id, int32 inc) { if ((id < 0) || (id >= MAX_CTR)) return; ctr[id].count += inc; } void counter_reset (int32 id) { if ((id < 0) || (id >= MAX_CTR)) return; ctr[id].count = 0; } void counter_reset_all ( void ) { int32 i; for (i = 0; i < n_ctr; i++) counter_reset (i); } static int32 get_namelen ( void ) { int32 i, len; len = 0; for (i = 0; i < n_ctr; i++) if (len < strlen(ctr[i].name)) len = strlen(ctr[i].name); for (i = 0; i < n_timer; i++) if (len < strlen(timer[i].name)) len = strlen(timer[i].name); return (len); } void counter_print_all (FILE *fp) { int32 i; if (n_ctr > 0) { fprintf (fp, "CTR:"); for (i = 0; i < n_ctr; i++) fprintf (fp, "[%s %10d]", ctr[i].name, ctr[i].count); fprintf (fp, "\n"); } } #if (ALPHA_OSF1) static int32 clock_speed (int32 dummy) { int32 i, j, k, besti, bestj, diff; uint32 rpcc_start, rpcc_end; struct rusage start, stop; float64 t; //1/20/04 Ed //getrusage (RUSAGE_SELF, &start); rpcc_start = rpcc(); for (i = 0; i < 100000000; i++) if (i > dummy) return (i); rpcc_end = rpcc(); //1/20/04 Ed //getrusage (RUSAGE_SELF, &stop); t = (stop.ru_utime.tv_sec - start.ru_utime.tv_sec) + ((stop.ru_utime.tv_usec - start.ru_utime.tv_usec) * 0.000001); mhz = ((rpcc_end - rpcc_start) / t) * 0.000001 + 0.5; diff = (int32)0x7fffffff; for (i = 100; i <= 1000; i += 100) { for (j = 1; j <= 10; j++) { k = i/j - mhz; if (k < 0) k = -k; if (k < diff) { diff = k; besti = i; bestj = j; } } } mhz = besti/bestj; E_INFO("%d ticks in %.3f sec; machine clock rate = %d MHz\n", rpcc_end - rpcc_start, t, mhz); return 0; } #endif int32 cyctimer_new (char *name) { #if (ALPHA_OSF1) { int32 dummy; dummy = name[0] | ((int32) 0x70000000); if (mhz == 0) clock_speed (dummy); } if (! timer) timer = (cyctimer_t *) ckd_calloc (MAX_TIMER, sizeof(cyctimer_t)); if (n_timer >= MAX_TIMER) { E_WARN("#timers (%d) exceeded\n", MAX_TIMER); return -1; } timer[n_timer].name = (char *) ckd_salloc (name); timer[n_timer].accum_time = 0.0; return (n_timer++); #else return -1; #endif } void cyctimer_resume (int32 id) { #if (ALPHA_OSF1) if ((id < 0) || (id >= MAX_TIMER)) return; timer[id].start_time = rpcc(); #endif } void cyctimer_pause (int32 id) { #if (ALPHA_OSF1) if ((id < 0) || (id >= MAX_TIMER)) return; timer[id].accum_time += (rpcc() - timer[id].start_time) * ACCUM_SCALE; #endif } void cyctimer_reset (int32 id) { if ((id < 0) || (id >= MAX_TIMER)) return; timer[id].accum_time = 0.0; } void cyctimer_reset_all ( void ) { int32 i; for (i = 0; i < n_timer; i++) cyctimer_reset (i); } void cyctimer_print_all (FILE *fp) { #if (ALPHA_OSF1) int32 i; char fmtstr[1024]; if (n_timer > 0) { fprintf (fp, "PROFILING TIMERS:\n"); sprintf (fmtstr, " TMR: %%-%ds %%10d\n", get_namelen()); for (i = 0; i < n_timer; i++) fprintf (fp, fmtstr, timer[i].name, (int32)(timer[i].accum_time)); } #endif } float64 cyctimer_get_sec (int32 id) { #if (ALPHA_OSF1) float64 t; t = (timer[id].accum_time / ACCUM_SCALE) / (1000000.0 * mhz); /* Sec */ return (t); #else return (0.0); #endif } void cyctimer_print_all_norm (FILE *fp, float64 norm_sec, int32 norm_id) { #if (ALPHA_OSF1) int32 i; float64 t; if (n_timer > 0) { fprintf (fp, "TMR:"); for (i = 0; i < n_timer; i++) { t = (timer[i].accum_time / ACCUM_SCALE) / (1000000.0 * mhz); /* Sec */ fprintf (fp, "[%s %6.1fs %5.1fx %3.0f%%]", timer[i].name, t, t / norm_sec, (timer[i].accum_time * 100.0) / timer[norm_id].accum_time); } fprintf (fp, "\n"); } #endif } #if (WIN32) #define TM_LOWSCALE 1e-7 #define TM_HIGHSCALE (4294967296.0 * TM_LOWSCALE); static float64 make_sec (FILETIME *tm) { float64 dt; dt = tm->dwLowDateTime * TM_LOWSCALE; dt += tm->dwHighDateTime * TM_HIGHSCALE; return (dt); } #else static float64 make_sec (struct timeval *s) { return (s->tv_sec + s->tv_usec * 0.000001); } #endif /* * Obtain and initialize a timing module */ timing_t *timing_new ( void ) { timing_t *tm; #if (ALPHA_OSF1) { int32 dummy; dummy = (dummy & 0x000000ff) | ((int32) 0x70000000); if (mhz == 0) clock_speed (dummy); } #endif tm = (timing_t *) ckd_calloc (1, sizeof(timing_t)); tm->t_elapsed = 0.0; tm->t_cpu = 0.0; return tm; } void timing_start (timing_t *tm) { #if (! _SUN4) #if (! WIN32) struct timeval e_start; /* Elapsed time */ #if (! _HPUX_SOURCE) struct rusage start; /* CPU time */ /* Unix but not HPUX */ //1/20/04 Ed //getrusage (RUSAGE_SELF, &start); tm->start_cpu = make_sec (&start.ru_utime) + make_sec (&start.ru_stime); #endif /* Unix + HP */ //1/20/04 Ed // gettimeofday (&e_start, 0); tm->start_elapsed = make_sec (&e_start); #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes (pid, &t_create, &t_exit, &kst, &ust); tm->start_cpu = make_sec (&ust) + make_sec (&kst); tm->start_elapsed = (float64)clock() / CLOCKS_PER_SEC; #endif #endif } void timing_stop (timing_t *tm) { #if (! _SUN4) float64 dt_cpu, dt_elapsed; #if (! WIN32) struct timeval e_stop; /* Elapsed time */ #if (! _HPUX_SOURCE) struct rusage stop; /* CPU time */ /* Unix but not HPUX */ //1/20/04 Ed //getrusage (RUSAGE_SELF, &stop); dt_cpu = make_sec (&stop.ru_utime) + make_sec (&stop.ru_stime) - tm->start_cpu; #else dt_cpu = 0.0; #endif /* Unix + HP */ //1/20/04 Ed //gettimeofday (&e_stop, 0); dt_elapsed = (make_sec (&e_stop) - tm->start_elapsed); #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes (pid, &t_create, &t_exit, &kst, &ust); dt_cpu = make_sec (&ust) + make_sec (&kst) - tm->start_cpu; dt_elapsed = ((float64)clock() / CLOCKS_PER_SEC) - tm->start_elapsed; #endif tm->t_cpu += dt_cpu; tm->t_elapsed += dt_elapsed; tm->t_tot_cpu += dt_cpu; tm->t_tot_elapsed += dt_elapsed; #endif } void timing_reset (timing_t *tm) { tm->t_cpu = 0.0; tm->t_elapsed = 0.0; }
C
#include<stdio.h> #include<math.h> int main() { int a[50]; int n; int sum=0; float average; printf("enter the value of n\n"); scanf("%d",&n); printf("enter the elements of array\n"); for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n;i++) { sum=sum+a[i]; } average=sum/n; printf("sum of n numbers is %d \n",sum); printf("average of n numbers is %f \n",average); } OUTPUT enter the value of n 5 enter the elements of array 1 2 3 4 5 sum of n numbers is 15 average of n numbers is 3.000000 ------------------ (program exited with code: 0) Press any key to continue . . .
C
#include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/device.h> #include <linux/wait.h> #include <linux/slab.h> #include <linux/semaphore.h> #include <linux/sched.h> #include <linux/uaccess.h> struct generic_device { wait_queue_head_t inq, outq; struct fasync_struct *fa; struct semaphore sem; char *rp, *wp; int buffer_size; char *buffer, *end; struct cdev cdev; struct class *cl; dev_t dev; }; static int Open(struct inode *inode, struct file *filp) { struct generic_device *dev = container_of(inode->i_cdev, struct generic_device, cdev); if(!dev) return -EFAULT; printk(" %s \n", __func__); filp->private_data = dev; return nonseekable_open(inode, filp); } static int Close(struct inode *inode, struct file *filp) { struct generic_device *dev = filp->private_data; /* if(dev) { kfree(dev->buffer); kfree(dev); filp->private_data = NULL; } */ printk(" %s \n", __func__); return 0; } static int Read(struct file *filp, char __user *buf, size_t count, loff_t *off) { struct generic_device *dev = filp->private_data; if(!dev) return -ENOTTY; if(down_interruptible(&dev->sem)) return -ERESTARTSYS; while(dev->rp == dev->wp)// This while loop is necessary as the different process might wait on the same wait queue at the different place of the driver , and if one process calls the wake_up_interruptible(), all the process on the wait queue will wake up even though the condition is false. {// Data is not yet ready. up(&dev->sem); //Check if the file is opened in O_NONBLOCK mode, so, that we can return -EAGAIN. if(filp->f_flags & O_NONBLOCK) return -EAGAIN; //Lets sleep untill the data is ready as it is opened in blocking mode. if(wait_event_interruptible(dev->inq, dev->rp != dev->wp)) return -ERESTARTSYS; if(down_interruptible(&dev->sem)) return -ERESTARTSYS; } //Now read the data as it is ready to read. if(dev->wp > dev->rp) count = min(count, (size_t)(dev->wp - dev->rp)); else // dev->wp is wrapped up count = min(count, (size_t)(dev->end - dev->rp)); if(copy_to_user(buf, dev->rp, count)) { up(&dev->sem); return -EFAULT; } dev->rp += count; printk(" %d bytes are read from function %s of process %s \n", count, __func__, current->comm); if(dev->rp == dev->end)// Wrap up the pointer. dev->rp = dev->buffer; up(&dev->sem); wake_up_interruptible(&dev->outq); return count; } int spacefree(struct generic_device *dev) { if(dev->rp == dev->wp) return dev->buffer_size -1; return ((dev->rp + dev->buffer_size - dev->wp) % dev->buffer_size) - 1; } int get_write_space(struct generic_device *dev, struct file *filp) { while(spacefree(dev) == 0) { DEFINE_WAIT(wait); up(&dev->sem); if(filp->f_flags & O_NONBLOCK) return -EAGAIN; prepare_to_wait(&dev->outq, &wait, TASK_INTERRUPTIBLE); if(spacefree(dev) == 0) schedule(); finish_wait(&dev->outq, &wait); if (signal_pending(current)) return -ERESTARTSYS; if(down_interruptible(&dev->sem)) return -ERESTARTSYS; } return 0; } static int Write(struct file *filp, const char __user *buf, size_t count, loff_t *pos) { int result; struct generic_device *dev = filp->private_data; if(down_interruptible(&dev->sem)) return -ERESTARTSYS; result = get_write_space(dev, filp); if(result) return result; // Space is present. count = min(count, (size_t) spacefree(dev)); if(dev->wp > dev->rp) count = min(count, (size_t)(dev->end - dev->wp)); else // The pointer is wrapped up count = min(count, (size_t)(dev->rp - dev->wp -1)); if(copy_from_user(dev->wp, buf, count)) { up(&dev->sem); return -EFAULT; } dev->wp += count; printk(" %d bytes are written from function %s of process %s \n", count, __func__, current->comm); if(dev->wp == dev->end) dev->wp = dev->buffer; up(&dev->sem); //Wake up for any writers. wake_up_interruptible(&dev->inq); if(dev->fa) kill_fasync(&dev->fa, SIGIO, POLL_IN); return count; } static int Fasync(int fd, struct file *filp, int mode) { struct generic_device *dev = filp->private_data; printk(" %s \n", __func__); return fasync_helper(fd, filp, mode, &dev->fa); } struct file_operations fops = { .owner = THIS_MODULE, .open = Open, .read = Read, .write = Write, .release = Close, // .poll = Poll, .fasync = Fasync }; struct generic_device *gdevice = NULL; static int __init Init(void) { gdevice = kmalloc(sizeof(*gdevice), GFP_KERNEL); if(!gdevice) return -ENOMEM; alloc_chrdev_region(&gdevice->dev, 0, 1, "DEV"); gdevice->cl = class_create(THIS_MODULE, "ctrclass"); device_create(gdevice->cl, NULL, gdevice->dev, NULL, "comp"); cdev_init(&gdevice->cdev, &fops); cdev_add(&gdevice->cdev, gdevice->dev, 1); sema_init(&gdevice->sem, 1); init_waitqueue_head(&gdevice->inq); init_waitqueue_head(&gdevice->outq); gdevice->buffer_size = 10; gdevice->buffer = kmalloc(gdevice->buffer_size, GFP_KERNEL); gdevice->end = gdevice->buffer + gdevice->buffer_size; gdevice->rp = gdevice->wp = gdevice->buffer; gdevice->fa = NULL; printk(" %s \n",__func__); return 0; } static void __exit Exit(void) { printk(" %s \n",__func__); cdev_del(&gdevice->cdev); device_destroy(gdevice->cl, gdevice->dev); class_destroy(gdevice->cl); unregister_chrdev_region(gdevice->dev, 1); kfree(gdevice->buffer); kfree(gdevice); gdevice = NULL; } module_init(Init); module_exit(Exit); MODULE_LICENSE("GPL");
C
/*********************************************************************************/ /* Author : Islam Abdo */ /* Version : V01 */ /* Date : 17 OCT 2020 */ /*********************************************************************************/ #include "STD_TYPES.h" #include "BIT_MATH.h" #include "STK_interface.h" #include "STK_config.h" #include "STK_private.h" /* define Callback Global variable (pointer to function) */ static void (*STK_CallBack) (void); /* define variable for interval mode */ static u8 STk_u8ModeOfInterval; /************* Function OF Initialize clock Source of STK **************************/ /* Apply clock choice from configuration file * Disable SysTick Interrupt * Disable SysTick */ void STK_voidInit (void) { #if STK_CLOCK_SRC == STK_SRC_AHB /* Disable STK - Disable STK Interrupt - Set clock source AHB */ STK->CTRL = 0x00000004; #elif STK_CLOCK_SRC == STK_SRC_AHB_8 /* Disable STK - Disable STK Interrupt - Set clock source AHB/8 */ STK->CTRL = 0; #endif } /************* Function OF Set Busy Wait **************************/ /* This is function Like delay function stop the code until finish count * 9 count = 1 us * 900 counts = 100 us * 9000 counts = 1 ms * and so on ... */ void STK_voidSetBusyWait (u32 Copy_u32Ticks) { /* Load ticks to load register */ STK->LOAD = Copy_u32Ticks; /* Start Timer */ SET_BIT(STK->CTRL, 0); /* Wait till flag is raised */ while( (GET_BIT(STK->CTRL, 16)) == 0); /* Stop Timer */ CLR_BIT(STK->CTRL, 0); STK->LOAD = 0 ; STK->VAL = 0; } /************* Function OF Set Interval Single **************************/ /* this function take ticks and function to do after ticks finished and do it once * but don't stop the code until finish count * 9 count = 1 us * 900 counts = 100 us * 9000 counts = 1 ms * and so on ... */ void STK_voidSetIntervalSingle (u32 Copy_u32Ticks, void (*Copy_ptr) (void)) { /* Load ticks to load register */ STK->LOAD = Copy_u32Ticks; /* Start Timer */ SET_BIT(STK->CTRL, 0); /* Save CallBack */ STK_CallBack = Copy_ptr; /* Set Mode to Single */ STk_u8ModeOfInterval = STK_SINGLE_INTERVAL; /* Enable STk Interrupt */ SET_BIT(STK->CTRL, 1); } /************* Function OF Set Interval Periodic **************************/ /* this function take ticks and function to do after ticks finished and do it many time until you call a function stop it * but don't stop the code until finish count * 9 count = 1 us * 900 counts = 100 us * 9000 counts = 1 ms * and so on ... */ void STK_voidSetIntervalPeriodic (u32 Copy_u32Ticks, void (*Copy_ptr) (void)) { /* Load ticks to load register */ STK->LOAD = Copy_u32Ticks; /* Start Timer */ SET_BIT(STK->CTRL, 0); /* Save CallBack */ STK_CallBack = Copy_ptr; /* Set Mode to Period */ STk_u8ModeOfInterval = STK_PERIOD_INTERVAL; /* Enable STk Interrupt */ SET_BIT(STK->CTRL, 1); } /************* Function OF Stop Interval **************************/ void STK_voidStopInterval (void) { /* Disable STk Interrupt */ CLR_BIT(STK->CTRL, 1); /* Stop Timer */ CLR_BIT(STK->CTRL, 0); STK->LOAD = 0 ; STK->VAL = 0; } /************* Function OF Get Elaped Time **************************/ /* Return the number of thicks that done (load - val) */ u32 STK_u32GetElapedTime (void) { u32 Local_u32ElapsedTime; Local_u32ElapsedTime = STK -> LOAD - STK -> VAL; return Local_u32ElapsedTime; } /************* Function OF Get Remaining Time **************************/ /* Return the number of thicks that will count (remaining time) (val) */ u32 STK_u32GetRemainingTime (void) { u32 Local_u32ElapsedTime; Local_u32ElapsedTime = STK -> VAL; return Local_u32ElapsedTime; } /************* Function OF STK Interrupt **************************/ /* This is function call a STK_CallBack() function to do when interrupt */ void SysTick_Handler (void) { u8 Local_u8Temporary; if (STk_u8ModeOfInterval == STK_SINGLE_INTERVAL) { /* Stop Interval */ /* Disable STk Interrupt */ CLR_BIT(STK->CTRL, 1); /* Stop Timer */ CLR_BIT(STK->CTRL, 0); STK->LOAD = 0 ; STK->VAL = 0; } /* CallBack notification */ STK_CallBack(); /* Clear Interrupt Flag */ Local_u8Temporary = GET_BIT(STK->CTRL, 16); } /************* Function OF Delay_ms **************************/ /* This is function is call from (STK_voidSetBusyWait()), it is delay function stop the code until finish count * 9 count = 1 us * 900 counts = 100 us * 9000 counts = 1 ms * and so on ... */ void STK_voidDelay_ms (u32 Copy_u32Ticks) { /* convert from ms to us as * 1 ms = 9000 us */ Copy_u32Ticks *= 9000; STK_voidSetBusyWait(Copy_u32Ticks); } void STK_voidStartTimer(u32 Copy_u32Ticks) { /* Load ticks to load register */ STK->LOAD = Copy_u32Ticks; /* Start Timer */ SET_BIT(STK->CTRL, 0); } void STK_voidStopTimer(void) { /* Stop Timer */ CLR_BIT(STK->CTRL, 0); STK->LOAD = 0 ; STK->VAL = 0; }
C
#include <stdio.h> int main(){ int casos; scanf("%d",&casos); while(casos--){ int e, f, c, t = 0; scanf("%d%d%d", &e, &f, &c); if(c != 1){ e += f; while(e / c){ t += e / c; e = e / c + e % c; } } printf("%d\n",t); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> /* * This is my solution to Project Euler Problem 4. In this problem, the user * is asked to find the largest palindrome made from the product of two 3-digit * numbers. */ int main(int argv, char *argc[]) { int a[6]; int i, j, prod; int palindrome = 0; /*Run two for loops to compute the products of all 3 digit numbers*/ for(i = 1; i < 1000; i++){ for(j = 1; j < 1000; j++){ prod = i*j; /*Store 6th digit in the first array slot, 5th in the second, etc.*/ a[5] = prod%10; a[4] = (prod%100 - a[5])/10; a[3] = (prod%1000 - a[4] -a[5])/100; a[2] = (prod%10000 - a[3] - a[4] - a[5])/1000; a[1] = (prod%100000 - a[2] - a[3] - a[4] - a[5])/10000; a[0] = (prod%1000000 - a[1]- a[2] - a[3] - a[4] - a[5])/100000; /*This checks if it is a palindrome */ if((a[0] == a[5]) && (a[1] == a[4]) && (a[2] == a[3])){ /*If the new found product that is a palindrome is larger than our preexisting largest palindrome, replace it.*/ if(palindrome < prod){ palindrome = prod; } } } } printf("The largest palindrome made from the product of two 3-digit numbers is: %d \n", palindrome); }
C
#include <stdio.h> #define BOARD_SIZE 10 void display(char b[][BOARD_SIZE]) { char ch; int i, j; printf(" "); for (i = 0; i < BOARD_SIZE; i++) printf("%2d", i); printf("\n ---------------------\n"); for (i = 0; i < BOARD_SIZE; i++) { printf("%3d |", i); for (j = 0; j < BOARD_SIZE; j++) printf(" %c", b[i][j]); printf("\n"); } } int winCheck(char b[][BOARD_SIZE], int r, int c) { int i; int sum; char player = b[r][c]; int ri, ci; sum = 1; ri = r, ci = c - 1; while(ci != -1 && b[ri][ci] == player) { //(->) sum++; ci--; if(sum == 5) return 1; } ri = r, ci = c + 1; while(ci != BOARD_SIZE && b[ri][ci] == player) { //(->) sum++; ci++; if(sum == 5) return 1; } sum = 0; ri = 0, ci = c; while(ri != BOARD_SIZE && b[ri][ci] == player) { //(->Ʒ) sum++; ri++; if(sum == 5) return 1; } sum = 0; if(r > c) ri = r - c, ci = 0; else if(r == c) ri = 0, ci = 0; else ri = 0, ci = c - r; while(ri != BOARD_SIZE && ci != BOARD_SIZE && b[ri][ci] == player) { //밢(->Ʒ) sum++; ri++; ci++; if(sum == 5) return 1; } sum = 0; if((r + c) < BOARD_SIZE) ri = 0, ci = r + c; else ri = (r + c) - (BOARD_SIZE - 1), ci = BOARD_SIZE - 1; while(ri != BOARD_SIZE && ci != -1 && b[ri][ci] == player) { //밢(->Ʒ) sum++; ri++; ci--; if(sum == 5) return 1; } return 0; } void main() { char board[BOARD_SIZE][BOARD_SIZE]; char turn = 'X'; int win = 0; int r, c; int i, j; int count; for(i = 0; i < BOARD_SIZE; i++ ) for(j = 0 ; j < BOARD_SIZE; j++ ) board[i][j] = ' '; count = 1; display(board); do { printf("Player %c( ):", turn); scanf("%d %d", &r, &c); if(board[r][c] != ' ') continue; board[r][c] = turn; display(board); if(win = winCheck(board, r, c)) { printf("Player %c wins!\n", turn); break; } turn = (turn == 'X' ? 'O' : 'X'); count++; } while(count <= BOARD_SIZE * BOARD_SIZE); if(!win && count == BOARD_SIZE * BOARD_SIZE) printf("Nobody wins!\n"); }
C
#include <stdio.h> #include <stdlib.h> char a[20] = "rucham dzieci"; struct ArrayQueue { int *t; size_t size; // Liczba elementów w kolejsce size_t first; // Indeks pierwszego elementu w kolejce size_t capacity; // Wielkość tablicy }; struct ArrayQueue make_queue(size_t initial_capacity) { struct ArrayQueue Q; Q.capacity = initial_capacity; Q.first = -1; Q.t = (int*)malloc(initial_capacity * sizeof(int)); return Q; } int pop_first(struct ArrayQueue *q) { if(q->size >= 1) { q->size --; int ret = q->t[q->first]; q->first = (q->first+1)%(q->capacity); return ret; } else { return -1; } } void push_last(struct ArrayQueue *q, int value) { if (q->size+1 > q->capacity) { int new_size = 1; while(new_size <= q->capacity) new_size *= 2; int *newtab = (int*)malloc(new_size*sizeof(int)); int iter = 0; int help = q->size; while(q->size > 0) { newtab[iter] = pop_first(q); iter++; } free(q->t); q->t = newtab; q->capacity = new_size; q->size = help; q->first = 0; } q->t[(q->first+q->size)%q->capacity] = value; q->size++; } void peek(struct ArrayQueue *p) { printf("\n{"); for(int i = 0 ; i < p->capacity; i++) printf("%d ", p->t[i]); printf("}\n"); } int main() { struct ArrayQueue q = make_queue(1); for (int i = 0; i < 4; i++) push_last(&q, i); printf("%lu %lu %lu,", q.size, q.first, q.capacity); //peek(&q); for (int i = 0; i < 7; i++) { printf(" %i", pop_first(&q)); push_last(&q, i); } //peek(&q); push_last(&q, 0); //peek(&q); printf(", %i, %lu %lu %lu", pop_first(&q), q.size, q.first, q.capacity); }
C
#include "util.h" #include "data-structures.h" #include "interp.h" expr_t* expr; env_t* env; cont_t* cont; expval_t val; void value_of() { switch (expr->tag) { case const_exp: val = inj_num(expr->num); apply_cont(); break; case var_exp: val = apply_env(env, expr->var); apply_cont(); break; case diff_exp: { cont_t* new_cont = make_cont(diff_1_cont); new_cont->exp = expr->rhs; new_cont->env = env; new_cont->cont = cont; cont = new_cont; expr = expr->lhs; value_of(); break; } case zero_exp: { cont_t* new_cont = make_cont(zero_cont); new_cont->cont = cont; cont = new_cont; expr = expr->exp; value_of(); break; } case if_exp: { cont_t* new_cont = make_cont(if_cont); new_cont->then_e = expr->then_e; new_cont->else_e = expr->else_e; new_cont->env = env; new_cont->cont = cont; cont = new_cont; expr = expr->exp; value_of(); break; } case let_exp: { cont_t* new_cont = make_cont(let_cont); new_cont->var = expr->var; new_cont->body = expr->body; new_cont->env = env; new_cont->cont = cont; cont = new_cont; expr = expr->exp; value_of(); break; } case proc_exp: { proc_t proc = { expr->var, expr->body, env }; val = inj_proc(proc); apply_cont(); break; } case call_exp: { cont_t* new_cont = make_cont(rator_cont); new_cont->exp = expr->rhs; new_cont->env = env; new_cont->cont = cont; cont = new_cont; expr = expr->lhs; value_of(); break; } case letrec_exp: { env_t* new_env = extend_env(env, expr->p_name, inj_num(42)); proc_t proc = { expr->var, expr->body, new_env }; new_env->val = inj_proc(proc); env = new_env; expr = expr->exp; value_of(); break; } } } void apply_cont() { switch (cont->tag) { case end_cont: { printf("Finished computation.\n"); break; } case zero_cont: { if (val.tag != num_val) abort("Expected numerical value in zero?"); cont = cont->cont; val = inj_bool(val.v_num == 0 ? 1 : 0); apply_cont(); break; } case let_cont: { env_t* new_env = extend_env(cont->env, cont->var, val); env = new_env; expr = cont->body; cont = cont->cont; value_of(); break; } case if_cont: { if (val.tag != bool_val) abort("Expected boolean value in if condition"); env = cont->env; if (val.v_bool) { expr = cont->then_e; } else { expr = cont->else_e; } cont = cont->cont; value_of(); break; } case diff_1_cont: { cont_t* new_cont = make_cont(diff_2_cont); new_cont->cont = cont->cont; new_cont->val = val; expr = cont->exp; env = cont->env; cont = new_cont; value_of(); break; } case diff_2_cont: { if (cont->val.tag != num_val || val.tag != num_val) abort("Expected both operands of - to be num"); val = inj_num(cont->val.v_num - val.v_num); cont = cont->cont; apply_cont(); break; } case rator_cont: { cont_t* new_cont = make_cont(rand_cont); new_cont->cont = cont->cont; new_cont->val = val; expr = cont->exp; env = cont->env; cont = new_cont; value_of(); break; } case rand_cont: { if (cont->val.tag != proc_val) { printf("Operator is %d\n", cont->val.tag); abort("Expected operator to be a procedure"); } proc_t proc = cont->val.v_proc; env_t* new_env = extend_env(proc.env, proc.var, val); env = new_env; cont = cont->cont; expr = proc.body; value_of(); break; } } } expval_t eval(expr_t* exp) { expr = exp; cont = make_cont(end_cont); env = empty_env(); value_of(); return val; }
C
// // Created by y123456 on 2021/9/23. // #include "include/ast.h" #include "include/as_frontend.h" #include <string.h> #include <stdio.h> static ast_t *var_lookup(list_t* list,const char* name){ for (int i = 0; i <list->size ; ++i) { ast_t *child_ast = list->items[i]; if(child_ast->type != AST_VARIABLE || ! child_ast->name) continue; if(strcmp(child_ast->name,name) ==0) return child_ast; } return NULL; } char* as_compound(ast_t* ast,list_t* list){ char* value = calloc(1,sizeof(char)); for (int i = 0; i < ast->child->size; ++i) { ast_t* child_ast = (ast_t*) ast->child->items[i]; char* next_value = as(child_ast,list); value = realloc(value, (strlen(value) +strlen(next_value) +1) * sizeof(char)); strcat(value,next_value); } return value; } char* as_assignment(ast_t* ast,list_t* list){ char *s = calloc(1,sizeof(char)); if(ast->value->type == AST_FUNCTION){ const char* template = ".global %s\n" "%s:\n" " pushl %%ebp\n" " movl %%esp,%%ebp\n"; s = realloc(s,(strlen(template)+ (strlen(ast->name) * 2) + 1)*sizeof(char)); sprintf(s,template,ast->name, ast->name); ast_t* as_val = ast->value; for(int i=0; i < as_val->child->size; ++i){ ast_t* farg = as_val->child->items[i]; ast_t* arg_variable = ast_init(AST_VARIABLE); arg_variable->name= farg->name; arg_variable->int_value= (int)(4 * as_val->child->size)- ( i * 4); list_push(list,arg_variable); } char* as_val_val = as(as_val->value,list); s = realloc(s, ( strlen(s)+ strlen(as_val_val) +1 ) * sizeof(char)); strcat(s,as_val_val); } return s; } char* as_variable(ast_t* ast,list_t* list){ char* s = calloc(1,sizeof(char)); ast_t *var = var_lookup(list,ast->name); if(!var){ printf("[AST Fronted]:'%s' is not defined\n",ast->name); exit(-1); } const char* template = "%d(%%esp)"; s = realloc(s,(strlen(template) + 8) * sizeof(char)); sprintf(s,template,var->int_value); return s; } char* as_call(ast_t* ast,list_t* list){ char *s = calloc(1,sizeof(char)); if(strcmp(ast->name,"return") == 0){ ast_t* first_arg = ast->value->child->size ? ast->value->child->items[0] : 0; char* var_s= calloc(3,sizeof(char)); var_s[0]='$'; var_s[1] ='0'; var_s[2] = '\0'; if(first_arg){ char* as_var = as(first_arg,list); var_s = realloc(var_s, (strlen(as_var) + 1 ) * sizeof(char)); strcpy(var_s,as_var); free(as_var); } const char* template= " movl %s,%%eax\n" " movl %%ebp,%%esp\n" " popl %%ebp\n" " ret\n"; char* ret_s = calloc(strlen(template) + 128,sizeof(char)); sprintf(ret_s,template,var_s); s = realloc(s, ( strlen(ret_s) + 1 ) * sizeof(char)); strcat(s,ret_s); } return s; } char* as_int(ast_t* ast,list_t* list){ char* template = "$%d"; char* s = calloc(strlen(template)+128,sizeof(char)); sprintf(s,template,ast->int_value); return s; } char* as_string(ast_t* ast,list_t* list){ return ast->string_value; } char* as_access(ast_t* ast,list_t* list){ ast_t* left = var_lookup(list,ast->name); char * left_as = as(left,list); ast_t* first_arg = ast->value->child->size ? ast->value->child->items[0] : 0; const char* template = "%s,%%eax\n" " movl %d(%%eax)"; char* s= calloc(strlen(template) + strlen(left_as) + 128, sizeof(char)); sprintf(s,template,left_as, (first_arg ? first_arg->int_value : 0) * 4); printf("%s\n",s); free(left_as); return s; } char *as_root(ast_t* ast,list_t* list){ const char* section = ".section .text\n" ".global _start\n" "_start:\n" " pushl 0(%esp)\n" " pushl 4(%esp)\n" " call main\n" " addl $4,%esp\n" " movl %eax,%ebx\n" " movl $1,%eax\n" " int $0x80\n\n"; char* value = calloc( (strlen(section) + 128) , sizeof(char )); strcpy(value,section); char* next_value = as(ast,list); value = realloc(value,(strlen(next_value) + strlen(value) +1) *sizeof(char)); strcat(value,next_value); return value; } char* as(ast_t *ast,list_t* list) { char* value = calloc(1, sizeof(char )); char * next_value = NULL; switch (ast->type) { case AST_COMPOUND:{ next_value = as_compound(ast,list); }break; case AST_ASSIGNMENT :{ next_value = as_assignment(ast,list); }break; case AST_VARIABLE:{ next_value = as_variable(ast,list); }break; case AST_CALL:{ next_value = as_call(ast,list); }break; case AST_INT:{ next_value = as_int(ast,list); }break; case AST_ACCESS:{ next_value = as_access(ast,list); }break; case AST_STRING:{ next_value = as_string(ast,list); }break; default:{ printf("[as fronted]: No fronted for ast of type '%d'\n",ast->type); exit(-1); } } value = realloc(value,(strlen(next_value) +1)*sizeof(char)); strcat(value,next_value); return value; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *left; struct node *right; }*root=NULL; struct node *create(int data) { struct node *newnode=(struct node *)malloc(sizeof(struct node)); newnode->data=data; newnode->left=NULL; newnode->right=NULL; return newnode; } void display(struct node *root) { if(root==NULL) return; else { display(root->left); printf(" %d ",root->data); display(root->right); } } int search(int data,int ino[],int strt,int end) { int i; for(i=strt;i<end;i++) { if(ino[i]==data) return i; } } struct node *build(int ino[],int pre[],int strt,int end) { int inindex; static int preindex=0; if(strt>end) return NULL; struct node *new=create(pre[preindex++]); if(strt==end) return new; inindex=search(new->data,ino,strt,end); new->left=build(ino,pre,strt,inindex-1); new->right=build(ino,pre,inindex+1,end); return new; } int main() { int pre[]={1,2,4,5,3,6,7}; int ino[]={4,2,5,1,6,3,7}; int len=sizeof(ino)/sizeof(ino[0]); root=build(ino,pre,0,len-1); display(root); return 0; }
C
/* * Copyright 2009 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can * be found in the LICENSE file. */ /* * Some useful formatting tools that allow us to build our own directive * processing simply. The code assumes that directives of the form * %X (for some character x). Further, in a format string '\\' is treated * the backslash character ('\') while '\%' escapes out the interpretation * of '%' as the beginning of a directive. * * If the specified %X directive is not understood by the directive processing * function, the directive will not be translated while processing the format * string. * * Note: Buffer insertions are based on the routines FormatDataAppend and * FormatAppend. Each of these routines append text to the buffer, based * on the current cursor position. The cursor is the index to add the next * character to the buffer, if the buffer was sufficiently large enough to * hold the appended text. Therefore, after all text has been appended, if * the cursor is smaller than the buffer size, no truncation occurs. * * Note: Buffer insertions will automatically add the null terminator after * the appended string, but the cursor is not updated to reflect this change. * If a buffer overflows, the last character in the buffer will be the null * terminator, unless the buffer size is empty. If the buffer size is empty, * there is no room for the null terminator and it is not inserted. * * Note: To dynamically compute the amount of space needed to format a string, * call on an empty buffer with size zero, and the cursor initially set to zero. * After the call, the value of the cursor, plus one, is the minimum sized * buffer that will be needed to format that string. */ #ifndef NATIVE_CLIENT_SRC_SHARED_UTILS_FORMMATTING_H__ #define NATIVE_CLIENT_SRC_SHARED_UTILS_FORMMATTING_H__ #include "native_client/src/shared/utils/types.h" /* * Defines the generic format for a fucntion that processses directives * when they are found. Returns true if the directive was processed and * the resulting string was added at the given cursor position. When the buffer * fills, no additional text is added to the buffer, even though the cursor * is incremented accordingly. Otherwise, the buffer is left unchanged, * and the function must return false. * * arguments: * directive - The character X of the found %X directive. * buffer - The buffer to add the resulting text of the directive * buffer_size - The size of the buffer. * data - (Generic) pointer to the data that should be used to process the * directive. * cursor - The index into the buffer, where the next character * should be added, if there is sufficient room in the buffer. */ typedef Bool (*FormatDataUsingDirectiveFcn)( char directive, char* buffer, size_t buffer_size, void* data, size_t* cursor); /* * Defines a driver routine to process a format string and put the rsulting * generated text in at the cursor position. When the buffer fills, no * additional text is added to the buffer, even though the cursor is * incremented accordingly. * * Note: Buffer overflow occurs iff the cursor is greater than or * equal to the buffer size. * * arguments: * buffer - The buffer to fill using the format. * buffer_size - The size of the buffer. * format - The format string to use. * data - (Generic) pointer to the data that should be used to process the * directives in the format string. * directive_fcn - The function to process directives as they are found. * cursor - The index into the buffer, where the next character should * be added, if there is sufficient room in the buffer. */ void FormatDataAppend(char* buffer, size_t buffer_size, const char* format, void* data, FormatDataUsingDirectiveFcn directive_fcn, size_t* cursor); /* * Defines a driver routine to process a format string and put the resulting * generated text in the given buffer. Returns true iff buffer overflow doesn't * occur. * * arguments: * buffer - The buffer to fill using the format. * buffer_size - The size of the buffer. * format - The format string to use. * data - (Generic) pointer to the data that should be used to process the * directives in the format string. * directive_fcn - The function to process directives as they are found. */ Bool FormatData(char* buffer, size_t buffer_size, const char* format, void* data, FormatDataUsingDirectiveFcn directive_fcn); /* * Append the given text at the cursor position. When the buffer fills, no * additional text is added to the buffer, even though the cursor is incremented * accordingly. * * Note: Buffer overflow occurs iff the cursor is greater than or * equal to the buffer size. * * arguments: * buffer - The buffer to fill with the text. * buffer_size - The size of the buffer. * text - The text to append. * cursor - The index into the buffer, where the next character * should be added, if there is sufficient room in the buffer. */ void FormatAppend(char* buffer, size_t buffer_size, const char* text, size_t* index); #endif /* NATIVE_CLIENT_SRC_SHARED_UTILS_FORMMATTING_H__ */
C
/* Program to find a number is Even or Odd using Function with no return value and argument */ #include<stdio.h> #include<conio.h> main() { void even(); even(); getch(); } void even() { int a; printf("Enter number: "); scanf("%d",&a); if(a%2==0) { printf("\n%d is an Even number",a); } else { printf("\n%d is an Odd number",a); } }
C
#ifndef _BHEAP_H_ #define _BHEAP_H_ #ifdef __cplusplus extern "C"{ #endif typedef struct bheap_t{ void *data; int data_size; int current_length; int total_length; }bheap_t; typedef int (*bheap_compare_t)(void *a, void *b); /* general compare method */ int bheap_compare_int_smaller(void *a, void *b); bheap_t* bheap_create(int total_length, int data_size); int bheap_insert(bheap_t *heap, void *data_in, bheap_compare_t compare); int bheap_peek_top(bheap_t *heap, void *data_out); int bheap_delete_top(bheap_t *heap, void *data_out, bheap_compare_t compare); #ifdef __cplusplus } #endif #endif
C
#include "v7_user.h" #include <sys\time.h> #include <sys\times.h> #include <sys\queue.h> #include "v7_internal.h" #include <stm32f7xx.h> #include <stm32746g_discovery.h> #include <pin_macros.h> #include "asm.h" #define CLOCK_PRIOITY 1 /* high piroirty on clock but honestly it just ticks */ static struct timeval arch_time = { 0,0 }; static const struct timeval arch_time_inc = { 0, 1000000U/60 }; /// 60 hz static TIM_HandleTypeDef TimHandle; void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if(htim == &TimHandle){ timeradd(&arch_time, &arch_time_inc, &arch_time); } //HAL_IncTick(); } time_t v7_time(time_t* t) { time_t sec = arch_time.tv_sec;// this is atomic so no locking needed if(t) *t=sec; return sec; } /** * @brief This function handles TIM interrupt request. * @retval None */ void TIM2_IRQHandler(void) { HAL_TIM_IRQHandler(&TimHandle); } static void configure_clock() { RCC_ClkInitTypeDef clkconfig; uint32_t uwTimclock, uwAPB1Prescaler = 0U; uint32_t uwPrescalerValue = 0U; uint32_t pFLatency; HAL_NVIC_SetPriority(TIM2_IRQn, CLOCK_PRIOITY ,0U); HAL_NVIC_EnableIRQ(TIM2_IRQn); /* Enable the TIM6 global Interrupt */ __HAL_RCC_TIM6_CLK_ENABLE(); /* Enable TIM6 clock */ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); /* Get clock configuration */ uwAPB1Prescaler = clkconfig.APB1CLKDivider; /* Get APB1 prescaler */ uwTimclock = HAL_RCC_GetPCLK1Freq(); if((uwAPB1Prescaler != RCC_HCLK_DIV1) ) uwTimclock*=2; /* Compute the prescaler value to have TIM6 counter clock equal to 1MHz */ uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000U) - 1U); TimHandle.Instance = TIM2; /* Initialize TIM2 */ /* Initialize TIMx peripheral as follow: + Period = [(TIM6CLK/1000) - 1]. to have a (1/1000) s time base. + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + ClockDivision = 0 + Counter direction = Up */ //TimHandle.Init.Period = (1000000U / 1000U) - 1U; // 1ms TimHandle.Init.Period = 1000000U; // 1sec //TimHandle.Init.Period = 1000000U/60; // 60hz TimHandle.Init.Prescaler = uwPrescalerValue; TimHandle.Init.ClockDivision = 0; TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if(HAL_TIM_Base_Init(&TimHandle) == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ HAL_TIM_Base_Start_IT(&TimHandle); } } void arch_gettimeofday(struct timeval * tv){ /* Disable TIM6 update Interrupt */ __HAL_TIM_DISABLE_IT(&TimHandle, TIM_IT_UPDATE); *tv = arch_time; /* Enable TIM6 Update interrupt */ __HAL_TIM_ENABLE_IT(&TimHandle, TIM_IT_UPDATE); } void arch_settimeofday(struct timeval * tv){ /* Disable TIM6 update Interrupt */ __HAL_TIM_DISABLE_IT(&TimHandle, TIM_IT_UPDATE); arch_time = *tv; /* Enable TIM6 Update interrupt */ __HAL_TIM_ENABLE_IT(&TimHandle, TIM_IT_UPDATE); } void SysTick_Handler(void) { HAL_IncTick(); HAL_SYSTICK_IRQHandler(); //osSystickHandler(); } void show_regs(struct pt_regs * regs); void asm_do_IRQ(int irq, struct pt_regs *regs) { if(irq < 16) { trace_printf("UNHANDLED FAULT! ISR:%d\n", irq); show_regs(regs); while(1) ; } else { trace_printf("UNHANDLED IRQ! ISR:%d\n", irq); show_regs(regs); } //trace_printf("ISR %d \n",irq); if(regs->ARM_EXC_lr == 0xfffffffd){ // check if we have work and raise pendf } while(1) ; } void v7_arch_setup() { configure_clock(); }
C
#include "types.h" #include "stat.h" #include "user.h" #include "fs.h" #include "fcntl.h" #define NUM_CHILDREN 2 #define TARGET_COUNT_PER_CHILD 50 #define COUNTER_FILE "counter" #define SEMAPHORE_NUM 0 int counter_init(char *filename, int value) { int fd; if ((fd = open(filename, O_CREATE | O_RDWR)) < 0) { printf(1, "counter_init: error initializing file: %s\n", filename); exit(); } printf(fd, "%d\n", value); close(fd); return 0; } int counter_get(char *filename) { int fd, n, value; char buffer[32]; if ((fd = open(filename, O_CREATE | O_RDWR)) < 0) { printf(1, "counter_get: error opening file: %s\n", filename); exit(); } n = read(fd, buffer, 31); buffer[n] = '\0'; value = atoi(buffer); close(fd); return value; } int counter_set(char *filename, int value) { int fd; if ((fd = open(filename, O_CREATE | O_RDWR)) < 0) { printf(1, "counter_set: error opening file: %s\n", filename); exit(); } printf(fd, "%d\n", value); close(fd); return value; } void child(void) { int i; int counter; printf(1, "Process started...\n"); sleep(10); for (i=0; i<TARGET_COUNT_PER_CHILD; i++) { sem_wait(SEMAPHORE_NUM, 1); counter = counter_get("counter"); counter++; counter_set("counter", counter); sem_signal(SEMAPHORE_NUM, 1); } exit(); } int main(int argc, char **argv) { int i; int final_counter; int final_target = NUM_CHILDREN*TARGET_COUNT_PER_CHILD; // Initialize semaphore to 1 if (sem_init(SEMAPHORE_NUM, 1) < 0) { printf(1, "main: error initializing semaphore %d\n", SEMAPHORE_NUM); exit(); } // Initialize counter counter_init(COUNTER_FILE, 0); printf(1, "Running with %d processes...\n", NUM_CHILDREN); // Start all children for (i=0; i<NUM_CHILDREN; i++) { int pid = fork(); if (pid == 0) child(); } // Wait for all children for (i=0; i<NUM_CHILDREN; i++) { wait(); } // Check the result final_counter = counter_get(COUNTER_FILE); printf(1, "Final counter is %d, target is %d\n", final_counter, final_target); if (final_counter == final_target) printf(1, "TEST PASSED!\n"); else printf(1, "TEST FAILED!\n"); // Clean up semaphore sem_destroy(SEMAPHORE_NUM); // Exit exit(); }
C
#include<stdio.h> #define N 200004 #define N1 N/2 /*problem id-11327 * *language-ANSI C * */ typedef unsigned long long ull; int p[N],phi[N]; ull sum[N]; void EulerPhiSieve() { int i,j; phi[1]=2, phi[2]=1; for(i=3;i<N;i++) phi[i]=i; for(i=4;i<N;i+=2) { phi[i]/=2;p[i]=1; } for(i=3;i<N;i+=2) { if(!p[i]) { phi[i]=i-1; for(j=i+i;j<N;j+=i) { phi[j]/=i; phi[j]*=(i-1); p[j]=1; } } } return; } void PreCal() { int i; EulerPhiSieve(); for(i=1;i<N;i++) sum[i]=(ull)phi[i]+sum[i-1]; return; } int gcd(int a,int b) { if(!b) return a; else gcd(b,a%b); } int BinarySearch(int low,int high,ull val) { int mid; while(low<=high) { mid=(low+high)/2; if(val>sum[mid]) { low=mid+1; if(val<sum[mid+1]) return mid+1; } else if(val==sum[mid]) return mid; else { high=mid-1; if(val>sum[mid-1]) return mid; } } } void Solve(ull K) { int i,idx,remain; if(K==1) { printf("0/1\n"); return; } idx=BinarySearch(1,N,K); remain=K-sum[idx-1]; for(i=1;i<idx;i++) { if(gcd(idx,i)==1) remain--; if(!remain) break; } printf("%d/%d\n",i,idx); return; } int main() { ull K; PreCal(); while(scanf("%llu",&K) && K) Solve(K); return 0; }
C
#include <stdio.h> int main (void) { int year; printf("Enter year: "); scanf("%d", &year); int a, b, c, d, e, f, g, h, i, j, k, l, m, easterMonth, easterDate, p; a=year%19; b=year/100; c=year%100; d=b/4; e=b%4; f=(b+8)/25; g=(b-f+1)/3; h=(19*a+b-d-g+15)%30; i=c/4; k=c%4; l=(32+2*e+2*i-h-k)%7; m=(a+11*h+22*l)/451; easterMonth =(h+l-7*m+114)/31; //[3=March, 4=April] p=(h+l-7*m+114)%31; easterDate=p+1; if (easterMonth==3){ printf("Easter is March %d in %d.\n", easterDate, year); } else { printf("Easter is April %d in %d.\n", easterDate, year); } return 0; }
C
#include <stdio.h> int main() { float i = 64.25; printf("Enter a floating-point value:%.2f \n", i); printf("fixed-point notation:%f\n", i); printf("exponential notation:%e\n", i); printf("p notation:%a\n", i); return 0; }
C
#include <stdint.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include "gamma.h" #include <stdbool.h> #include <string.h> int main() { /* scenario: test_random_actions uuid: 559032029 */ /* random actions, total chaos */ gamma_t* board = gamma_new(8, 5, 5, 10); assert( board != NULL ); assert( gamma_move(board, 1, 2, 7) == 0 ); assert( gamma_move(board, 2, 3, 6) == 0 ); assert( gamma_move(board, 3, 4, 2) == 1 ); assert( gamma_move(board, 3, 4, 1) == 1 ); assert( gamma_move(board, 4, 7, 4) == 1 ); assert( gamma_move(board, 5, 4, 4) == 1 ); assert( gamma_free_fields(board, 5) == 36 ); assert( gamma_move(board, 1, 4, 3) == 1 ); assert( gamma_move(board, 1, 6, 2) == 1 ); assert( gamma_move(board, 2, 3, 1) == 1 ); assert( gamma_move(board, 3, 4, 3) == 0 ); assert( gamma_move(board, 3, 5, 0) == 1 ); assert( gamma_move(board, 4, 2, 1) == 1 ); assert( gamma_move(board, 5, 0, 1) == 1 ); assert( gamma_busy_fields(board, 5) == 2 ); assert( gamma_golden_possible(board, 5) == 1 ); assert( gamma_move(board, 1, 3, 3) == 1 ); assert( gamma_move(board, 2, 4, 3) == 0 ); assert( gamma_free_fields(board, 2) == 29 ); assert( gamma_move(board, 3, 2, 0) == 1 ); assert( gamma_move(board, 3, 2, 3) == 1 ); assert( gamma_move(board, 4, 0, 1) == 0 ); assert( gamma_move(board, 5, 4, 6) == 0 ); assert( gamma_free_fields(board, 5) == 27 ); assert( gamma_move(board, 1, 1, 6) == 0 ); assert( gamma_move(board, 2, 2, 3) == 0 ); assert( gamma_move(board, 3, 2, 1) == 0 ); assert( gamma_move(board, 3, 6, 0) == 1 ); assert( gamma_move(board, 4, 7, 2) == 1 ); assert( gamma_move(board, 1, 4, 6) == 0 ); assert( gamma_move(board, 2, 2, 0) == 0 ); assert( gamma_move(board, 3, 1, 2) == 1 ); assert( gamma_move(board, 3, 4, 4) == 0 ); assert( gamma_move(board, 4, 4, 4) == 0 ); assert( gamma_move(board, 5, 6, 1) == 1 ); assert( gamma_busy_fields(board, 5) == 3 ); assert( gamma_move(board, 1, 2, 2) == 1 ); assert( gamma_move(board, 1, 4, 4) == 0 ); assert( gamma_move(board, 2, 6, 2) == 0 ); assert( gamma_move(board, 2, 4, 3) == 0 ); assert( gamma_busy_fields(board, 3) == 7 ); assert( gamma_move(board, 4, 7, 2) == 0 ); assert( gamma_move(board, 5, 1, 1) == 1 ); assert( gamma_move(board, 5, 6, 4) == 1 ); assert( gamma_move(board, 1, 4, 5) == 0 ); assert( gamma_move(board, 1, 1, 0) == 1 ); assert( gamma_move(board, 2, 2, 2) == 0 ); assert( gamma_move(board, 2, 1, 1) == 0 ); assert( gamma_free_fields(board, 2) == 19 ); assert( gamma_move(board, 3, 3, 7) == 0 ); assert( gamma_move(board, 3, 6, 0) == 0 ); assert( gamma_free_fields(board, 3) == 19 ); assert( gamma_move(board, 4, 2, 3) == 0 ); assert( gamma_move(board, 4, 6, 2) == 0 ); assert( gamma_free_fields(board, 5) == 19 ); assert( gamma_move(board, 1, 4, 1) == 0 ); assert( gamma_move(board, 2, 3, 5) == 0 ); assert( gamma_move(board, 3, 0, 1) == 0 ); assert( gamma_move(board, 4, 3, 7) == 0 ); assert( gamma_move(board, 1, 3, 7) == 0 ); assert( gamma_free_fields(board, 1) == 19 ); assert( gamma_move(board, 2, 3, 5) == 0 ); assert( gamma_move(board, 2, 5, 4) == 1 ); assert( gamma_move(board, 3, 3, 1) == 0 ); assert( gamma_move(board, 4, 6, 3) == 1 ); assert( gamma_busy_fields(board, 4) == 4 ); assert( gamma_golden_move(board, 4, 3, 3) == 1 ); assert( gamma_move(board, 5, 3, 0) == 1 ); assert( gamma_move(board, 5, 2, 0) == 0 ); assert( gamma_move(board, 1, 2, 5) == 0 ); assert( gamma_move(board, 1, 3, 3) == 0 ); assert( gamma_move(board, 2, 3, 5) == 0 ); assert( gamma_move(board, 2, 0, 1) == 0 ); assert( gamma_move(board, 3, 2, 5) == 0 ); assert( gamma_move(board, 3, 5, 1) == 1 ); assert( gamma_free_fields(board, 3) == 15 ); assert( gamma_move(board, 4, 3, 5) == 0 ); assert( gamma_move(board, 4, 5, 0) == 0 ); assert( gamma_move(board, 5, 4, 3) == 0 ); assert( gamma_move(board, 1, 1, 7) == 0 ); assert( gamma_golden_possible(board, 1) == 1 ); assert( gamma_move(board, 2, 3, 2) == 1 ); assert( gamma_move(board, 3, 4, 2) == 0 ); assert( gamma_move(board, 3, 5, 4) == 0 ); char* board753183248 = gamma_board(board); assert( board753183248 != NULL ); assert( strcmp(board753183248, "....5254\n" "..341.4.\n" ".3123.14\n" "5542335.\n" ".135.33.\n") == 0); free(board753183248); board753183248 = NULL; assert( gamma_move(board, 4, 3, 1) == 0 ); assert( gamma_move(board, 5, 0, 0) == 1 ); assert( gamma_busy_fields(board, 5) == 7 ); assert( gamma_free_fields(board, 5) == 13 ); assert( gamma_move(board, 1, 1, 0) == 0 ); assert( gamma_move(board, 1, 4, 4) == 0 ); assert( gamma_move(board, 2, 3, 1) == 0 ); assert( gamma_busy_fields(board, 2) == 3 ); assert( gamma_move(board, 3, 2, 2) == 0 ); assert( gamma_move(board, 3, 5, 2) == 1 ); assert( gamma_move(board, 4, 2, 0) == 0 ); assert( gamma_move(board, 5, 4, 3) == 0 ); assert( gamma_move(board, 1, 6, 2) == 0 ); assert( gamma_busy_fields(board, 1) == 4 ); assert( gamma_move(board, 2, 2, 0) == 0 ); assert( gamma_move(board, 2, 1, 3) == 1 ); assert( gamma_busy_fields(board, 2) == 4 ); assert( gamma_free_fields(board, 2) == 11 ); assert( gamma_move(board, 3, 2, 1) == 0 ); assert( gamma_move(board, 4, 6, 3) == 0 ); assert( gamma_free_fields(board, 4) == 11 ); assert( gamma_busy_fields(board, 5) == 7 ); assert( gamma_move(board, 1, 2, 0) == 0 ); assert( gamma_move(board, 2, 5, 1) == 0 ); assert( gamma_move(board, 3, 3, 0) == 0 ); assert( gamma_move(board, 3, 5, 2) == 0 ); assert( gamma_free_fields(board, 3) == 11 ); assert( gamma_move(board, 4, 4, 2) == 0 ); assert( gamma_move(board, 4, 0, 1) == 0 ); assert( gamma_move(board, 5, 2, 0) == 0 ); assert( gamma_free_fields(board, 5) == 11 ); assert( gamma_move(board, 1, 0, 2) == 1 ); assert( gamma_move(board, 1, 1, 0) == 0 ); assert( gamma_move(board, 2, 4, 2) == 0 ); assert( gamma_move(board, 2, 2, 1) == 0 ); assert( gamma_free_fields(board, 2) == 10 ); assert( gamma_move(board, 4, 4, 0) == 1 ); assert( gamma_move(board, 4, 1, 0) == 0 ); assert( gamma_busy_fields(board, 4) == 6 ); assert( gamma_move(board, 5, 6, 2) == 0 ); assert( gamma_move(board, 1, 1, 7) == 0 ); assert( gamma_move(board, 1, 2, 4) == 1 ); assert( gamma_move(board, 2, 7, 4) == 0 ); assert( gamma_busy_fields(board, 2) == 4 ); assert( gamma_move(board, 3, 3, 5) == 0 ); assert( gamma_move(board, 4, 3, 7) == 0 ); assert( gamma_move(board, 5, 4, 3) == 0 ); assert( gamma_move(board, 5, 5, 3) == 1 ); gamma_delete(board); return 0; }
C
#include <stdio.h> #include <inttypes.h> int main(void) { int32_t me32; me32 = 45933945; printf("먼저, int32_t를 int형이라고 가정한다: "); printf("me32 = %d\n", me32 ); printf("이제, 어떠한 가정도 하지 말자.\n"); printf("그 대신에, inttypes.h에 있는 \"macro\"를 사용한다: "); printf("me32 = %" PRId32 "\n", me32); return 0; }
C
#include <pebble.h> #include "weights_timer.h" #define HEADER_MSG "Weights" #define STOPPED_FOOTER_MSG "Select to start" #define RUNNING_FOOTER_MSG "Select to stop" #define SET_COUNT_MSG "Set %d" #define REST_TIME_SEC 60 #define GET_READY_TIME_SEC 10 #define COOLDOWN_TIME_SEC 120 typedef enum { set_rest, activity_cooldown } WeightTimerModes; static void timer_tick_second(PTimerState timer); static void toggle_set_timer(PTimerState timer); static void timer_reset(PTimerState timer); static void timer_expire(PTimerState timer); static void start_cooldown(PTimerState timer); static void timer_reset_sets(PTimerState timer); WeightTimerModes timer_mode = set_rest; char set_count_text[6]; int set_count = 0; static void update_set_count_text(PTimerState timer) { snprintf(set_count_text, sizeof(set_count_text), SET_COUNT_MSG, set_count); timer->stopped_counter_text = set_count_text; } static void timer_tick_second(PTimerState timer) { if (timer->current_time_sec == GET_READY_TIME_SEC) vibes_double_pulse(); } static void toggle_set_timer(PTimerState timer) { if (!timer->is_running) { timer_reset(timer); timer->footer = RUNNING_FOOTER_MSG; } else { timer->footer = STOPPED_FOOTER_MSG; } timer->is_running = !timer->is_running; } static void start_cooldown(PTimerState timer) { timer_reset_sets(timer); timer_mode = activity_cooldown; timer->current_time_sec = COOLDOWN_TIME_SEC; timer->is_running = true; } static void timer_reset(PTimerState timer) { timer->current_time_sec = REST_TIME_SEC; timer_mode = set_rest; } static void timer_expire(PTimerState timer) { vibes_long_pulse(); timer->is_running = false; if (timer_mode == set_rest) { set_count++; } else { timer_reset(timer); } update_set_count_text(timer); } static void timer_reset_sets(PTimerState timer) { if (!timer->is_running) { set_count = 0; update_set_count_text(timer); } } void create_weights_timer(PTimerState timer) { timer->header = HEADER_MSG; timer->footer = STOPPED_FOOTER_MSG; timer->is_running = false; timer->handlers.timer_expire_handler = timer_expire; timer->handlers.timer_reset_handler = timer_reset; timer->handlers.timer_select_button_handler = toggle_set_timer; timer->handlers.timer_long_select_button_handler = timer_reset_sets; timer->handlers.timer_tick_notify_handler = timer_tick_second; timer->handlers.timer_back_button_handler = start_cooldown; timer_reset(timer); timer_reset_sets(timer); }