language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/****************************************************/ integer * integer_sadd(integer * d1, integer * d2) { int k, i = d2->len_of_integer; INTEGER_FULL_TYPE sum = 0; if (d1->vec_of_integer[d1->len_of_integer - 1] > (INTEGER_MAXNUM >> 1)) { d1->len_of_integer++; d1->vec_of_integer = realloc(d1->vec_of_integer, d1->len_of_integer * sizeof(INTEGER_HALF_TYPE)); d1->vec_of_integer[d1->len_of_integer - 1] = 0; } for (k = 0; k < i; k++) { sum += ((INTEGER_FULL_TYPE) (d1->vec_of_integer[k])) + ((INTEGER_FULL_TYPE) (d2->vec_of_integer[k])); d1->vec_of_integer[k] = EXTRACT(sum); sum >>= INTEGER_HALF; } for (; sum != 0; k++) { sum += d1->vec_of_integer[k]; d1->vec_of_integer[k] = EXTRACT(sum); sum >>= INTEGER_HALF; } return d1; }
C
/********************************************************************** Module: g_adt.c Author: Scott Wang Date: 2006 Oct 5 Purpose: A data struct for Omega game **********************************************************************/ #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <pthread.h> #include "g_adt.h" #include "eheap.h" #include "field.h" #include "screen.h" #include "move_man.h" #include "move_zombie.h" #include "move_bullet.h" #include "image.h" #include "collision.h" #include "globals.h" /* calculate the array index from given row and col */ #define ROW_INDEX(row) (row - FIELD_MIN_ROW) #define COL_INDEX(col) (col - FIELD_MIN_COL) /* return true iff the calculating result from given row and col are correct indexes.. */ #define IS_CORRECT_INDEX(row,col) \ ( ROW_INDEX(row) >= 0 && ROW_INDEX(row) < FIELD_HEIGHT \ && COL_INDEX(col) >= 0 && COL_INDEX(col) < FIELD_WIDTH ) /* define winning or losing message */ #define WON "You won" #define LOST "You need to practice steering!" /* an array holds every spots in the field where t indicate what characters in the game d is an void pointer points to the character lock is a mutex lock for the cell */ static struct g_array { game_type_t t; void *d; pthread_mutex_t lock; }g[FIELD_HEIGHT][FIELD_WIDTH]; /* finish the game, clean up whatever left on the screen free memeory locations */ static void g_adt_fini(char *message); void g_adt_init() { int row,col; for(row=0; row < FIELD_HEIGHT; row++){ for(col=0; col<FIELD_WIDTH; col++){ g[row][col].t = EMPTY; g[row][col].d = NULL; } } } game_type_t g_adt_get_type(int row, int col) { assert(IS_CORRECT_INDEX(row,col)); return g[ROW_INDEX(row)][COL_INDEX(col)].t; } void g_adt_add(int row,int col,void *d, game_type_t t) { assert(IS_CORRECT_INDEX(row,col)); int r_index = ROW_INDEX(row); int c_index = COL_INDEX(col); if(!reset_flag && !collision_is_occur(t,d,g[r_index][c_index].t,g[r_index][c_index].d)){ g[r_index][c_index].d = d; g[r_index][c_index].t = t; } } void g_adt_remove(int row, int col) { assert(IS_CORRECT_INDEX(row,col)); g[ROW_INDEX(row)][COL_INDEX(col)].d = NULL; g[ROW_INDEX(row)][COL_INDEX(col)].t = EMPTY; } void g_adt_lose() { g_adt_fini(LOST); } void g_adt_win() { g_adt_fini(WON); } void g_adt_fini(char *message) { screen_fini(); printf("%s\n",message); /* clean up */ int row,col; for(row=0; row < FIELD_HEIGHT; row++){ for(col=0; col<FIELD_WIDTH; col++){ efree(g[row][col].d); } } exit(1); } /* lock the cell */ void g_adt_lock(int row, int col) { if(IS_CORRECT_INDEX(row,col)) pthread_mutex_lock(&g[ROW_INDEX(row)][COL_INDEX(col)].lock); } /* unlock the cell */ void g_adt_unlock(int row,int col) { if(IS_CORRECT_INDEX(row,col)) pthread_mutex_unlock(&g[ROW_INDEX(row)][COL_INDEX(col)].lock); }
C
/* Employee_info_list REQ: 1. Write a struct that has a member that is the name of a business department: HR, Sales, Research, Software, and Executive (use enums for the 4 departments). 2. A second member that is an annual salary as an int. 3. A third member that is a social security number(unsigned). 4. Generate 10 employees with different social security numbers. 5. Invent a salary generator for each department (use some base salary for the department and add in a randomly generated offset). 6. Print out the 10 employees and their values to the screen-one line at a time. RoadMap: input elements for stack; auto generate id string DE+FFFFFFFF; push struct into stack; Note: input seq: name(%s), dept(%u) <HR,Sales,RD,SW,Exec>, contract_type(%c), Level(%s) or Period(%d) result: [email protected] 28.04.2021 */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_SAL 9000 //max salary #define MIN_SAL 4000 //min salary #define RANGE 5000 //salary gap between Max and Min #define TOTAL 4 //total employee #define SA_OVER rand() % RANGE #define SA SA_OVER + MIN_SAL // #define FILL \ // for (i = 0; i < TOTAL; i++) \ // data[i] = SA #define EMPTY -1 #define FULL (TOTAL - 1) typedef enum SECTION{HR = 1,Sales,RD,SW,Exec}Section; // typedef enum Section dept; // char *GEN_ID(int len); //generate ID_String=states_code+random("FF...FFF") maximual 6byte, eg: FFFF FFFF FFFF char *GEN_ID(void); char *StringDirectionT(Section *sec); typedef struct EMPLY_INFO { int index; char name[20]; Section dept; int salary; char *social_id; char contract_type; //p = Permanent, T =template; union { int period; //T: contract avaiable year. char Level[20]; // P: level. } ct; } emply_info; typedef struct stack { emply_info s[TOTAL]; int top; } stack; void reset(stack *stk) { stk->top = EMPTY; } void push(emply_info c, stack *stk) { stk->top++; stk->s[stk->top] = c; } emply_info pop(stack *stk) { return (stk->s[stk->top--]); } emply_info top(const stack *stk) { return (stk->s[stk->top]); } int is_empty(const stack *stk) { return (stk->top == EMPTY); } int is_full(const stack *stk) { return (stk->top == FULL); } int main() { emply_info employee; stack stack_of_em_info; reset(&stack_of_em_info); int i=0; // emply_info* employee = new emply_info; printf("Input info: \nname\tdept\tcontract_type\tLevelorPeriod\n"); while (!is_full(&stack_of_em_info)) // while (i < TOTAL) { employee.index = i++; scanf("%s %u %c", employee.name, &(employee.dept), &(employee.contract_type)); if (employee.contract_type == 'P') { scanf("%s", employee.ct.Level); //Permanent contract } else //Temporary contract { scanf("%d", &employee.ct.period); } employee.social_id = GEN_ID(); employee.salary = SA; push(employee, &stack_of_em_info); } printf("\nIndex\t\tName\t\tDept\t\tsocial_id\t\tSalary\t\tcontract_type\t\tperiod or Level\n"); // i = 0; while (!is_empty(&stack_of_em_info)) { employee = pop(&stack_of_em_info); if (employee.contract_type == 'P') //Permanent contract { printf("%d\t\t%s\t\t%s\t\t%s\t\t%d\t\t%c\t\t%s\n", employee.index, employee.name, StringDirectionT(&(employee.dept)), employee.social_id, \ employee.salary,employee.contract_type,employee.ct.Level); } else //Temporary contract { printf("%d\t\t%s\t\t%s\t\t%s\t\t%d\t\t%c\t\t%d\n", employee.index, employee.name, StringDirectionT(&(employee.dept)), employee.social_id,employee.salary,employee.contract_type,employee.ct.period); } } return 0; } char *GEN_ID(void) { int i; unsigned ID; // char *empy_id; unsigned max_Hex = 0xFFFFFFFF; srand((unsigned)time(0)); ID = rand() % max_Hex; // unsigned a; // char *s; // for (i = 0; i < len; i++) // { // strcat(s, "F"); // } // puts(s); // a = strtoul(s, &s, 16); // char *string = malloc(strlen(s) + 1); char *string = malloc(9); char *state = "DE"; char *ID_string = malloc(strlen(state) + strlen(string)); sprintf(string, "%08X", ID); strcpy(ID_string, state); strcat(ID_string, string); puts(ID_string); // empy_id = ID_string; // printf("integer = %d string = %s\n", ID, string); // printf("ID_string = %s\n", ID_string); // printf("The string 'str' is %s and the number 'num' is %X. \n",s, a); // free(s); // s = NULL; free(string); string = NULL; // free(ID_string); // ID_string = NULL; return ID_string; } char * StringDirectionT(Section *sec) { switch(*sec) { case HR: return "HR"; case Sales: return "Sales"; case RD: return "RD"; case SW: return "SW"; case Exec: return "Exec"; default: printf("Illegal value!\n"); } }
C
/* Fetch the desired region of xe3-formatted catalog stars. * * xe3 is a very compact format storing just ra/dec/mag/class for each star. * Each star occupies 3 bytes and stores RA to a precision of +/- .38 arcsecs, * Dec to .44 arcsec, Mag in the range 10..20 to .16 and 1 class bit set to 0 * for star or 1 for other. One xe3 file stores all stars in a band of * declination one degree hi, beginning on an integral dec boundary. Thus 180 * xe3 files are required to cover the entire sky. * * The overall file structure is an initial line of ASCII giving file type and * the base declination, followed by a table of 360 records indexed by RA in * whole degs giving the file offset and starting RA into the star records * for that RA, followed by any number of star records sorted by increasing RA. * Each star record occupies 3 bytes and stores the dec offset from the base * dec of the band, the RA offset from the RA of the previous record, the mag * and the class. * * The file starts with 8 ASCII chars including a final newline in the format * "xe3 HDD\n", where H is 'N' for north hemishere else 'S'. DD is the base * of the dec band, zero filled whole degrees. Dec offsets in the star * records are added to the base dec if H is 'N' else subtracted from base. * * Following the header is a table of 360 records each 8 bytes long. The array * is indexed by RA in whole degrees. Each index record contains a file offset * in bytes from the front of the file to the first star record with an RA * greater than or equal to the index RA value, and the RA of said star. Each * of these values is 4 bytes stored big-endian. * * Following the index table are star records sorted in increasing RA. Each star * record is 3 bytes. The bits are packed as follows (stored bigendian): * 0.. 5 rabits * 6..17 decbits * 18..22 magbits * 23 star * then * ra = (rasum + rabits+.5)*RAPBIT/cos(decband) * dec = (north ? decband + (decbits+.5) : decband - (decbits+.5))*DECPBIT * mag = BRMAG + (magbits + .5)*MAGPBIT * starlike if star else really a star * where decband is the integer from the ASCII header line, rasum is an unsigned * int to accumulate the rabits values (initialized at the start of a sweep * from the index table entry) and dec and ra are in degrees (so beware if * your cos() expects rads). */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "xephem.h" #define MAXGSC22FOV degrad(5) /* max FOV to fetch */ /* packing in each record */ #define DECBITS 12 /* dec stored in 12 bits */ #define DECHI 1.0 /* height of dec band, degrees */ #define DECPBIT (DECHI/(1<<DECBITS)) /* dec degs per bit */ #define DECMASK ((1<<DECBITS)-1) /* dec mask */ #define RABITS 6 /* delta ra stored in 6 bits */ #define MAXDRA (49.0/3600.0) /* max delta RA from one to next, degs*/ #define RAPBIT (MAXDRA/(1<<RABITS)) /* ra delta degrees per bit */ #define RAMASK ((1<<RABITS)-1) /* ra mask */ #define MAGBITS 5 /* mag stored in 5 bits */ #define BRMAG 10.0 /* brightest mag we encode */ #define DIMMAG 22.0 /* dimmest mag we encode */ #define DELMAG (DIMMAG-BRMAG) /* mag range */ #define MAGPBIT (DELMAG/(1<<MAGBITS)) /* mags per bit within range */ #define MAGMASK ((1<<MAGBITS)-1) /* mag mask */ #define HDRLEN 8 /* bytes in ASCII header line */ #define BPIDX 8 /* bytes per index entry */ /* room for one star packet */ #define XE3PKTSZ 3 /* bytes per packet - DO NOT CHANGE */ typedef unsigned char UC; typedef unsigned long UL; typedef UC PKT[XE3PKTSZ]; /* an array of ObjF which can be grown efficiently in multiples of NINC */ typedef struct { ObjF *mem; /* malloced array */ int max; /* max number of cells in mem[] or -1 to just count */ int used; /* number actually in use */ } ObjFArray; #define NINC 32 /* grow mem array this many at a time */ static FILE *xe3open (char *dir, int north, int db, char fn[], char msg[]); static int addDec (ObjFArray *ofap, char *dir, double mag, int dec, double dmin, double dmax, double rmin, double rmax, char *msg); static int addOneObjF (ObjFArray *ap, Obj *op); static void unpack (unsigned *rasump, double cdb, int db, PKT pkt, Obj *op); static void mkxe3name (char *dir, Obj *op); /* return 0 if dir looks like it contains some xe3 files, else -1 */ int xe3chkdir (char *dir, char *msg) { char fn[1024]; FILE *fp; fp = xe3open (dir, 1, 0, fn, msg); if (!fp) return (-1); fclose (fp); return (0); } /* add a collection of XE3 stars around the given location at *opp, which already contains * nop entries. if trouble fill msg[] and return -1, else return count. * N.B. *opp is only changed if we return > 0. */ int xe3fetch (char *dir, double ra, double dec, double fov, double mag, ObjF **opp, int nop, char *msg) { int topd, botd, d; double dmin, dmax; double rov; ObjFArray ofa; int s = 0; /* bug if not given a place to save new stars */ if (!opp) { printf ("xe3fetch with opp == NULL\n"); abort(); } /* enforce limit */ if (fov > MAXGSC22FOV) { static int fovwarned; if (!fovwarned) { xe_msg (1, "All XE3 catalog requests will be limited to %.2f degree FOV", raddeg(MAXGSC22FOV)); fovwarned = 1; } fov = MAXGSC22FOV; } /* switch everything to degrees */ ra = raddeg(ra); dec = raddeg(dec); rov = raddeg(fov/2); /* find top and bottom dec limits, in degrees */ dmin = dec - rov; dmax = dec + rov; botd = (int)floor(dmin); topd = (int)floor(dmax); /* init ofa */ ofa.mem = *opp; ofa.max = nop; ofa.used = nop; /* read across ra range for each dec band, beware 360 wrap */ for (d = botd; d <= topd; d++) { double rovdec = d==90||d==-90 ? 180 : rov/cos(degrad(d)); double rmin = ra - rovdec, rmax = ra + rovdec; int db = d; if (d < -90) { db = -181-d; rmin = 0; rmax = 360; } else if (d > 89) { db = 179-d; rmin = 0; rmax = 360; } else if (rmin < 0) { s = addDec (&ofa, dir, mag, db, dmin, dmax, rmin+360, 360, msg); if (s < 0) break; rmin = 0; } else if (rmax > 360) { s = addDec (&ofa, dir, mag, db, dmin, dmax, 0.0, rmax-360, msg); if (s < 0) break; rmax = 360; } s = addDec (&ofa, dir, mag, db, dmin, dmax, rmin, rmax, msg); if (s < 0) break; } /* finished */ if (s < 0) { if (ofa.mem) free (ofa.mem); return (-1); } if (ofa.mem) *opp = ofa.mem; return (ofa.used); } /* add stars for dec band [-90..89] from dmin..dmax rmin..rmax to ofap. * all units in degrees. * if ok return 0 else -1 with reason in msg[]. * dec is floor of band, ie, -90 .. 89. */ static int addDec (ObjFArray *ofap, char *dir, double mag, int dec, double dmin, double dmax, double rmin, double rmax, char *msg) { int north = dec >= 0; int db = north ? dec : dec+1; double cdb = cos(degrad(db)); int rabase = (int)floor(rmin); char fn[1024]; unsigned rasum, offset; UC idx[BPIDX]; PKT pkt; FILE *fp; Obj o; /* fprintf (stderr, "addDec %g .. %g %g .. %g\n", rmin, rmax, dmin, dmax); */ /* open file */ fp = xe3open (dir, north, db, fn, msg); if (!fp) return (-1); /* read index */ if (fseek (fp, HDRLEN + rabase*BPIDX, SEEK_SET) < 0) { sprintf (msg, "%s:\nindex is short", fn); fclose (fp); return (-1); } if (fread (idx, BPIDX, 1, fp) != 1) { sprintf (msg, "%s:\nindex entry is short", fn); fclose (fp); return (-1); } offset = (idx[0] << 24) | (idx[1] << 16) | (idx[2] << 8) | idx[3]; rasum = (idx[4] << 24) | (idx[5] << 16) | (idx[6] << 8) | idx[7]; /* move to first ra packet */ if (fseek (fp, offset, SEEK_SET) < 0) { sprintf (msg, "%s:\npacket list is short", fn); fclose (fp); return (-1); } /* scan to rmax, work in rads */ dmin = degrad(dmin); dmax = degrad(dmax); rmin = degrad(rmin); rmax = degrad(rmax); while (1) { if (fread (pkt, sizeof(pkt), 1, fp) != 1) { if (feof(fp)) break; sprintf (msg, "%s:\n%s", fn, syserrstr()); fclose (fp); return (-1); } unpack (&rasum, cdb, dec, pkt, &o); if (o.f_RA > rmax) break; if (get_fmag(&o) <= mag && o.f_RA >= rmin && dmin <= o.f_dec && o.f_dec <= dmax) { mkxe3name (dir, &o); if (addOneObjF (ofap, &o) < 0) { sprintf (msg, "not enough memory after %d objects", ofap->used); fclose (fp); return (-1); } } } /* ok */ fclose(fp); return (0); } /* unpack the raw PKT into Obj *op. * dec is -90..89 */ static void unpack (unsigned *rasump, double cdb, int dec, PKT pkt, Obj *op) { unsigned v = (pkt[0] << 16) | (pkt[1] << 8) | pkt[2]; unsigned radelta = (v&RAMASK); double decoffset = (((v>>RABITS)&DECMASK) + 0.5)*DECPBIT; double mag = (((v>>(RABITS+DECBITS))&MAGMASK) + 0.5)*MAGPBIT + BRMAG; int isother = (v >> (RABITS+DECBITS+MAGBITS)); double ra = (*rasump + radelta + 0.5)*RAPBIT/cdb; double dc = dec<0 ? dec+1-decoffset : dec+decoffset; *rasump += radelta; zero_mem ((void *)op, sizeof(ObjF)); op->o_type = FIXED; op->f_class = isother ? 'T' : 'S'; op->f_RA = (float)degrad(ra); op->f_dec = (float)degrad(dc); op->f_epoch = (float)J2000; set_fmag (op, mag); } /* make up a name from the f_RA/dec fields of the given object */ static void mkxe3name (char *dir, Obj *op) { char rstr[32], dstr[32]; char *cat; /* get RA and dec as fixed-length strings */ fs_sexa (rstr, radhr(op->f_RA), 2, 36000); if (rstr[0] == ' ') rstr[0] = '0'; rstr[2] = rstr[3]; rstr[3] = rstr[4]; rstr[4] = rstr[6]; rstr[5] = rstr[7]; rstr[6] = rstr[9]; rstr[7] = '\0'; fs_sexa (dstr, raddeg(op->f_dec), 3, 3600); if (dstr[1] == ' ') { dstr[0] = '+'; dstr[1] = '0'; } if (dstr[1] == '-') { dstr[0] = '-'; dstr[1] = '0'; } if (dstr[0] == ' ') dstr[0] = '+'; dstr[3] = dstr[4]; dstr[4] = dstr[5]; dstr[5] = dstr[7]; dstr[6] = dstr[8]; dstr[7] = '\0'; /* use as much as possible of basename as catalog name */ if ((cat = strrchr(dir,'/')) || (cat = strrchr(dir,'\\'))) cat++; /* skip the / */ else cat = dir; sprintf (op->o_name, "%.*s %s%s", MAXNM-(7+7+2), cat, rstr, dstr); } /* add one ObjF entry to ap[], growing if necessary. * return 0 if ok else return -1 */ static int addOneObjF (ObjFArray *ap, Obj *op) { ObjF *newf; if (ap->used >= ap->max) { /* add room for NINC more */ char *newmem = ap->mem ? realloc ((void *)ap->mem, (ap->max+NINC)*sizeof(ObjF)) : malloc (NINC*sizeof(ObjF)); if (!newmem) return (-1); ap->mem = (ObjF *)newmem; ap->max += NINC; } newf = &ap->mem[ap->used++]; (void) memcpy ((void *)newf, (void *)op, sizeof(ObjF)); return (0); } /* open the given xe3 file. * if ok return name and FILE * else return NULL with reason in msg[] * north is 1 for dec floors 0..89, 0 for dec floors -90..-1. * db is dec band as used in xe3 file, ie, rounded towards 0, ie, -89..89. */ static FILE * xe3open (char *dir, int north, int db, char fn[], char msg[]) { char nschar = north ? 'N' : 'S'; char header[HDRLEN+1]; FILE *fp; char myns; int mydb; /* want abs band in file name and header */ db = abs(db); /* open and check header */ sprintf (fn, "%s/%c%02d.xe3", dir, nschar, db); fp = fopenh (fn, "rb"); if (!fp) { (void) sprintf (msg, "%s:\n%s", fn, syserrstr()); return (NULL); } if (fread (header, HDRLEN, 1, fp) != 1) { sprintf (msg, "%s:\nno header: %s", fn, syserrstr()); fclose (fp); return(NULL); } header[HDRLEN-1] = '\0'; if (sscanf (header, "xe3 %c%2d", &myns, &mydb) != 2 || myns != nschar || mydb != db) { sprintf (msg, "%s:\nnot an XE3 file", fn); fclose (fp); return(NULL); } /* ok */ return (fp); } #ifdef MAIN_TEST /* stand alone dump a region of xe3 to stdout. * cc -o xe3 -DMAIN_TEST -Ilibastro -Ilibip -Llibastro xe3.c -lastro -lm */ #include <errno.h> int main (int ac, char *av[]) { ObjF *ofp = NULL; char msg[1024]; double ra, dec, fov; char *dir; int n; if (ac != 5) { fprintf (stderr, "usage: %s xe3dir ra dec fov (all degs)\n", av[0]); return(1); } dir = av[1]; ra = degrad(atof(av[2])); dec = degrad(atof(av[3])); fov = degrad(atof(av[4])); n = xe3fetch (dir, ra, dec, fov, 100.0, &ofp, msg); if (n < 0) { fprintf (stderr, "%s\n", msg); exit(1); } while (n) { db_write_line ((Obj *)&ofp[--n], msg); printf ("%s\n", msg); } return (0); } char * syserrstr () { return (strerror(errno)); } FILE * fopenh (char *name, char *how) { return (fopen (name, how)); } #endif
C
#version 440 core // this simple vertex program passes position through and colours vertexes based on position. layout (location = 0) in vec4 position; out vec4 frag_color; void main(void) { gl_Position = position; frag_color = vec4(gl_Position.x, gl_Position.y, 0.0, 1.0); }
C
//============================================================================= // // ͏ [input.h] // Author : // //============================================================================= #ifndef _INPUT_H_ #define _INPUT_H_ //***************************************************************************** // }N` //***************************************************************************** // vOƂɎg #define USE_KEYBOARD // 錾ƃL[{[hő”\ɂȂ #define USE_MOUSE // 錾ƃ}EXő”\ɂȂ #define USE_PAD // 錾ƃpbhő”\ɂȂ /* game pad */ #define LEFTSTICK_UP 0x00000001l // L[(.IY<0) #define LEFTSTICK_DOWN 0x00000002l // L[(.IY>0) #define LEFTSTICK_LEFT 0x00000004l // L[(.IX<0) #define LEFTSTICK_RIGHT 0x00000008l // L[E(.IX>0) #define BUTTON_A 0x00000010l // `{^(.rgbButtons[0]&0x80) #define BUTTON_B 0x00000020l // a{^(.rgbButtons[1]&0x80) #define BUTTON_X 0x00000040l // b{^(.rgbButtons[2]&0x80) #define BUTTON_Y 0x00000080l // w{^(.rgbButtons[3]&0x80) #define BUTTON_L 0x00000100l // x{^(.rgbButtons[4]&0x80) #define BUTTON_R 0x00000200l // y{^(.rgbButtons[5]&0x80) #define BUTTON_SELECT 0x00000400l // k{^(.rgbButtons[6]&0x80) #define BUTTON_START 0x00000800l // q{^(.rgbButtons[7]&0x80) #define BUTTON_LSTICK 0x00001000l // rs`qs{^(.rgbButtons[8]&0x80) #define BUTTON_RSTICK 0x00002000l // l{^(.rgbButtons[9]&0x80) #define BUTTON_POV_UP 0x00004000l // \L[ #define BUTTON_POV_DOWN 0x00008000l // \L[ #define BUTTON_POV_RIGHT 0x00010000l // \L[E #define BUTTON_POV_LEFT 0x00020000l // \L[ #define RIGHTSTICK_UP 0x00100000l // EXeBbN #define RIGHTSTICK_DOWN 0x00200000l // EXeBbN #define RIGHTSTICK_RIGHT 0x00400000l // EXeBbNE #define RIGHTSTICK_LEFT 0x00800000l // EXeBbN #define GAMEPADMAX 4 // ɐڑWCpbh̍ő吔Zbg //***************************************************************************** // vg^Cv錾 //***************************************************************************** HRESULT InitInput(HINSTANCE hInst, HWND hWnd); void UninitInput(void); void UpdateInput(void); //---------------------------- keyboard bool GetKeyboardPress(int nKey); bool GetKeyboardTrigger(int nKey); bool GetKeyboardRepeat(int nKey); bool GetKeyboardRelease(int nKey); //---------------------------- mouse BOOL IsMouseLeftPressed(void); // NbN BOOL IsMouseLeftTriggered(void); // NbNu BOOL IsMouseRightPressed(void); // ENbN BOOL IsMouseRightTriggered(void); // ENbNu BOOL IsMouseCenterPressed(void); // NbN BOOL IsMouseCenterTriggered(void); // NbNu long GetMouseX(void); // }EXXɓΒl long GetMouseY(void); // }EXYɓΒl long GetMouseZ(void); // }EXzC[Βl //---------------------------- game pad BOOL IsButtonPressed(int padNo,DWORD button); BOOL IsButtonTriggered(int padNo,DWORD button); #endif
C
#include <stdio.h> int main(int argc, const char *argv[]) { FILE *fp = NULL; char buf[10] = {0}; //fgets(buf,10,stdin); //printf("%s\n",buf); fp = fopen("test","r"); if(fp == NULL) { printf("fail to fopen\n"); return -1; } fgets(buf,10,fp); printf("%s\n",buf); fgets(buf,10,fp); printf("%s\n",buf); fclose(fp); return 0; }
C
#include "../munit/munit.h" #include "event_processor.h" classes_stack *top; classes_list *head; classes_list *tail; static void* clear_list_setup(const MunitParameter params[], void* user_data) { head = malloc(sizeof(classes_list)); tail = malloc(sizeof(classes_list)); head->next = tail; } static void* clear_stack_setup(const MunitParameter params[], void* user_data) { top = malloc(sizeof(classes_stack)); top->class_use = malloc(sizeof(class_use)); top->prev = NULL; } MunitResult clear_list_test(const MunitParameter params[], void* fixture) { clear_list(&head, &tail); munit_assert_ptr_equal(head, NULL); munit_assert_ptr_equal(tail, NULL); return MUNIT_OK; } MunitResult clear_stack_test(const MunitParameter params[], void* fixture) { clear_stack(&top); munit_assert_ptr_equal(top, NULL); return MUNIT_OK; } MunitTest clear_tests[] = { { "clear a list ", clear_list_test, clear_list_setup, NULL, MUNIT_TEST_OPTION_NONE, NULL }, { "clear a stack ", clear_stack_test, clear_stack_setup, NULL, MUNIT_TEST_OPTION_NONE, NULL }, { NULL, NULL, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL } }; const MunitSuite clear_suite = { "clear ", clear_tests, NULL, 1, MUNIT_SUITE_OPTION_NONE };
C
#include <webassembly.h> #include <stdlib.h> #include "headers/game.h" /** Un "buffer" da 5 interi per rappresentare una pedina [y, x, tower_0, tower_1, tower_2] */ int buffered_piece[5]; /** Un "buffer" da 8 interi per rappresentare le 4 mosse possibili di una pedina * [y0, x0, y1, x1, y2, x2, y3, x3]*/ int buffered_moves[8]; /** Un "buffer" da 11 interi per rappresentare gli "indizi" nel gioco, ovvero le pedine che possono essere mosse */ int buffered_hint[11]; /** * Quando viene chiamata, chiama a sua volta la funzione play(...) e ne restituisce il risultato * @param p L'indice della pedina da muovere * @param i La direzione della mossa * @return L'esito della giocata */ export short do_move(short p, short i) { return playGame(p, i); } /** * Lancia la funzione per attendere la mossa della CPU per poi restituirne il risultato * @return L'esito della giocata della CPU */ export short play_CPU() { return awaitCPU(); } /** * Riempie correttamente il buffer per le pedine e ne restituisce il puntatore * @param i L'indice della pedina * @return Il puntatore al buffer * @note Se la pedina fosse NULLA o l'indice fuori dal range [0-21] * allora il buffer viene riempito da valori pari ad una cella disposta */ export int *get_piece(int i) { Piece *p; buffered_piece[0] = -1; buffered_piece[1] = -1; buffered_piece[2] = EMPTY_PIECE; buffered_piece[3] = EMPTY_PIECE; buffered_piece[4] = EMPTY_PIECE; if (i<0 || i>21) return buffered_piece; p = getPiece(i); if (p == NULL) return buffered_piece; buffered_piece[0] = p->y; buffered_piece[1] = p->x; buffered_piece[2] = p->tower[0]; buffered_piece[3] = p->tower[1]; buffered_piece[4] = p->tower[2]; return buffered_piece; } /** * Riempie il buffer delle mosse per poi restituirne il puntatore * @param j l'indice della pedina * @return Il puntatore del buffer * @note Se l'indice della pedina fosse fuori dal range [0-21] o se la pedina fosse NULL, * la funzione riempie il buffer con valori pari a -1 */ export int *get_moves(int j) { int i, team; Piece *p; for (i=0; i<8; i++) { buffered_moves[i] = -1; } if (j < 0 || j > 21) return buffered_moves; if (getCurrentTurn() == CPU_TEAM && getGameState() != STATE_GAME_PVP) return buffered_moves; p = getPiece(j); team = getTeam(p); if (team == getCurrentTurn()) { calculateMoves(team); if (p == NULL) return buffered_moves; for (i = 0; i < 4; i++) { if (isMoveLegal(&p->moves[i])) { buffered_moves[2 * i] = p->moves[i].target.y; buffered_moves[2 * i + 1] = p->moves[i].target.x; } } } return buffered_moves; } /** * Inizializza una nuova sessione di gioco chiamando la funzione corrispondente. * @param type Il valore per il tipo di gioco */ export void new_game(int type) { initGame((short) type); } /** * Restituisce il valore che rappresenta lo stato del gioco al momento della chiamata * @return Lo stato del gioco */ export int get_game_state() { return (int) getGameState(); } /** * Termina la sessione di gioco chiamando l'apposita funzione */ export void end_game() { quitGame(); } /** * Restituisce il valore che rappresenta il turno del gioco al momento della chiamata * @return Il turno del gioco */ export int get_turn() { return getCurrentTurn(); } /** * Restituisce il valore di mobilita' di un giocatore (vedi canTeamMove(...)) * @return int - Un valore intero compreso nel range [0-2] */ export int get_status() { return canTeamMove(getCurrentTurn(), NULL); } /** * Restituisce un buffer da 11 interi contenente tutti gli indici delle pedine che il giocatore puo' muovere * rispetto al turno corrente. * @return Il buffer degli indici delle pedine giocabili * @note Quasi mai le pedine giocabili sono esattamente 11, percio' il buffer viene riempito con tanti elementi * quante le pedine giocabili, mentre gli altri elementi vengono impostati a -1 * @note Gli indici delle pedine giocabili sono condensati all'inizio del buffer, in modo da lasciare una singola * coda di -1 * @note In qualche caso limite nel quale la cella della List ausiliare non viene riempita, semplicente la pedina non * viene conteggiata */ export int *get_hint() { List *l; int i, m, team; for (i=0; i<11; i++) { buffered_hint[i] = -1; } l = createList(); if (l == NULL) { return buffered_hint; } team = getCurrentTurn(); calculateMoves(team); for (i=0; i<22; i++) { int flag = 0; int *hint = malloc(sizeof(int)); Piece *p = getPiece(i); if (hint == NULL) { continue; } if (p == NULL) { continue; } if (getTeam(p) != team) { continue; } for (m=0; m<4; m++) { if (isMoveLegal( &(p->moves[m]) )) { flag = 1; } if (flag) { break; } } if (flag) { *hint = i; pushList(l, hint); } else { free(hint); } } for (i=0; i<l->len; i++) { buffered_hint[i] = *( (int *) getElementAt(l, i) ); } return buffered_hint; }
C
#include "head.h" int goout = 0; int shmid; //共享内存id sensor_data *shmaddr; //指向共享内存区域指针(修改为结构体指针) key_t key; int msgid; MSG msg; pthread_t mythread; int *thread_arg; struct sockaddr_in ser_addr ; int count; //接收数据个数 int sockfd ; //定义套接字 unsigned char recvdata[N] = {0}; //接收数据缓冲区 int main(int argc , char **argv) { ser_addr.sin_family = PF_INET; ser_addr.sin_port = htons(50000); ser_addr.sin_addr.s_addr = inet_addr("192.168.0.5"); /************************************************************ * 创建套接字并绑定套接字 * *********************************************************/ if((sockfd = socket(PF_INET , SOCK_STREAM , 0)) < 0) { printf("%s%s%d%s\n" , __FILE__ ,__FUNCTION__, __LINE__ , strerror(errno)); exit(1); } if(connect(sockfd , (struct sockaddr*)&ser_addr , sizeof(ser_addr)) < 0) { printf("%s%s%d%s\n" , __FILE__ ,__FUNCTION__, __LINE__ , strerror(errno)); exit(1); } printf("port = %d , addr = %s\n" , ntohs(ser_addr.sin_port) , inet_ntoa(ser_addr.sin_addr)); /************************************************************ * 创建共享内存 * *********************************************************/ if((key = ftok("/etc" , 'r')) == -1) //创建key值id { perror("ftok"); exit(-1); } if((shmid = shmget(key , sizeof(sensor_data) , 0666 | IPC_CREAT | IPC_EXCL)) < 0) //获得共享内存id { if((shmid = shmget(key , sizeof(sensor_data) , 0666)) < 0) { perror("shmget"); exit(-1); } } if((shmaddr = (sensor_data*)shmat(shmid , NULL , 0)) == NULL) //映射共享内存首地址 { perror("shmat"); exit(-1); } signal(SIGINT,handler); signal(SIGUSR1,handler); /************************************************************ * 创建线程 * *********************************************************/ if(pthread_create(&mythread , NULL , thread_function , (void*)&sockfd) < 0) //创建进程 { perror("pthread_create failed"); exit(-1); } while((count = recv(sockfd , recvdata ,sizeof(recvdata) , 0)) >= 0) //接收数据 { datadeal(recvdata , count); bzero(recvdata , sizeof(recvdata)); if(count == 0) { printf("Client logout............\n"); kill(getpid() , SIGUSR1); } if( goout == 1) break; } if(pthread_join(mythread , (void **)&thread_arg) < 0) //等待线程结束 { perror("fail to pthread_join"); exit(-1); } printf("wait thread %d\n",*thread_arg); return 0; } /************************************************************ * 线程处理函数 ************************************************************/ void *thread_function(void *arg) { printf("This is %d thread!\n", *(int*)arg - 2); unsigned char msgdata; if((msgid = msgget(key , 0666 | IPC_CREAT)) < 0) //创建消息队列 { perror("msgget"); exit(-1); } printf("msgget success!\n"); while(1) { msgrcv(msgid , &msg , MSGLEN , TYPEA , 0); printf("thread working ....\n"); printf("*****************************************\n"); switch(msg.commend) { case fan_speed_0: printf("fan_speed_0\n"); msgdata = msg.commend; break; case fan_speed_1: printf("fan_speed_1\n"); msgdata = msg.commend; break; case fan_speed_2: printf("fan_speed_2\n"); msgdata = msg.commend; break; case fan_speed_3: printf("fan_speed_3\n"); msgdata = msg.commend; break; case pump_off: printf("pump_off\n"); msgdata = msg.commend; break; case pump_on: printf("pump_on\n"); msgdata = msg.commend; break; case led1_off: printf("led1_off\n"); msgdata = msg.commend; break; case led1_on: printf("led1_on\n"); msgdata = msg.commend; break; case led2_off: printf("led2_off\n"); msgdata = msg.commend; break; case led2_on: printf("led2_on\n"); msgdata = msg.commend; break; default: break; } printf("Begin To Send Commend...........\n"); send(sockfd , &msgdata , sizeof(char) , 0); if( goout == 1) break; } } /************************************************************ * 接收到数据处理函数 ************************************************************/ void datadeal(unsigned char *arg , int count) { int i; sensor_data data = { .air_temp = 0 , .air_hum = 0, .soil_temp = 0, .soil_hum = 0, .liquid_level = 0 , .co2 = 0 , .light = 0 }; for(i = 0 ; i < count ; i++) printf("recvdata[%d] = %d\n" , i , arg[i]); /***********************处理数据****************************/ data.air_temp = arg[0]*10 + arg[1]; data.air_hum = arg[2]*10 + arg[3]; data.soil_temp = arg[4]*10 + arg[5]; data.soil_hum = arg[6]*10 + arg[7]; data.liquid_level= arg[8]; data.co2 = arg[9]*100 + arg[10]; data.light = arg[11]*100 + arg[12]; /*******************将数据放入共享内存***********************/ *shmaddr = data; #if 1 printf("air_temp = %d\n" , data.air_temp); printf("air_hum = %d\n" , data.air_hum); printf("soil_temp = %d\n" , data.soil_temp); printf("soil_hum = %d\n" , data.soil_hum ); printf("liquid_level = %d\n" ,data.liquid_level); printf("co2 density = %d\n" , data.co2); printf("light = %d\n" , data.light); #endif } /************************************************************ * 信号处理函数 ************************************************************/ void handler(int sigio) { if(sigio = SIGINT) { goout = 1; if(shmdt(shmaddr) < 0) //取消内存映射 { perror("shmdt"); exit(-1); } if(shmctl(shmid , IPC_RMID , NULL) < 0) //删除对象 { perror("shmctl"); exit(-1); } printf("shmctl remove!!!\n"); if(msgctl(msgid , IPC_RMID , NULL) < 0) { perror("msgctl"); exit(-1); } printf("msgctl remove!!!\n"); close(sockfd); } if(sigio == SIGUSR1) { close(sockfd); printf("****************connecting***********\n"); if((sockfd = socket(PF_INET , SOCK_STREAM , 0)) < 0) { printf("%s%s%d%s\n" , __FILE__ ,__FUNCTION__, __LINE__ , strerror(errno)); exit(1); } sleep(1000); if(connect(sockfd , (struct sockaddr*)&ser_addr , sizeof(ser_addr)) < 0) { printf("%s%s%d%s\n" , __FILE__ ,__FUNCTION__, __LINE__ , strerror(errno)); exit(1); } printf("***********connect sucessful!********\n"); printf("port = %d , addr = %s\n" , ntohs(ser_addr.sin_port) , inet_ntoa(ser_addr.sin_addr)); } }
C
// Copy input to output // COMP1521 18s1 // MINGFANG JIAO Z5142125 #include <stdlib.h> #include <stdio.h> void copy(FILE *, FILE *); int main(int argc, char *argv[]){ if (argc == 1) { copy(stdin, stdout); } else { // for each command line argument int i; for (i = 0; i < argc; i++) { FILE *input = fopen(argv[i], "r"); if(input == NULL){ printf("Can't read %s\n",argv[i]); } else { copy(stdin,stdout); fclose(input); } } } return EXIT_SUCCESS; } // Copy contents of input to output, char-by-char // Assumes both files open in appropriate mode void copy(FILE *input, FILE *output){ char line[BUFSIZ]; while(fgets(line,BUFSIZ,input) != NULL){ fputs(line,output); } }
C
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <getopt.h> #include "DES.h" ////////////////////////////////////////////////////// // GLOBAL VARIABLES // //////////////////////////////////////////////////// static FILE * output = NULL; ////////////////////////////////////////////////////// // FUNCTIONS // //////////////////////////////////////////////////// // usage static void usage(int status) { if(status == EXIT_SUCCESS) { fprintf(stdout,"Usage: desbox [OPTION] FILE\n" "Encrypt or Descrypt with Whitebox-DES.\n\n" " -d, --decrypt decrypt DES from input file\n" " -e, --encrypt encrypt DES from input file\n" " -o, --output=FILE write result to FILE\n" " -h, --help display this help\n"); } else { fprintf(stderr, "Try 'desbox --help' for more information.\n"); } exit(status); } // a supprimer void printbits(uint64_t v) { for(int ii = 0; ii < 64; ii++) { if( ((v << ii) & FIRSTBIT) == (uint64_t)0) printf("0"); else printf("1"); } } int main(int argc, char ** argv) { // vars bool encrypt = true; FILE * input = NULL; ////////////////////////////////////////////////////// // OPTION PARSER // //////////////////////////////////////////////////// int optc = 0; const char* short_opts = "dehk:o:"; const struct option long_opts[] = { {"decrypt", no_argument, NULL, 'd'}, {"encrypt", no_argument, NULL, 'e'}, {"help", no_argument, NULL, 'h'}, {"output", required_argument, NULL, 'o'}, {NULL, 0, NULL, 0} }; while((optc = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) { switch(optc) { case 'd': // decrypt mode encrypt = false; break; case 'h': // help usage(EXIT_SUCCESS); break; case 'o': // output file output = fopen(optarg, "w"); if(output == NULL) { fprintf(stderr, "Error: don't have permission to write output file"); exit(EXIT_FAILURE); } break; default : // no arguments usage(EXIT_FAILURE); } } ////////////////////////////////////////////////////// // CHECK ARGUMENTS // //////////////////////////////////////////////////// // Check if there is a input file passed as argument if(argv[optind] == NULL) { fprintf(stderr, "Error: Missing input file argument\n"); usage(EXIT_FAILURE); } // Check if we can open the input file input = fopen(argv[optind], "rb"); if(input == NULL) { fprintf(stderr, "Error: can't open input file\n"); usage(EXIT_FAILURE); } // default output file if none is specified if(output == NULL) output = fopen("output.txt", "w"); // check if we have write rights if(output == NULL) { fprintf(stderr, "Error: don't have permission to write output file\n"); exit(EXIT_FAILURE); } ////////////////////////////////////////////////////// // APP // //////////////////////////////////////////////////// // // 3. 16 Rounds of enc/decryption // size_t amount; // used for fwrite uint64_t data; while((amount = fread(&data, 1, 8, input)) > 0) { if(amount != 8) { data = data << (8 * (8 - amount)); } printf("\n amount = %zd, data = ", amount); printbits(data); // initial permutation Permutation(&data, true); // encrypt rounds if(encrypt) { for(int ii = 0; ii < 16; ii++) { rounds(&data, a_key[ii]); } } // decrypt rounds else { data = (data << 32) + (data >> 32); for(int ii = 15; ii >= 0; ii--) { rounds(&data, a_key[ii]); } data = (data << 32) + (data >> 32); } // final permutation Permutation(&data, false); printf("\n\nbeforewriting\n"); if(amount != 8) { data = data << (8 * (8 - amount)); } printf("\n amount = %zd, data = ", amount); printbits(data); // write output fwrite(&data, 1, amount, output); data = 0; } fclose(input); fclose(output); // return EXIT_SUCCESS; }
C
/* * pwm_if.h * * Created on: Dec 21, 2017 * Author: a0225962 */ #ifndef INTERFACES_PWM_IF_H_ #define INTERFACES_PWM_IF_H_ // // The PWM works based on the following settings: // Timer reload interval -> determines the time period of one cycle // Timer match value -> determines the duty cycle // range [0, timer reload interval] // The computation of the timer reload interval and dutycycle granularity // is as described below: // Timer tick frequency = 80 Mhz = 80000000 cycles/sec // For a time period of 0.5 ms, // Timer reload interval = 80000000/2000 = 40000 cycles // To support steps of duty cycle update from [0, 255] // duty cycle granularity = ceil(40000/255) = 157 // Based on duty cycle granularity, // New Timer reload interval = 255*157 = 40035 // New time period = 0.5004375 ms // Timer match value = (update[0, 255] * duty cycle granularity) // #define TIMER_INTERVAL_RELOAD 40035 /* =(255*157) */ #define DUTYCYCLE_GRANULARITY 157 //**************************************************************************** // //! Update the dutycycle of the PWM timer //! //! \param ulBase is the base address of the timer to be configured //! \param ulTimer is the timer to be setup (TIMER_A or TIMER_B) //! \param ucLevel translates to duty cycle settings (0:255) //! //! This function //! 1. The specified timer is setup to operate as PWM //! //! \return None. // //**************************************************************************** void UpdateDutyCycle(unsigned long ulBase, unsigned long ulTimer, unsigned char ucLevel); //**************************************************************************** // //! Setup the timer in PWM mode //! //! \param ulBase is the base address of the timer to be configured //! \param ulTimer is the timer to be setup (TIMER_A or TIMER_B) //! \param ulConfig is the timer configuration setting //! \param ucInvert is to select the inversion of the output //! //! This function //! 1. The specified timer is setup to operate as PWM //! //! \return None. // //**************************************************************************** void SetupTimerPWMMode(unsigned long ulBase, unsigned long ulTimer, unsigned long ulConfig, unsigned char ucInvert); //**************************************************************************** // //! Sets up the identified timers as PWM to drive the peripherals //! //! \param none //! //! This function sets up the folowing //! 1. TIMERA2 (TIMER B) as RED of RGB light //! 2. TIMERA3 (TIMER B) as YELLOW of RGB light //! 3. TIMERA3 (TIMER A) as GREEN of RGB light //! //! \return None. // //**************************************************************************** void InitPWMModules(); //**************************************************************************** // //! Disables the timer PWMs //! //! \param none //! //! This function disables the timers used //! //! \return None. // //**************************************************************************** void DeInitPWMModules(); #endif /* INTERFACES_PWM_IF_H_ */
C
#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> //fibonacci void *fib(void *argv){ int n = *(int *)argv; if(n>=0&&n<=10000){ int arr[10000]={0}; arr[0]=0; arr[1]=1; int i; for(i=2;i<=n;i++){ arr[i]=arr[i-1]+arr[i-2]; } for(i=0;i<=n;i++){ printf(" %d \n",arr[i]); } }else{ printf("Out of Oprand Bound\n"); } } //primeNumbersBySieveOfEratosthenes void *primeNumbers(void *argv){ int n = *(int *)argv; int num[1000] ={0}; int i; for (i = 2; i <=n; ++i ) { num[i] = 1; } // 按照埃拉托斯特尼筛法,将为基数的倍数的所有数标记为非素数。 i = 2; while ( i * i <= n ) { int c; int idx; for ( c = 2, idx = 2*i; idx <=n; ++c, idx = i * c) { num[idx] = 0; } do { ++i; }while ( i * i <= n && num[i] == 0); } printf("primeNumbers less than or equal to %d:\n",n); for(i=0;i<=n;i++){ if(num[i]==1){ printf("%d\n",i); } } } int main(){ //prepare for process creation pid_t pid1; pid_t pid2; pid_t pid3; pid_t pid4; printf("=======FATHER-1|PPID:%d|PID%d\n",getppid(),getpid()); //prepare for thread creation pthread_t tid1; pthread_t tid2; pthread_attr_t attr; pthread_attr_init(&attr); //fork() pid1=fork(); if(pid1==0){ printf("=======CHILD-1|PPID:%d|PID%d\n",getppid(),getpid()); int n=10; pthread_create(&tid1,&attr,fib,&n); pthread_create(&tid2,&attr,primeNumbers,&n); pthread_join(tid1,NULL); pthread_join(tid2,NULL); exit(0); }else{ pid2=fork(); wait(NULL); } if(pid2==0){ printf("=======CHILD-2|PPID:%d|PID%d\n",getppid(),getpid()); pid3=fork(); if(pid3==0){ printf("=======CHILD-3|PPID:%d|PID%d\n",getppid(),getpid()); printf("File are listed bellow:\n"); execl("/bin/ls","ls",NULL); // execl("/bin/ps","ps",NULL); // execl("/bin/cp","cp","hello.c","hello2.c",NULL); exit(0); }else{ pid4=fork(); if(pid4==0){ printf("=======CHILD-4|PPID:%d|PID%d\n",getppid(),getpid()); execlp("/home/oriens/Documents/Operation SYS HW/experiment1/hello","./hello",NULL); exit(0); }else{ wait(NULL); } wait(NULL); } exit(0); }else{ wait(NULL); } return 0; }
C
/** * @file testebbchar.c * @author Derek Molloy * @date 7 April 2015 * @version 0.1 * @brief A Linux user space program that communicates with the ebbchar.c LKM. It passes a * string to the LKM and reads the response from the LKM. For this example to work the device * must be called /dev/ebbchar. * @see http://www.derekmolloy.ie/ for a full description and follow-up descriptions. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <stdint.h> #include <unistd.h> int main(){ int ret, fd; uint8_t receive = 0; printf("Starting device test code example...\n"); fd = open("/dev/nes", O_RDONLY); // Open the device with read/write access if (fd < 0){ perror("Failed to open the device..."); return errno; } printf("Reading from the device...\n"); while(1) { ret = read(fd, (void*)&receive, sizeof(receive)); // Read the response from the LKM if (ret < 0){ perror("Failed to read the message from the device."); return errno; } printf("Button values: %x\n", receive); usleep(16666); } printf("End of the program\n"); return 0; }
C
/* version 88/06/02:Mirella 5.0 */ /********************* MIRAMEBA.C ****************************************/ /* This module is essentially the numerical recipes amoeba program, modified for Mirella/tools support */ #ifdef VMS #include mirella #else #include "mirella.h" #endif static float ALPHA=1.0; static float BETA=0.5; static float GAMMA=2.0; mirella normal am_iter = 0; /* final iteration in samoeba */ mirella float am_tol = 2.e-6; /* tolerance in samoeba */ mirella int am_pflg = 0; /* flag to print iteration and error */ mirella int am_debug = 0; /* flag to pring intermediate results */ mirella int am_itmax = 500; /* maximum number of iterations */ extern int interrupt; /* * p is a matrix[ndim+1][ndim] which is initialized to the n+1 vectors of * the starting simplex; at the end, any row is a solution. * ndim is the dimension of the space (number of parameters) * ftol is the fractional tolerance (try 2.e-6 for singles) * funk is the pointer to the function which you are trying to minimize; it * takes a float vector argument of length ndim. * piter is a pointer to the iteration number. * the function returns funk averaged over the final simplex. */ mirella double amoeba(p,ndim,ftol,funk,piter) float **p; int ndim; double ftol; double (*funk)(); normal *piter; { int mpts,j,inhi,ilo,ihi,i; float yprr,ypr,rtol,*pr,*prr,*pbar,ybar; float *y; float step; mpts=ndim+1; y=(float *)malloc((mpts)*sizeof(float)); pr=(float *)malloc((ndim)*sizeof(float)); prr=(float *)malloc((ndim)*sizeof(float)); pbar=(float *)malloc((ndim)*sizeof(float)); /* init y to values of funk at vertices */ for(i=0;i<mpts;i++) y[i] = (*funk)(p[i]); *piter=0; ilo = 0; if(am_pflg) scrprintf("\n"); begin: for(;;) { ilo=0; if (y[0] > y[1]) { ihi=0; inhi=1; } else { ihi=1; inhi=0; } for(i=0;i<mpts;i++) { if (y[i] < y[ilo]) ilo=i; if (y[i] > y[ihi]) { inhi=ihi; ihi=i; } else if (y[i] > y[inhi]) if (i != ihi) inhi=i; } if(am_debug){ scrprintf("\ni,yl,yh=%3d %12.3f %12.3f\nx[ilo]:",*piter,y[ilo],y[ihi]); for(j=0;j<ndim;j++) scrprintf(" %7.5f",p[ilo][j]); } if ((*piter)++ >= am_itmax) { scrprintf("\nToo many iterations in AMOEBA"); goto cleanup; } rtol=2.0*fabs(y[ihi]-y[ilo])/(fabs(y[ihi])+fabs(y[ilo])); if(am_pflg && !((*piter)%10)){ ybar = 0; for(i=0;i<mpts;i++) ybar += y[i]; ybar /= mpts; scrprintf("\ri=%3d f=%f tol=%f",*piter,ybar,rtol); } if (rtol < ftol) break; if(dopause()){ interrupt = 0; scrprintf("\nDo you want to rescale and start again?"); if(_yesno()){ scrprintf("\nStepsize? "); scanf("%f",&step); j=0; for(i=0;i<mpts;i++) if(i != ilo) p[i][j++] += step; goto begin; }else goto cleanup; } for(j=0;j<ndim;j++) pbar[j]=0.0; for(i=0;i<mpts;i++) if (i != ihi) for(j=0;j<ndim;j++) pbar[j] += p[i][j]; for(j=0;j<ndim;j++){ pbar[j] /= ndim; pr[j]=(1.0+ALPHA)*pbar[j]-ALPHA*p[ihi][j]; } ypr=(*funk)(pr); if (ypr <= y[ilo]) { for(j=0;j<ndim;j++) prr[j]=GAMMA*pr[j]+(1.0-GAMMA)*pbar[j]; yprr=(*funk)(prr); if (yprr < y[ilo]) { for(j=0;j<ndim;j++) p[ihi][j]=prr[j]; y[ihi]=yprr; } else { for(j=0;j<ndim;j++) p[ihi][j]=pr[j]; y[ihi]=ypr; } } else if (ypr >= y[inhi]) { if (ypr < y[ihi]) { for(j=0;j<ndim;j++) p[ihi][j]=pr[j]; y[ihi]=ypr; } for(j=0;j<ndim;j++) prr[j]=BETA*p[ihi][j]+(1.0-BETA)*pbar[j]; yprr=(*funk)(prr); if (yprr < y[ihi]) { for(j=0;j<ndim;j++) p[ihi][j]=prr[j]; y[ihi]=yprr; } else { for(i=0;i<mpts;i++) { if (i != ilo) { for(j=0;j<ndim;j++) { pr[j]=0.5*(p[i][j]+p[ilo][j]); p[i][j]=pr[j]; } y[i]=(*funk)(pr); } } } } else { for(j=0;j<ndim;j++) p[ihi][j]=pr[j]; y[ihi]=ypr; } } cleanup: free(y); free(pbar); free(prr); free(pr); ypr = 0.; for(i=0;i<mpts;i++) ypr += (*funk)(p[i]); ypr /= (float)mpts; if(am_pflg) scrprintf("\n"); am_iter = *piter; /* export to mirella */ return ypr; } /* * simple amoeba interface */ mirella double samoeba(x,dx,funk,nd) float *x, *dx; /* initial guess, initial deltas */ double (*funk)(); /* function */ int nd; /* dimension */ { float ***mp; float **p; int i,j; float ret; mp = (float ***)matralloc("amoebamat",nd+1,nd,sizeof(float)); p = *mp; for(i=0;i<nd+1;i++){ for(j=0;j<nd;j++){ p[i][j] = x[j]; if(j == i-1) p[i][j] += dx[j]; } } ret = amoeba(p,nd,am_tol,funk,&am_iter); bufcpy((char *)x,(char *)p[0],nd*sizeof(float)); chfree((char *)mp); return ret; }
C
FLOAT identity(FLOAT x) { return x; } FLOAT dIdentity(FLOAT y) { return 1; } FLOAT sigmoid(FLOAT x) { return 1 / (1 + exp(-x)); } FLOAT dSigmoid(FLOAT y) { return y * (1 - y); } //using fast tanh of math.h instead /* FLOAT tanh(FLOAT x) { return (2 * sigmoid(2 * x) - 1); } */ FLOAT dTanh(FLOAT y) { return 1 - y * y; }
C
#include <stdlib.h> #include <signal.h> #include <string.h> int main() { int i; char *ptr; //for(i=0; i < 32 * 1024; i +=16) for(i=0; i < 8192; i += 1024 ) { ptr = (char *) malloc( i ); memset(ptr, 0xFF, i ); fprintf(stderr,"%p ", ptr ); } ptr[-1] = '0'; //free(ptr); //free(ptr); raise(SIGSEGV); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: slupe <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/04 16:48:12 by slupe #+# #+# */ /* Updated: 2019/12/05 20:55:02 by slupe ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int h_count(char *line) { int count; count = 0; if (!line) return (0); while (*line) { if (*line == '#') count++; line++; } return (count); } int read_one(char *line) { int n_line; int count; n_line = 0; count = 0; while (n_line < 4) { count += h_count(line); if (ft_strlen(line) != 4 || count > 4) //|| !chk_char(line)) { printf("FAIL 1: count = %d, strlen = %ld\n", count, ft_strlen(line)); exit(EXIT_FAILURE); } n_line++; } if (count < 4) { printf("FAIL 2"); exit(EXIT_FAILURE); } return (1); } int main(int argc, char **argv) { int fd; char *line; line = 0; if (argc == 2) { fd = open(argv[1], O_RDONLY); while (1) { /*if (get_next_line(fd, &line) == 1) { read_one(line); ft_putstr(line); ft_putchar('\n'); }*/ else break ; } close(fd); } return (0); }
C
#include<stdio.h> #include<string.h> #include<limits.h> #define f(i,x,y) for(int i=x;i<y;i++) #define inf 9999 int g[1000][1000], n, seen[1000]; void fw() { int dist[n][n]; f(i,0,n) f(j,0,n) dist[i][j] = g[i][j]; f(k,0,n) f(i,0,n) f(j,0,n) if(dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; f(i,0,n) f(j,0,n) if(dist[i][j]<=1) { f=1; if(!seen[i]) printf("%d,",i); seen[i]=1; } if(!f) printf("No"); } int main() { int m; scanf("%d %d", &n, &m); f(i,0,n) f(j,0,n) { if(i==j) g[i][j] = 0; else g[i][j] = inf; } while(m--) { int x,y; scanf("%d %d", &x, &y); g[x][y]=1; } fw(); }
C
/* MIT License Copyright (c) 2019 Elliot K Bewey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "csasm/csasm.h" CS_RETCODE_T cerr_print(void) { fprintf(stderr, "[asm_err] "); return CSASM_SUCCESS; } int add_label(const indexnum_t line, char* label, linedarr_t* linearr) { indexnum_t length = linearr->length; lined_t* lined = linearr->lined; lined = malloc(sizeof(lined_t) * length + 1); if(lined == NULL) { cerr_print(); fprintf(stderr, "Failed to alloc label space\n"); return CSASM_FAILURE; } lined_t ln_data = { .label = label, .line = line }; linearr->lined[linearr->length] = ln_data; linearr->length += 1; return CSASM_SUCCESS; } indexnum_t get_label_line(const char* label, const linedarr_t* linearr) { for(indexnum_t i = 0; i < linearr->length; i++) { if(strcmp(linearr->lined[i].label, label) == 0) { return linearr->lined[i].line; } } return -1; } CS_RETCODE_T csasm_add(tknd_t data, csparams_t* params) { if(data.operand == NULL) { cerr_print(); fprintf(stderr, "ADD requires operand ADDR\n"); exit(CSASM_FAILURE); } long addr = strtol(data.operand, NULL, 0); params->acc += params->memory[addr]; return CSASM_SUCCESS; } CS_RETCODE_T csasm_out(tknd_t data, csparams_t* params) { #ifdef CSASM_DLONG_NUMBERS printf("[asm_out] %lld\n", params->acc); #else printf("[asm_out] %ld\n", params->acc); #endif return CSASM_SUCCESS; } CS_RETCODE_T csasm_mov(tknd_t data, csparams_t* params) { if(data.operand == NULL) { cerr_print(); fprintf(stderr, "MOV requires operand ADDR\n"); exit(CSASM_FAILURE); } long addr = strtol(data.operand, NULL, 0); params->memory[addr] = params->acc; return CSASM_SUCCESS; } CS_RETCODE_T csasm_ldr(tknd_t data, csparams_t* params) { if(data.operand == NULL) { cerr_print(); fprintf(stderr, "LDR requires operand ADDR\n"); exit(CSASM_FAILURE); } long addr = strtol(data.operand, NULL, 0); // 0 = hex params->acc = params->memory[addr]; return CSASM_SUCCESS; } CS_RETCODE_T csasm_set(tknd_t data, csparams_t* params) { if(data.operand == NULL) { cerr_print(); fprintf(stderr, "SET requires operand VAL\n"); exit(CSASM_FAILURE); } long val = strtol(data.operand, NULL, 10); // 10 for base ten params->acc= val; return CSASM_SUCCESS; } CS_RETCODE_T csasm_lbl(tknd_t data, csparams_t* params) { return CSASM_SUCCESS; } CS_RETCODE_T csasm_jmp(tknd_t data, csparams_t* params) { if(data.operand == NULL) { cerr_print(); fprintf(stderr, "JMP requires operand LABEL\n"); exit(CSASM_FAILURE); } int ret = get_label_line(data.operand, &params->lined); if(ret < 0) { cerr_print(); fprintf(stderr, "Failed to JMP to label %s (does it exist?)\n", data.operand); exit(CSASM_FAILURE); } params->line = ret; return CSASM_SUCCESS; } CS_RETCODE_T csasm_inp(tknd_t data, csparams_t* params) { long val = 0; scanf("%ld", &val); params->acc = val; return CSASM_SUCCESS; } CS_RETCODE_T csasm_empty(tknd_t data, csparams_t* params) { return CSASM_SUCCESS; } char* open_file(const char* dir) { const char* mode = "r"; FILE * file_ptr; char* buffer = NULL; long length; file_ptr = fopen(dir, mode); if(file_ptr) { fseek(file_ptr, 0, SEEK_END); length = ftell(file_ptr) + 1; fseek(file_ptr, 0, SEEK_SET); buffer = malloc(length); if(buffer == NULL) { perror("Failed to malloc file buffer"); exit(EXIT_FAILURE); } fread(buffer, 1, length, file_ptr); fclose(file_ptr); buffer[length-1] = '\0'; } return buffer; } int str_opcode(const char* str, const deftkn_t* tokens, const size_t length) { for(size_t i = 0; i < length; i++) { deftkn_t curr_tkn = tokens[i]; if(strcmp(curr_tkn.scode, str) == 0) { return curr_tkn.icode; } } return -1; } void print_token(const tkn_t token) { printf("%u : %s\r\n", token.opcode, token.data.operand); } CS_RETCODE_T tokenize(char* str, const deftkn_t* deftkns, const size_t deftkns_length, tkn_t* out) { char* opcode = strtok_r(str, " ", &str); if(opcode == NULL) { cerr_print(); fprintf(stderr, "Tokenize opcode fail\n"); return CERR_TOKENIZE_OPCODE_FAIL; } int i_opcode = str_opcode(opcode, deftkns, deftkns_length); if(i_opcode < 0) { return CERR_UNKNOWN_OPCODE; } char* operand = strtok_r(NULL, " ", &str); tknd_t token_data = { .operand = operand }; tkn_t token = { .opcode = i_opcode, .data = token_data }; *out = token; return CSASM_SUCCESS; } CS_RETCODE_T tokenize_lines(char* str, const deftkn_t* deftkns, const size_t deftkns_length, size_t* tkn_length, tkn_t** out) { long buffered_length = 16; long index = 0; char* tok_ptr = NULL; tok_ptr = strtok_r(str, "\n", &str); tkn_t* tokens = malloc(sizeof(tkn_t) * buffered_length); while(tok_ptr != NULL) { if(index >= buffered_length) { buffered_length = buffered_length * 2; tokens = realloc(tokens, sizeof(tkn_t) * buffered_length); buffered_length = buffered_length; } long length = strlen(tok_ptr) + 1; char* buffer = malloc(length); if(buffer == NULL) { perror("Failed to malloc tkn buffer"); return CERR_TKN_MALLOC_FAIL; } buffer[length-1] = '\0'; snprintf(buffer, length, "%s", tok_ptr); tkn_t token; CS_RETCODE_T token_status = tokenize(buffer, deftkns, deftkns_length, &token); if(token_status != 0) { if(token_status == CERR_UNKNOWN_OPCODE) { cerr_print(); fprintf(stderr, "Unknown opcode \"%s\" on line %lu\n", buffer, index); } return token_status; } tokens[index] = token; buffered_length = index + 1; tokens[index].data.src = buffer; tok_ptr = strtok_r(NULL, "\n", &str); index = index + 1; *tkn_length = index; } *out = tokens; return CSASM_SUCCESS; } csparams_t gen_params(void) { linedarr_t lined_arr = { .length = 0, .lined = malloc(sizeof(lined_t)) }; csparams_t new_params = { .lined = lined_arr, .line = 0 }; return new_params; } CS_RETCODE_T free_tokens(tkn_t* tkns, const size_t tkns_length) { for(size_t i = 0; i < tkns_length; i++) { free(tkns[i].data.src); } free(tkns); return CSASM_SUCCESS; } CS_RETCODE_T process_tokens(csparams_t* params, const tkn_t* tkns, const size_t tkns_length, const deftkn_t* deftkns, const size_t deftkns_length) { // Temporary int lbl_opcode = str_opcode("lbl", deftkns, deftkns_length); // Preprocessing for(params->line = 0; params->line < tkns_length; params->line++) { tkn_t token = tkns[params->line]; if(token.opcode == lbl_opcode) { int astatus = add_label(params->line, token.data.operand, &params->lined); if(astatus != 0) { return astatus; } } } // Runtime params->line = 0; for(params->line = 0; params->line < tkns_length; params->line++) { tkn_t token = tkns[params->line]; deftkns[token.opcode].def_func(token.data, params); } free(params->lined.lined); } CS_RETCODE_T exit_status(const CS_RETCODE_T status) { if(status == 0) { printf("Program exited OK (%d)\n\r", status); } else { printf("Program exited with error code (%d)\n\r", status); } return status; }
C
#include <stdio.h> #include <stdlib.h> #include "mem.h" void* alloc(size_t size){ void *a = mem_alloc(size); printf("Allocated %ld bytes at : %p\n",size,a); return a; } void free_alloc(void *a){ mem_free(a); printf("Freed %p\n",a); } int main(int argc,char **argv){ mem_init(); void *a = alloc(455), *b = alloc(333); free_alloc(a); a = NULL; b = NULL; b++; return 0; }
C
#include <avr/io.h> #include <stdlib.h> #include <string.h> #include <avr/pgmspace.h> #include "F_CPU.h" #include "util/delay.h" #include "oled.h" #include "joystick.h" #include "menu.h" #include "menu_names.h" #include "sram.h" Node newNode(MENU menu){ // Assign struct to Node Node node; node.menu = menu; // Parent and children node.parent = NULL; node.child1 = NULL; node.child2 = NULL; node.child3 = NULL; return node; } void initMenu(void){ oled_init(); oled_clearScreen(); // Clear screen, go to pos (0, 0) _delay_ms(500); // Making the Main Menu struct MENU MainMenu; // Main menu interface MainMenu.title = MM_title_string; MainMenu.menu1 = MM_menu1_string; MainMenu.menu2 = MM_menu2_string; MainMenu.menu3 = MM_menu3_string; // Sub Menus MENU PlayGame; MENU HighScores; MENU Settings; // Play Game interface PlayGame.title = PG_title_string; PlayGame.menu1 = PG_menu1_string; PlayGame.menu2 = PG_menu2_string; PlayGame.menu3 = PG_menu3_string; // High Scores interface HighScores.title = HS_title_string; char HS1[16], HS2[16], HS3[16]; uint8_t HIGHSCORES[3]; SRAM_read_highscores(&HIGHSCORES[0]); // Converting uint8_t to string itoa(HIGHSCORES[0], HS1, 10); itoa(HIGHSCORES[1], HS2, 10); itoa(HIGHSCORES[2], HS3, 10); HighScores.menu1 = HS3; HighScores.menu2 = HS2; HighScores.menu3 = HS1; // Settings interface Settings.title = SETTING_title_string; Settings.menu1 = SETTING_menu1_string; Settings.menu2 = SETTING_menu2_string; Settings.menu3 = SETTING_menu3_string; // Initialize main menu mainMenuNode = newNode(MainMenu); playGameNode = newNode(PlayGame); highScoresNode = newNode(HighScores); settingsNode = newNode(Settings); // Addressen til mainMenu.child1 blir satt til addressen settings mainMenuNode.child1 = &playGameNode; mainMenuNode.child2 = &highScoresNode; mainMenuNode.child3 = &settingsNode; playGameNode.parent = &mainMenuNode; highScoresNode.parent = &mainMenuNode; settingsNode.parent = &mainMenuNode; // Making Main Menu constructMenu(&mainMenuNode); } void constructMenu(Node* node){ // Initialize screen oled_clearScreen(); currentNode = node; arrowPagePos = 2; setArrow(arrowPagePos); // Construct menu oled_pos(0,10); oled_print(node->menu.title); oled_pos(2,20); oled_print(node->menu.menu1); oled_pos(3,20); oled_print(node->menu.menu2); oled_pos(4,20); oled_print(node->menu.menu3); _delay_ms(500); } void removeArrow(int line){ oled_pos(line, 0); for(int i = 0; i < 8*strlen(Arrow_string); i++){ oled_write_data(0x00); } } void setArrow(int line){ if(line < 5 && line > 1){ removeArrow(arrowPagePos); oled_pos(line, 0); oled_print(Arrow_string); arrowPagePos = line; } _delay_ms(300); // Such that the user have time to put joystick to neutral } const char* update_menu(){ JOY_dir_t joyDirection = getJoystickDirection(50); if(joyDirection == UP){ setArrow(arrowPagePos-1); } if(joyDirection == DOWN){ setArrow(arrowPagePos+1); } if(joyDirection == LEFT && currentNode->parent != NULL){ constructMenu(currentNode->parent); } if(joyDirection == RIGHT){ switch(arrowPagePos){ case 2: if(currentNode->child1 != NULL){ constructMenu(currentNode->child1); }else if ( strcmp(currentNode->menu.menu1, "Easy") == 0 ){ return currentNode->menu.menu1; } break; case 3: if(currentNode->child2 != NULL){ constructMenu(currentNode->child2); }else if ( strcmp(currentNode->menu.menu2, "Medium") == 0 ){ return currentNode->menu.menu2; } break; case 4: if(currentNode->child3 != NULL){ constructMenu(currentNode->child3); }else if ( strcmp(currentNode->menu.menu3, "Hard") == 0 ){ return currentNode->menu.menu3; } break; default: break; } } return NULL; }
C
/* ECP: FILEname=fig9_22.c */ #include <stdio.h> #include "complex.h" main( void ) { Complex A, B; A = InitComplex( 2.0, 4.0 ); B = InitComplex( 0.0, 0.0 ); AddComplex( A, A, B ); printf( "B is: " ); PrintComplex( B ); printf( "\n" ); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #define MAX_BUF 128 main() { int n, fd[2]; pid_t pid; char buf[MAX_BUF]; if (pipe(fd) < 0) { perror("pipe"); exit(1); } if ((pid = fork()) < 0) { perror("fork"); exit(1); } else if (pid == 0) { printf("Child is using %d for writing.\n", fd[1]); printf("Child is using %d for reading.\n", fd[0]); close(fd[1]); if ((n = read(fd[0], buf, MAX_BUF)) < 0) { perror("read"); exit(1); } printf("Child : Received data from parent: %s\n", buf); fflush(stdout); write(STDOUT_FILENO, buf, n); // console에 parent로 부터 받은 data를 출력. } else { printf("Parent is using %d for wrintg.\n", fd[1]); printf("Parent is using %d for reading.\n", fd[0]); close(fd[0]); strcpy(buf, "Hello, World!\n"); printf("Parent: Send data to child\n"); printf("strlen(buf) : %d", strlen(buf)+1); write(fd[1], buf, strlen(buf)); // strlen(buf) + '\n' 을 자식에게 send해준다. } exit(0); }
C
#include "ft_printf.h" char *ajout_zero_o(char *chaine) { int lon; char *nouvelle; lon = ft_strlen(chaine); if (lon == 1 && chaine[0] == '0') return (chaine); if (!(nouvelle = ft_strnew(lon + 1))) return (chaine); nouvelle[0] = '0'; nouvelle = ft_strncat(nouvelle, chaine, lon); free(chaine); return (nouvelle); } char *ajout_0x_x(char c, char *chaine) { int lon; char *nouvelle; lon = ft_strlen(chaine); if (lon == 1 && chaine[0] == '0') return (chaine); if (!(nouvelle = ft_strnew(lon + 2))) return (chaine); nouvelle[0] = '0'; nouvelle[1] = (c == 'x') ? 'x' : 'X'; nouvelle = ft_strncat(nouvelle, chaine, lon); free(chaine); return (nouvelle); } char *modif_hash(t_maillon **maillon, char c) { if (c == 'o' || c == 'O') return (ajout_zero_o((*maillon)->chaine)); else if (c == 'x' || c == 'X') return (ajout_0x_x((*maillon)->conversion, (*maillon)->chaine)); return ((*maillon)->chaine); } char *modif_plus(t_maillon **maillon, char c) { char *chaine; char *nouvelle; int lon; chaine = (*maillon)->chaine; lon = ft_strlen(chaine); if ((*maillon)->conversion == 'd' || (*maillon)->conversion == 'i') { if (chaine[0] != '-') { if (!(nouvelle = ft_strnew(lon + 1))) return (chaine); nouvelle[0] = c; nouvelle = ft_strncat(nouvelle, chaine, lon); free(chaine); return (nouvelle); } } return (chaine); }
C
#include <stdio.h> /** * main - program start * Description: generate a lowercase alphabet string using putchar * Return: 0 */ int main(void) { char letter = 'a'; char z = 'z'; while (letter <= z) { putchar (letter); letter++; } putchar ('\n'); return (0); }
C
//L8_z2 //while((smietnik=getchar())!='\n'); #include <stdio.h> #include <string.h> #define N 10 #define M 10000 void wyswietl(char *, char *); void generuj_dane(double (*)[N]); void zapisz_do_pliku_bin(char *, double (*)[N]); void zapisz_do_pliku_text(char *, double (*)[N]); int main(int argc, char **argv) { char nazwa[N],nazwa2[N], tekstowy[]="r", binarny[]="rb", smietnik; int i=0, j=0, len; double DANE[N][N]={0.0}; generuj_dane(DANE); printf("\npodaj nazwe pliku do ktorego zapisac w formie tekstowej: \n"); fgets(nazwa,10,stdin); len=strlen(nazwa); if(nazwa[len-1]=='\n') nazwa[len-1]='\0'; strcat (nazwa, ".txt"); zapisz_do_pliku_text(nazwa,DANE); printf("\npodaj nazwe pliku do ktorego zapisac w formie binarnej: \n"); fgets(nazwa2,10,stdin); len=strlen(nazwa2); if(nazwa2[len-1]=='\n') nazwa2[len-1]='\0'; strcat (nazwa2, ".txt"); zapisz_do_pliku_bin(nazwa2,DANE); printf("tekstowy %s\n ",nazwa); wyswietl(nazwa,tekstowy); printf("\nbinarny %s\n",nazwa2); wyswietl(nazwa2,binarny); return 0; } void generuj_dane(double (*t)[N]) { int i, j, w=1; for (j=0; j<=9;j++) for (i=0; i<=9;i++) { *(*(t+j)+i)=w++; } } void zapisz_do_pliku_bin(char *plik, double (*t)[N]) { int i, j; FILE *fp; fp=fopen(plik,"w+b"); if (fp==NULL) fprintf(stderr,"Blad otwarcia pliku\n"); else { for (j=0; j<=9;j++) for (i=0; i<=9;i++) { fprintf(fp,"%lf ",*(*(t+j)+i)); // fputs(((char) *(*(t+j)+i)),fp); } } fclose(fp); } void zapisz_do_pliku_text(char *plik, double (*t)[N]) { int i, j; FILE *fp; fp=fopen(plik,"w+"); if (fp==NULL) fprintf(stderr,"Blad otwarcia pliku\n"); else { for (j=0; j<=9;j++) for (i=0; i<=9;i++) { fprintf(fp,"%lf ",*(*(t+j)+i)); } } fclose(fp); } void wyswietl(char *plik, char *tryb) { FILE *fp; char wynik[M]; fp=fopen(plik,tryb); if (fp==NULL) fprintf(stderr,"Blad otwarcia pliku\n"); else { fgets(wynik,10000,fp); fputs(wynik,stdout); } }
C
#pragma warning(disable:4996) /*two_func.c -- 一个文件中包含两个函数*/ #include<stdio.h> void butler(void);/* ANSI/ISO C 函数原型*/ int main() { printf("I will summon the butler function.\n"); butler(); printf("Yes.Bring me some tea and writeable DVDs.\n"); return 0; } void butler(void)/* 函数定义开始 */ { printf("You rang,sir?\n"); }
C
void pointers() { //normal integer variable int i = 1234; //* means pointer variable //0 is a special memory address that is always invalid, alwasy initialize this int * p = 0; //get the pointer of something & address of indicator p = &i; //get the value back out of the pointer, the value that is in the memory space the pointer is pointing to int j = *p; //this does not change p, it puts the value into the memory that p is pointing to *p = 23434; } void array() { //unitialized int numbers[4]; //initialized int numbers2[3] = {1,3,4}; //anthing not specified will be zerro int numbers3[3] = { 1,3 }; //there is no length property in arrays //find the number of bytes of the array int sizeOfarrayinbytes = sizeof(numbers); //get the actual length //divide total number of bytes by the size of the byte of one thing int the arrray int lengthofarray = sizeOfarrayinbytes / sizeof(numbers[0]); //get pointer to first memory location of array int * p = numbers; //get pointer to the end of the array, the point after the last element, so the next location where another array could start int * end = p + lengthofarray; //another way to loop for (;p != end; ++p) { //this will be the value that is in each element of the array //the pointer starts at the beginning and because it know that its an int it knows to print out 32 bits from the pointer address //then add 1 which really means asdd 32 bits to get to the next address //print *p } } //we are passing in a pointer to an array of integers //but this function does not know how many elements are in the array //all the information that it has is the address of the beginnings and the type of the things in the array (int) //you have to pass arrays to functions as pointers, not the actual array //you cannot do sizeof on the pointer because it will just tell you the size of the pointer (int) 4 bytes //you actually have to require the size as a paramter void print(int * numbers, int size) { } //or you can just send in the the address of the begin and the end and do the loop that way void printanotherway(int * begin, int * end) {}
C
#include <MLV/MLV_all.h> #define RED 1 #define BLUE 2 int main() { int c = RED; int x,y; int clique = 0; MLV_create_window("rectangle","shapes",1080,720); MLV_draw_filled_rectangle(5,5,1070,710, MLV_COLOR_RED); MLV_actualise_window(); MLV_wait_mouse(&x,&y); while (clique != 1) { if (c == RED) { MLV_clear_window(MLV_COLOR_BLACK); MLV_draw_filled_rectangle(5,5,1070,710, MLV_COLOR_BLUE); MLV_actualise_window(); MLV_wait_mouse(&x,&y); c = BLUE; } else { MLV_clear_window(MLV_COLOR_BLACK); MLV_draw_filled_rectangle(5,5,1070,710, MLV_COLOR_RED); MLV_actualise_window(); MLV_wait_mouse(&x,&y); c = RED; } } }
C
#ifndef __ENEMIES_H__ #define __ENEMIES_H__ #include "gf2d_entity.h" typedef enum { ET_RED, ET_BLUE, ET_GREEN, ET_YELLOW, ET_SUPER }EnemyTypes; /** * @brief spawn a new red flower * @param parent the parent to spawnt he flower on, null is at the start of the level's next path * @return the spawned entity */ Entity* redSpawn(Entity* parent); /** * @brief spawn a new blue flower * @param parent the parent to spawnt he flower on, null is at the start of the level's next path * @return the spawned entity */ Entity* blueSpawn(Entity* parent); /** * @brief spawn a new green flower * @param parent the parent to spawnt he flower on, null is at the start of the level's next path * @return the spawned entity */ Entity* greenSpawn(Entity* parent); /** * @brief spawn a new yellow flower * @param parent the parent to spawnt he flower on, null is at the start of the level's next path * @return the spawned entity */ Entity* yellowSpawn(Entity* parent); /** * @brief spawn a new super flower * @param parent the parent to spawnt he flower on, null is at the start of the level's next path * @return the spawned entity */ Entity* superSpawn(Entity* parent); /** * @brief red flower's think. Kills flower on <=0 health. Restores max speed after slow over. * @param self the flower to do thinking */ void redThink(Entity* self); /** * @brief blue flower's think. Kills flower on <=0 health. Restores max speed after slow over. * @param self the flower to do thinking */ void blueThink(Entity* self); /** * @brief green flower's think. Kills flower on <=0 health. Restores max speed after slow over. * @param self the flower to do thinking */ void greenThink(Entity* self); /** * @brief yellow flower's think. Kills flower on <=0 health. Restores max speed after slow over. * @param self the flower to do thinking */ void yellowThink(Entity* self); /** * @brief super flower's think. Kills flower on <=0 health. Restores max speed after slow over. * @param self the flower to do thinking */ void superThink(Entity* self); /** * @brief All flowers' move function. Handles redirection on path. * @param self the flower to do moving */ void flowerMove(Entity* self); /** * @brief kill a red flower * @param self the flower to kill * @return NULL */ Entity* redDie(Entity* self); /** * @brief kill a blue flower * @param self the flower to kill * @return the red flower spawned on death */ Entity* blueDie(Entity* self); /** * @brief kill a green flower * @param self the flower to kill * @return the blue flower spawned on death */ Entity* greenDie(Entity* self); /** * @brief kill a yellow flower * @param self the flower to kill * @return the yellow flower spawned on death */ Entity* yellowDie(Entity* self); /** * @brief kill a super flower * @param self the flower to kill * @return the yellow flower spawned on death */ Entity* superDie(Entity* self); #endif
C
typedef struct list { char *value; int key; struct list *next; } *List; List initList(int key, const char *value); int containsValue(List l, const char *cuvant); List removeFromBucket(List l, const char *value); List addLast(List l, int key, const char *value); List freeBucket(List l);
C
// Pi (not in math.h) #define M_PI 3.14159265358979323846 #include <math.h> double missingAngle(double h, double a, double o) { if (o == 0) { return round(acos(a/h)*180/M_PI ); } if (h == 0) { return round(atan(o/a)*180/M_PI ); } if (a == 0) { return round(asin(o/h)*180/M_PI ); } }
C
#include <libmtp.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "mtp_helpers.h" char *toIDStr(MTPDeviceIdInfo info) { char buffer[1024]; sprintf(buffer, "%d:%d:%s", info.vendor_id, info.product_id, info.serial); unsigned int idLen = strlen(buffer); char *idStr = malloc((idLen + 1) * idLen); strcpy(idStr, buffer); return idStr; } void toMTPDeviceInfo(MTPDeviceInfo *device_info, LIBMTP_mtpdevice_t *device, uint32_t busLocation, uint8_t devNum, uint16_t vendor_id, uint16_t product_id) { char *serial = LIBMTP_Get_Serialnumber(device); char *friendly = LIBMTP_Get_Friendlyname(device); char *description = LIBMTP_Get_Modelname(device); char *manufacturer = LIBMTP_Get_Manufacturername(device); device_info->id_info.vendor_id = vendor_id; device_info->id_info.product_id = product_id; device_info->id_info.serial = serial; device_info->device_id = toIDStr(device_info->id_info); device_info->friendly_name = friendly; device_info->description = description; device_info->manufacturer = manufacturer; device_info->busLocation = busLocation; device_info->devNum = devNum; } bool getOpenDevice(MTPDeviceInfo *deviceInfo, const char *deviceId, LIBMTP_mtpdevice_t **device, LIBMTP_raw_device_t **raw_devs, uint32_t *busLocation, uint8_t *devNum) { *device = NULL; *raw_devs = NULL; LIBMTP_mtpdevice_t *open_device = NULL; LIBMTP_error_number_t ret; int numdevs; ret = LIBMTP_Detect_Raw_Devices(raw_devs, &numdevs); if (ret == LIBMTP_ERROR_NONE && numdevs > 0) { for (int i = 0; i < numdevs; i++) { LIBMTP_mtpdevice_t *found_device = LIBMTP_Open_Raw_Device_Uncached(raw_devs[i]); char *serial = LIBMTP_Get_Serialnumber(found_device); MTPDeviceIdInfo id_info; id_info.vendor_id = (*raw_devs)[i].device_entry.vendor_id; id_info.product_id = (*raw_devs)[i].device_entry.product_id; id_info.serial = serial; if (strcmp(toIDStr(id_info), deviceId) == 0) { *device = found_device; *busLocation = (*raw_devs)[i].bus_location; *devNum = (*raw_devs)[i].devnum; toMTPDeviceInfo(deviceInfo, found_device, *busLocation, *devNum, id_info.vendor_id, id_info.product_id); return true; } LIBMTP_Release_Device(found_device); } } free(raw_devs); return false; } int getDevicesInfo(MTPDeviceInfo **devices) { LIBMTP_raw_device_t *raw_devs = NULL; LIBMTP_error_number_t ret; int numdevs; ret = LIBMTP_Detect_Raw_Devices(&raw_devs, &numdevs); if (ret == LIBMTP_ERROR_NONE && numdevs > 0) { *devices = malloc(numdevs * sizeof(MTPDeviceInfo)); for (int i = 0; i < numdevs; i++) { LIBMTP_mtpdevice_t *device = LIBMTP_Open_Raw_Device_Uncached(&raw_devs[i]); toMTPDeviceInfo(&((*devices)[i]), device, raw_devs[i].bus_location, raw_devs[i].devnum, raw_devs[i].device_entry.vendor_id, raw_devs[i].device_entry.product_id); LIBMTP_Release_Device(device); } } return numdevs; } bool getDeviceInfo(MTPDeviceInfo *deviceInfo, const char *deviceId) { LIBMTP_mtpdevice_t *device = NULL; LIBMTP_raw_device_t *rawdevices = NULL; uint32_t busLocation; uint8_t devNum; bool ret = false; if (getOpenDevice(deviceInfo, deviceId, &device, &rawdevices, &busLocation, &devNum)) { LIBMTP_Release_Device(device); ret = true; } if (rawdevices != NULL) { free(rawdevices); } return ret; } void initMTP() { LIBMTP_Init(); } bool getStorageDevice(MTPStorageDevice *storageDevice, const char *device_id, const char *path) { LIBMTP_mtpdevice_t *device; LIBMTP_raw_device_t *rawdevices; uint32_t busLocation; uint8_t devNum; MTPDeviceInfo deviceInfo; bool ret = false; if (getOpenDevice(&deviceInfo, device_id, &device, &rawdevices, &busLocation, &devNum)) { LIBMTP_devicestorage_t *storage; storageDevice->storage_id = NULL; storageDevice->capacity = 0; storageDevice->free_space = 0; char *pathCopy = malloc(sizeof(char) * (strlen(path) + 1)); strcpy(pathCopy, path); char *pathPart = strtok(pathCopy, "/"); for (storage = device->storage; storage != 0 && pathPart != NULL; storage = storage->next) { if (strcmp(storage->StorageDescription, pathPart) == 0) { storageDevice->storage_id = malloc(sizeof(char) * 20); sprintf(storageDevice->storage_id, "%#lx", storage->id); storageDevice->free_space = storage->FreeSpaceInBytes; storageDevice->capacity = storage->MaxCapacity; ret = true; } } LIBMTP_Release_Device(device); free(pathCopy); } if (rawdevices != NULL) { free(rawdevices); } return ret; }
C
#pragma once #include "glm.hpp" struct Controller { float resource1; float resource2; int normalunitlevel; int rangeunitlevel; int tankunitlevel; float normalunitcost; float rangeunitcost; float tankunitcost; float normalunitcost2; float rangeunitcost2; float tankunitcost2; float towercost; float wallcost; float generator1cost; float generator2cost; float levelupnormalcost; float leveluprangecost; float leveluptankcost; float levelupnormalcost2; float leveluprangecost2; float leveluptankcost2; float buildrange; glm::vec3 nexusposition; enum ControllerType { DEFAULT, PLAYER, ENEMY, }; ControllerType controllertype; Controller() { resource1 = 200; resource2 = 0; normalunitlevel = 1; rangeunitlevel = 1; tankunitlevel = 1; normalunitcost = normalunitlevel * 40; rangeunitcost = rangeunitlevel * 60; tankunitcost = tankunitlevel * 90; normalunitcost2 = normalunitlevel * 30; rangeunitcost2 = rangeunitlevel * 50; tankunitcost2 = tankunitlevel * 80; towercost = 250; wallcost = 30; generator1cost = 160; generator2cost = 160; levelupnormalcost = normalunitlevel * 30; leveluprangecost = rangeunitlevel * 70; leveluptankcost = tankunitlevel * 100; levelupnormalcost2 = normalunitlevel * 40; leveluprangecost2 = rangeunitlevel * 100; leveluptankcost2 = tankunitlevel * 150; buildrange = 200; nexusposition = glm::vec3(0, 0, 0); controllertype = DEFAULT; } Controller(ControllerType controllertype, glm::vec3 nexusposition) { this->controllertype = controllertype; this->nexusposition = nexusposition; resource1 = 200; resource2 = 0; normalunitlevel = 1; rangeunitlevel = 1; tankunitlevel = 1; normalunitcost = normalunitlevel * 40; rangeunitcost = rangeunitlevel * 60; tankunitcost = tankunitlevel * 90; normalunitcost2 = normalunitlevel * 30; rangeunitcost2 = rangeunitlevel * 50; tankunitcost2 = tankunitlevel * 80; towercost = 250; wallcost = 30; generator1cost = 160; generator2cost = 160; levelupnormalcost = normalunitlevel * 30; leveluprangecost = rangeunitlevel * 70; leveluptankcost = tankunitlevel * 100; levelupnormalcost2 = normalunitlevel * 40; leveluprangecost2 = rangeunitlevel * 100; leveluptankcost2 = tankunitlevel * 150; buildrange = 200; } };
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include<stdio.h> unsigned int parse_memory_size(char *m); struct mem_block { char buffer[1048576]; }; int main (int argc, char *argv[]) { printf("PID: %d\n", (int) getpid()); if (argc < 2) { printf ("please specify the amout of memory (MB) you want to allocate"); return 0; } unsigned int memory_to_alloc_in_mb = atoi(argv[1]); // count the number of blocks in MB unit int numOfBlock = memory_to_alloc_in_mb; struct mem_block* blocks[numOfBlock]; //printf("size of mem_block: %lu\n", sizeof(blocks)); struct timeval start, alloc_end, end; unsigned long alloc_timer, timer; while(1) { char dummy; printf("press enter to start allocation.\n"); dummy = getchar(); gettimeofday(&start, NULL); // allocate the memory for (int i = 0; i < numOfBlock; i++) { struct mem_block* block = malloc(sizeof(struct mem_block)); for (int j = 0; j < 1048576; j++) { block -> buffer[j] = 'a'; } blocks[i] = block; } gettimeofday(&alloc_end, NULL); printf("press enter to free the memory\n"); dummy = getchar(); // free the memory for (int i = 0; i < numOfBlock; i++) { free(blocks[i]); } gettimeofday(&end, NULL); alloc_timer = 1000000 * (alloc_end.tv_sec - start.tv_sec) + alloc_end.tv_usec - start.tv_usec; timer = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec; printf("one alloc-free round end. alloc time %ld us. total time %ld us\n", alloc_timer, timer); while(1) { char exit; printf("exit? 'y', alloc again? 'a'\n"); scanf("%c", &exit); if (exit == 'y' || exit == 'Y') { return 0; } else if (exit == 'a' || exit == 'A') { break; } } } }
C
#include <stdlib.h> #include "ft_stock_str.h" #include <unistd.h> void ft_putchar(char a) { write(1, &a, 1); } void ft_print(char str[]) { int a; a = 0; while (str[a] != '\0') { ft_putchar(str[a]); a++; } } void ft_putnbr(int size) { long int i; i = size; if (i > 9) { ft_putnbr(i / 10); ft_putnbr(i % 10); } else ft_putchar(i + '0'); } void ft_show_tab(struct s_stock_str *par) { int i; i = 0; while (par[i].str != 0) { ft_print(par[i].str); ft_putchar('\n'); ft_putnbr(par[i].size); ft_putchar('\n'); ft_print(par[i].copy); ft_putchar('\n'); i++; } }
C
#include "motor.h" #include "distanceSensor.h" #include "indicators.h" #define WALL_FLLOW_DEBUG false // Full speed PID Values double WALL_FULL_SPEED_Kp = 3.7; double WALL_FULL_SPEED_Kd = 0; #define WALL_FULL_SPEED_Ki 0 // Half Speed PID values #define WALL_HALF_SPEED_Kp 0 #define WALL_HALF_SPEED_Kd 0 #define WALL_HALF_SPEED_Ki 0 #define WALL_POSITION 650 #define FRONT_MIN_DISTANCE 200 unsigned int frontDistance = 0; unsigned int leftDistance = 0; unsigned int rightDistance = 0; int wallError = 0; int wallI = 0; int walLastError = 0; int WallMotorSpeed = 0; void calPidWall (float Kp , float Kd , float Ki , unsigned int position){ wallError = position; wallI = wallI + wallError; WallMotorSpeed = (Kp * wallError) + (Kd * (wallError - walLastError)) + wallI*Ki; walLastError = wallError; } void fullSpeedWallFollow(void){ while(1){ frontDistance = getDistance(FRONT); leftDistance = getDistance(LEFT); rightDistance = getDistance(RIGHT); calPidWall(WALL_FULL_SPEED_Kp,WALL_FULL_SPEED_Kd,WALL_FULL_SPEED_Ki,rightDistance-leftDistance); // calculate pid For left and right motors rightMotorSpeed = WALL_BASE_SPEED_RIGHT + WallMotorSpeed; leftMotorSpeed = WALL_BASE_SPEED_LEFT - WallMotorSpeed; if (rightMotorSpeed > WALL_MOTOR_SPEED_RIGHT ) rightMotorSpeed = WALL_MOTOR_SPEED_RIGHT; // prevent the motor from going beyond max speed if (leftMotorSpeed > WALL_MOTOR_SPEED_LEFT ) leftMotorSpeed = WALL_MOTOR_SPEED_LEFT; // prevent the motor from going beyond max speed if (rightMotorSpeed < 0) rightMotorSpeed = 0; // keep the motor speed positive if (leftMotorSpeed < 0) leftMotorSpeed = 0; // keep the motor speed positive if (rightDistance == 0 && leftDistance == 0) { break; // We have found a junction or dedend } if(2 < frontDistance && frontDistance < FRONT_MIN_DISTANCE ){ //beep(2,100); break; // found a junction } else { if (WALL_FLLOW_DEBUG) { Serial.print(rightDistance - leftDistance); Serial.print("\t"); Serial.print(wallError); Serial.print("\t"); Serial.print(leftMotorSpeed); Serial.print("\t"); Serial.print(rightMotorSpeed); Serial.print("\t"); Serial.println(); } else { forward(); speedControl(leftMotorSpeed,rightMotorSpeed); // change motor speed according PID values } } } speedControl(255,255); backward(); delay(BACKWORD_STOP_DELAY); Stop(); // stop both motors after wall Follow beep(2,250); } void checkWallDedend(void) { freeforward(200); FreeRotateLeft(150); freeforward(200); // now check there have ay wall if(getDistance(LEFT) != 0 || getDistance(RIGHT) != 0){ //we have found 4way junction // allso we have take our turn beep(100,1); } else{ // wehave found dedend //GO back FreeRotateLeft(300); freeforward(200); FreeRotateRight(150); } } void WallFollowing() { normalSpeed(); while(1){ frontDistance = getDistance(FRONT); leftDistance = getDistance(LEFT); rightDistance = getDistance(RIGHT); if (frontDistance < 4 && frontDistance != 0) { Stop(); delay(1000); if(leftDistance < 4){ turnRight(); } else{ turnLeft(); } delay(200); Stop(); } else { if (leftDistance > 10 && leftDistance < 20 ) { turnLeft(); delay(30); forward(); delay(30); } else if (leftDistance < 5 && leftDistance > 0) { turnRight(); delay(30); forward(); delay(30); } else if (leftDistance > 20 || leftDistance == 0) { forward(); delay(50); turnLeft(); delay(30); forward(); delay(30); } else { forward(); } } delay(20); } }
C
/****************************************************************************** Online C Compiler. Code, Compile, Run and Debug C program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include<stdio.h> int main() { int first=1, second=1, k, c, sum=0; scanf("%d",&k); if(0<k && k<41) { for(int i=0; i<k; i++) { sum = sum + first; c = first + second; first = second; second = c; } } printf("%d", sum); return 0; }
C
#ifndef LUA_SCRIPT_H #define LUA_SCRIPT_H /*========================================================= DECLARATIONS =========================================================*/ #include "lua/lua_script_.h" /*========================================================= INCLUDES =========================================================*/ #include "common.h" #include "thirdparty/lua/lua.h" /*========================================================= CONSTANTS =========================================================*/ /*========================================================= TYPES =========================================================*/ /** Lua script context. */ struct lua_script_s { lua_State* state; }; /** Generic callback function for getting a value from a lua script. Used for get_array(). @param lua The Lua script context. @param out__val Pointer to the memory location to place the value. @param size The amount of memory (in bytes) available at the location for the value. @returns TRUE if successful, FALSE otherwise. */ typedef boolean(*lua_script__get_value_func_t)(lua_script_t* lua, void* out__val, int size); /*========================================================= CONSTRUCTORS =========================================================*/ /** Constructs a Lua script context. @param lua The Lua script context. */ void lua_script__construct(lua_script_t* lua); /** Destructs a Lua script context. @param lua The Lua script context. */ void lua_script__destruct(lua_script_t* lua); /*========================================================= FUNCTIONS =========================================================*/ /** Cancels loop iteration. Must be preceeded by either start_loop() or next(). @param lua The Lua script context. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__cancel_loop(lua_script_t* lua); /** Gets an array of values from the top of the stack. @param lua The Lua script context. @param get_value_callback The callback function used to retrieve a value and put it in the output array. @param out__array The array to populate with the values. @param item_size The size of an item in the array. @param num_items The number of items in the array. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_array ( lua_script_t* lua, lua_script__get_value_func_t get_value_callback, void* out__array, int item_size, int num_items ); /** Gets an array of values from the specified variable. @param lua The Lua script context. @param variable The variable to get the array from. @param get_value_callback The callback function used to retrieve a value and put it in the output array. @param out__array The array to populate with the values. @param item_size The size of an item in the array. @param num_items The number of items in the array. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_array_var ( lua_script_t* lua, const char* variable, lua_script__get_value_func_t get_value_callback, void* out__array, int item_size, int num_items ); /** Gets an array of floats from the top of the stack. @param lua The Lua script context. @param out__val Location to put to retrieved value. @param num_items The number of items in the array. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_array_of_float(lua_script_t* lua, float* out__val, int num_items); /** Gets an array of floats from the specified variable. @param lua The Lua script context. @param variable The variable to get the array from. @param out__val Location to put to retrieved value. @param num_items The number of items in the array. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_array_of_float_var(lua_script_t* lua, const char* variable, float* out__val, int num_items); /** Gets the value from the top of the stack as a boolean. @param lua The Lua script context. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_bool(lua_script_t* lua, boolean* out__val); /** Gets the value from the specified variable as a boolean. @param lua The Lua script context. @param variable The name or path of the variable to get. Must be a null-terminated string. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_bool_var(lua_script_t* lua, const char* variable, boolean* out__val); /** Executes a script file. @param lua The Lua script context. @param file_path The file to execute. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__execute_file(lua_script_t* lua, const char* file_path); /** Executes a script from a string. @param lua The Lua script context. @param str The string to execute. Must be a null-termined string. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__execute_string(lua_script_t* lua, const char* str); /** Gets the value from the top of the stack as a float. @param lua The Lua script context. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_float(lua_script_t* lua, float* out__val); /** Gets the value from the specified variable as a float. @param lua The Lua script context. @param variable The name or path of the variable to get. Must be a null-terminated string. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_float_var(lua_script_t* lua, const char* variable, float* out__val); /** Gets the value from the top of the stack as a int. @param lua The Lua script context. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_int(lua_script_t* lua, int* out__val); /** Gets the value from the specified variable as a int. @param lua The Lua script context. @param variable The name or path of the variable to get. Must be a null-terminated string. @param out__val Location to put to retrieved value. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_int_var(lua_script_t* lua, const char* variable, int* out__val); /** */ boolean lua_script__get_key(lua_script_t* lua, char* out__key, int max_key_size); /** Gets the value from the top of the stack as a string. @param lua The Lua script context. @param out__val Location to put to retrieved value. @param max_str_size The size of the output buffer. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_string(lua_script_t* lua, char* out__str, int max_str_size); /** Gets the value from the specified variable as a string. @param lua The Lua script context. @param variable The name or path of the variable to get. Must be a null-terminated string. @param out__val Location to put to retrieved value. @param max_str_size The size of the output buffer. @returns TRUE if successful, FALSE otherwise. */ boolean lua_script__get_string_var(lua_script_t* lua, const char* variable, char* out__str, int max_str_size); /** Pops previous value and pops previous key. If a next key is present in the table, push the next key and then pushes the next value. Must be preceeded by either start_loop() or next(). */ boolean lua_script__next(lua_script_t* lua); /** */ uint32_t lua_script__pop(lua_script_t* lua, uint32_t num); /** */ uint32_t lua_script__pop_all(lua_script_t* lua); /** Pushes the specified variable path onto the stack. Nested variables are supported using the period separator. Examples: variableName tableName tableName.key tableName.nestedTable.key @param lua The lua script context. @param variable The name of the variable to push. This must be a null terminated string. @param variable The length of the variable string. @return The number of elements pushed. */ uint32_t lua_script__push(lua_script_t* lua, const char* variable); /** Setup iteration through table. Pushes nil twice. Expects a table to be on top of stack. Use next() to iterate through values. @param lua The lua script context. */ boolean lua_script__start_loop(lua_script_t* lua); #endif /* LUA_SCRIPT_H */
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> char closing(char c) { switch (c) { case '(': return ')'; case '[': return ']'; case '<': return '>'; case '{': return '}'; } return EOF; } char opening(char c) { switch (c) { case ')': return '('; case ']': return '['; case '>': return '<'; case '}': return '{'; } return EOF; } bool isOpening(char c) { return closing(c) != EOF; } long getCompleteScore(char *orders) { long score = 0; while (*orders != '-') { score *= 5; switch (*orders) { case '(': score += 1; break; case '[': score += 2; break; case '{': score += 3; break; case '<': score += 4; break; } orders--; } return score; } //STOLEN int compare( const void* a, const void* b) { long int_a = * ( (long*) a ); long int_b = * ( (long*) b ); if ( int_a == int_b ) return 0; else if ( int_a < int_b ) return -1; else return 1; } long score(FILE *fp) { char* data = malloc(1000); long nums[1000]; long nums_length = 0; char* orders = data; *orders = '-'; long result = 0; char c; while (c != EOF) { c = getc(fp); if (isOpening(c)) { orders++; *orders = c; } else { char top = *orders; if (c == closing(top)) { orders--; } else { // INCOMPLETE LINE if (c == '\n') { nums_length++; nums[nums_length - 1] = getCompleteScore(orders); } data = malloc(1000); orders = data; *orders = '-'; while (c != '\n' && c != EOF) { c = getc(fp); } } } } qsort(nums, nums_length, sizeof(long), compare ); return nums[(nums_length - 1) / 2]; } int main() { FILE *fp = fopen("input", "r+"); long result = score(fp); printf("%ld\n", result); }
C
#include "audioCl.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ao/ao.h> #include <math.h> //Affiche la liste des musiques au clients void liste_musiques(char *son[],int taille) { int i; printf("\n******** Voici la liste de musiques disponible ******** \n"); for(i=0;i<taille;i++) { printf("%d) %s\n",i+1,son[i]); } } //INUTILE POUR LE MOMENT void play_musique(char recv_data[]){ ao_device *device; ao_sample_format format; int default_driver; /* -- Initialize -- */ ao_initialize(); /* -- Setup for default driver -- */ default_driver = ao_default_driver_id(); memset(&format, 0, sizeof(format)); format.bits = 16; format.channels = 2; format.rate = 44100; format.byte_format = AO_FMT_LITTLE; /* -- Open driver -- */ device = ao_open_live(default_driver, &format, NULL /* no options */); if (device == NULL) { fprintf(stderr, "Error opening device.\n"); return; } ao_play(device, recv_data, sizeof(recv_data)); /* -- Close and shutdown -- */ ao_close(device); ao_shutdown(); }
C
#include <stdio.h> int main(void) { int values[16], row[4], column[4], diagsum[2], i; for(i=0; i<4; i++) { row[i] = 0; column[i] = 0; if (i < 2) diagsum[i] = 0; } printf("Enter the numbers from 1 to 16 in any order: "); for (i = 0; i < 16; i++) scanf("%d", &(values[i])); for (i = 0; i < 16; i++) { if (i % 4 == 0) { printf("\n%-4d", values[i]); } else printf("%-4d", values[i]); if (i < 4) row[0] += values[i]; else if (i < 8 && i >= 4) row[1] += values[i]; else if (i < 12 && i>= 8) row[2] += values[i]; else row[3] += values[i]; if ((i+1)%4 == 1) column[0]+= values[i]; else if ((i+1)%4 == 2) column[1] += values[i]; else if ((i+1)%4 == 3) column[2] += values[i]; else column[3] += values[i]; if (i%5 == 0) diagsum[0] += values[i]; else if (i%3 == 0) diagsum[1] += values[i]; } printf("\n"); printf("Row sums: %d %d %d %d\n", row[0], row[1], row[2], row[3]); printf("Column sums: %d %d %d %d\n", column[0], column[1], column[2], column[3]); printf("Diagonal sums: %d %d\n", diagsum[0], diagsum[1]); return 0; }
C
//************************************************************************************ //Estimated time spent ~ 7 hours //File: fraction.c //Assignment: Homework 4 //Author: Mahesh Gautam //Date: Spring 2016 //Description: This program takes in a input file containing fractions via command line //argument, sorts them, reduces them, calculates their sum, and prints the sum and the //sorted fractions in the same order as they came in i.e (whole, numerator/denominator) //************************************************************************************** #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "fraction.h" //function to initialize fractions bool fraction_init(FILE *fp, fraction *f) { int ch; int wholeNumber, multiplier; //multiplier is Sign multiplier long long numerator, denominator; //stop when end of file reached if ((ch = fgetc(fp)) == EOF) return false; //initialize whole, numerator, and denominator wholeNumber = numerator = denominator = 0; multiplier = 1; // parse wholeNumber if (ch == '-') multiplier = -1; else wholeNumber = ch - '0'; while ( (ch = fgetc(fp)) != ' ' ) { wholeNumber = wholeNumber * 10 + ch - '0'; } // parse numerator ch = fgetc(fp); if (ch == '-') multiplier = -1; else numerator = ch - '0'; while ( (ch = fgetc(fp)) != '/' ) { numerator = numerator * 10 + ch - '0'; } // parse denominator while ( (ch = fgetc(fp)) != '\n' ) { denominator = denominator * 10 + ch - '0'; } // reduce the numerator and denominator to lowest terms long long divisor = fraction_gcd(denominator, numerator); numerator = numerator / divisor; denominator = denominator / divisor; numerator += wholeNumber * denominator; numerator *= multiplier; // set remaining member variables f->numerator = numerator; f->denominator = denominator; return true; //all went well - return true } //find out greatest common divisor using Euclids algorithm long long fraction_gcd(long long a, long long b) { while (b != 0) { long long oldA = a; a = b; b = oldA % b; } return a; } //This function adds the fraction using greaterst common divisor void fraction_add(fraction *f1, const fraction *f2) { f1->numerator = (f1->numerator * f2->denominator) + (f2->numerator * f1->denominator); f1->denominator *= f2->denominator; long long divisor = fraction_gcd(f1->denominator, f1->numerator); f1->numerator /= divisor; f1->denominator /= divisor; } //function to print the fractions in the same order as they came in void fraction_print(const fraction *f) { int wholePrint = f->numerator / f->denominator; int numeratorPrint = f->numerator % f->denominator; //make sure whole and numerator both dont have negative sign at once if (wholePrint < 0 && numeratorPrint < 0) { numeratorPrint = -numeratorPrint; } int denominatorPrint = f->denominator; //take absolute value of denominator so its not negative and print everything printf("%d %d/%d\n", wholePrint, numeratorPrint, abs((int)f->denominator)); } //function to compare the fraction so we can use the values to sort our fractions int fraction_compare(const void *lhs, const void *rhs) { fraction *f1 = (fraction*)lhs; fraction *f2 = (fraction*)rhs; return (f1->numerator * f2-> denominator) - (f2->numerator * f1->denominator); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #define MAXBUFSIZE 4096 int main (int argc, char** argv) { int i; int server_socket; int client_socket; int file_fd; struct stat sb; struct sockaddr_in server_addr; struct sockaddr_in client_addr; socklen_t clilen = sizeof(client_addr); char buf[MAXBUFSIZE]; int buflen; char file[100]; // file to open int nbytes_read; time_t now; // present time char timebuf[100]; char content_length_buf[100]; char content_type[30]; // content_type string char content_type_buf[100]; server_socket = socket(AF_INET, SOCK_STREAM, 0 ); //create a server socket server_addr.sin_family = AF_INET; //IPv4 protocol server_addr.sin_port = htons( (unsigned short) atoi( argv[1] ) ); //port number server_addr.sin_addr.s_addr = htonl (INADDR_ANY); //for any addr to connect to the server bind(server_socket, (struct sockaddr*) & server_addr, sizeof(server_addr) ); //create a listener listen(server_socket, 100); //start to listen while (1) { client_socket = accept(server_socket, (struct sockaddr*) &client_addr, &clilen ); // waiting to accept a client //TCP connection nbytes_read = read(client_socket, buf, MAXBUFSIZE); // read request from client strcpy(file, ""); // empty string for (i = 4; i < MAXBUFSIZE; i++ ) //split the "GET /xxx" string if(buf[i] == ' ') { buf[i] = 0; break; } /* handling the requested file string*/ if ( buf[ strlen(buf) - 5] == '.' || buf[ strlen(buf) - 4] == '.') { strcpy (file, "htdocs/"); strcat(file, &buf[5] ); file_fd = open( file, O_RDONLY ); } else { if (buf[5] != '\0') { strcpy (file, "htdocs/"); strcat(file, &buf[5] ); } if (buf[ strlen(buf) - 1] == '/') strcat(file, "index.html\0"); else strcat(file, "/index.html\0"); file_fd = open( file, O_RDONLY ); } /**************************************/ for (i=0; i < strlen(file); i++) //get the content type if (file[i] == '.') { strcpy(content_type, &file[i+1]); break; } fprintf(stderr, "%s\n", file); //print the opened file if (file_fd > 0) { // opening successes stat( file, &sb ); //get the information of the file /**************** 200 OK header **********************/ write(client_socket, "HTTP/1.1 200 OK\r\n", strlen("HTTP/1.1 200 OK\r\n") ); // get and write the present time now = time( (time_t*) 0 ); (void) strftime( timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime( &now ) ); write(client_socket,"Date: ", strlen("Date: ") ); write(client_socket, timebuf, strlen(timebuf) ); // get and write the present time // get and write the Last-Modified time (void) strftime( timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime( &sb.st_mtime ) ); write(client_socket,"\r\nLast-Modified: ", strlen("\r\nLast-Modified: ") ); write(client_socket, timebuf, strlen(timebuf) ); // get and write the Last-Modified time // write the Content-Type if ( strcmp(content_type,"jpg") == 0 || strcmp(content_type,"png") == 0 || strcmp(content_type,"bmp") == 0 || strcmp(content_type,"gif") == 0 ) buflen = snprintf( content_type_buf, sizeof(content_type_buf), "\r\nContent-Type: image/%s", content_type ); else if (strcmp(content_type,"txt") == 0) buflen = snprintf( content_type_buf, sizeof(content_type_buf), "\r\nContent-Type: text/%s", "plain" ); else buflen = snprintf( content_type_buf, sizeof(content_type_buf), "\r\nContent-Type: text/%s", "html" ); write(client_socket, content_type_buf, buflen ); // write the Content-Type // write the Content-Length buflen = snprintf( content_length_buf, sizeof(content_length_buf), "\r\nContent-Length: %ld", (int64_t) sb.st_size ); write(client_socket, content_length_buf, buflen ); // write the Content-Length write(client_socket, "\r\n\r\n", strlen("\r\n\r\n") ); // end of header /********************************************************/ while ( ( nbytes_read = read( file_fd, buf, MAXBUFSIZE ) ) > 0 ) // read and write the requested data write(client_socket, buf, nbytes_read ); close(file_fd); } else { /**************** 404 NOT FOUND header **********************/ write(client_socket, "HTTP/1.1 404 Not Found\r\n", strlen("HTTP/1.1 404 Not Found\r\n") ); // get and write the present time now = time( (time_t*) 0 ); (void) strftime( timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime( &now ) ); write(client_socket,"Date: ", strlen("Date: ") ); write(client_socket, timebuf, strlen(timebuf) ); // get and write the present time write(client_socket, "\r\n\r\n", strlen("\r\n\r\n") ); // end of header /*************************************************************/ write(client_socket, "404 error : File not found!!\n", strlen("404 error : File not found!!\n") ); // indicate that file not found } close(client_socket); } return 0; }
C
#if defined(_WIN32) #include <windows.h> #else #include <unistd.h> #endif /* sleeps for 4n seconds, where n is the argument to the program */ int main(int argc, char** argv) { int time; if (argc > 1) { time = 4 * atoi(argv[1]); } #if defined(_WIN32) Sleep(time * 1000); #else sleep(time); #endif return 0; }
C
/* $Header: /home/student1/dos_cvrt/RCS/unix2dos.c,v 1.2 1998/12/06 21:34:06 student1 Exp $ * Basil Fawlty $Date: 1998/12/06 21:34:06 $ * * UNIX to DOS text format conversion. * * $Log: unix2dos.c,v $ * Revision 1.2 1998/12/06 21:34:06 student1 * Added error checking. * * Revision 1.1 1998/11/27 02:29:21 student1 * Initial revision */ static const char rcsid[] = "$Id: unix2dos.c,v 1.2 1998/12/06 21:34:06 student1 Exp $"; #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include "dos_cvrt.h" /* * Convert file named by pathname to DOS * text format, on standard output: */ int unix2dos(const char *pathname) { int ch; /* Current input character */ int rc = 0; /* Return code */ FILE *in = 0; /* Input file */ if ( !(in = fopen(pathname,"r")) ) { fprintf(stderr,"%s: opening %s for read.\n", strerror(errno),pathname); return RC_OPENERR; } while ( (ch = fgetc(in)) != EOF ) { if ( ch == '\n' ) if ( put_ch('\r') ) { rc = RC_WRITERR; /* Write failed */ goto xit; } if ( put_ch(ch) ) { rc = RC_WRITERR; /* Write failed */ goto xit; } } /* * Test for a read error: */ if ( ferror(in) ) { fprintf(stderr,"%s: reading %s\n", strerror(errno),pathname); rc = RC_READERR; } xit:fclose(in); return rc; } /* End $Source: /home/student1/dos_cvrt/RCS/unix2dos.c,v $ */
C
#pragma once #include <stdint.h> #include <stddef.h> struct terminal { size_t width; size_t height; size_t row; size_t col; size_t tab_size; uint8_t color; uint16_t* buffer; }; void term_init(struct terminal* term, size_t width, size_t height, void* buffer); void term_putchar_at(struct terminal* term, char c, uint8_t color, size_t x, size_t y); void term_putchar(struct terminal* term, char c); void term_write(struct terminal* term, const char *data, size_t size); void term_write_string(struct terminal* term, const char *str); void term_clear_screen(struct terminal* term);
C
#include <stdio.h> #include <stdbool.h> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; typedef struct TreeNode node; #define BAD_HEIGHT -100 int max( int left, int right ) { if ( left > right ) { return left; } return right; } int getHeightIfBalanced(struct TreeNode* root) { int leftHeight; int rightHeight; if ( root == NULL ) { return -1; } leftHeight = getHeightIfBalanced(root->left); rightHeight = getHeightIfBalanced(root->right); if ( (leftHeight == BAD_HEIGHT) || (rightHeight == BAD_HEIGHT) ) { return BAD_HEIGHT; } if (( leftHeight == rightHeight + 1 ) || ( leftHeight == rightHeight ) || ( leftHeight == rightHeight -1 ) ) { return ( max(leftHeight, rightHeight) + 1); } else { return BAD_HEIGHT; } } bool isBalanced(struct TreeNode* root) { if ( getHeightIfBalanced(root) == BAD_HEIGHT) { return false; } return true; } int main() { }
C
#include<stdio.h> int main(int argc, char const *argv[]) { // char a[][10]={"ss"}; int i; for(i=0;i<argc;i++) { printf("%d:%s\n",i,argv[i] );//argv存储了命令行后跟随的命令,argv[0]固定为路径 } return 0; } /* #include<stdio.h> #include<string.h> int main(int argc, char *argv[]) { // char a[][10]={"ss"}; int i; char *a; for(i=0;i<argc;i++) { printf("%d:%s\n",i,argv[i] );//argv存储了命令行后跟随的命令,argv[0]固定为路径 } //printf("%s\n",argv[1]); //printf("%d\n",strcmp(argv[1],"help")); a=argv[1]; printf("a:%s\n",a ); if ((strcmp(argv[1],"help"))==0) { printf("you need help\n" ); } return 0; } */
C
#include<stdio.h> void main(){ int a,i,b,arr[8]={0,0,0,0,0,0,0,0}; printf("enter the number which is to be converted from decimal to hexadecimal\n\n"); printf("please enter non negative and integer values only\n\n"); scanf("%d",&a); if(a) if(a<0){ printf("sorry.......it works only for non negative decimal values"); exit(0); } if(a==0){ printf("the resultant Hexadecimal number is %d",a); exit(0); } if(a>0){ for(i=0;a!=0;i++){ arr[i]=a%16; a=a/16; } for(i=0;i<7;i++){ if(arr[7-i]!=0){ b=i; break; }} for(i=0;i<(8-b);i++){{ if(arr[7-b-i]<10){ printf("%d",arr[7-b-i]); } else{ printf("%c",(arr[7-b-i]+55)); }}}}}
C
/* * main.c * * Created on: Nov 10, 2013 * Author: Nathan Lane * Class: CSIS-2430 * * Trip Through Germany. */ #include "sqlite3.h" #include <stdio.h> #include <stdlib.h> int main() { int retval; sqlite3_stmt * stmt; sqlite3 * handle; char * val; int col; int cols; retval = sqlite3_open("tripthroughgermany", &handle); if (retval) { printf("Database connection failed to tripthroughgermany.\n"); return 1; } printf("Connected successfully.\n"); retval = sqlite3_prepare_v2(handle, "select a.location_name from, b.location_name to, kilometers, cost from distance, location a, location b where a.location_id = from_location_id and b.location_id = to_location_id", -1, &stmt, 0); if (retval) { printf("Could not query database.\n"); return 2; } cols = sqlite3_column_count(stmt); while(1) { retval = sqlite3_step(stmt); if(retval == SQLITE_ROW) { for(col = 0; col < cols; col++) { val = (char *) sqlite3_column_text(stmt, col); printf("%s = %s\t", sqlite3_column_name(stmt, col), val); } printf("\n"); } else if(retval == SQLITE_DONE) { printf("All rows fetched\n"); break; } else { printf("Some error encountered\n"); return 3; } } return 0; }
C
/* * @Author: 王教鼎 * @Date: 2021/5/20 9:40 下午 * @Description: 第3题 */ #include <stdio.h> int main(void) { const int NUMBER_OF_DAYS_IN_A_YEAR = 365; int age = 27; int days = age * NUMBER_OF_DAYS_IN_A_YEAR; printf("你的年龄:%d岁,\n", age); printf("你的年龄转换成天数:%d天\n", days); return 0; }
C
/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s\n", argv0); } int main(int argc, char *argv[]) { char *login; argv0 = argv[0], argc--, argv++; if (argc) usage(); if ((login = getlogin())) puts(login); else eprintf("no login name\n"); return fshut(stdout, "<stdout>"); }
C
// .* matches ab because .* == .. = ab bool isMatch(const char *s, const char *p) { if(*p =='\0') return *s =='\0'; if(*(p+1) == '*'){ //* 的作用,P能匹配:匹配0个,进入下一阶段子集;匹配1个,进入子集;匹配2个。。。。 //匹配不上, 直接进入下一阶段匹配 while((*p == '.' && *s != '\0') || *s == *p){ if(isMatch(s,p+2)) return true; s++; } return isMatch(s,p+2); // ab ----- c*ab }else{ if((*p == '.' && *s != '\0') || *s == *p) return isMatch(s+1,p+1); else return false; } } /** * b[i + 1][j + 1]: if s[0..i] matches p[0..j] * if p[j] != '*' * b[i + 1][j + 1] = b[i][j] && s[i] == p[j] * if p[j] == '*', denote p[j - 1] with x, * then b[i + 1][j + 1] is true iff any of the following is true * 1) "x*" repeats 0 time and matches empty: b[i + 1][j -1] * 2) "x*" repeats 1 time and matches x: b[i + 1][j] * 3) "x*" repeats >= 2 times and matches "x*x": s[i] == x && b[i][j + 1] * '.' matches any single character */ bool isMatch(const char *s, const char *p) { int i, j; int m = strlen(s); int n = strlen(p); bool b[m + 1][n + 1]; b[0][0] = true; for (i = 0; i < m; i++) { b[i + 1][0] = false; } // p[0..j - 2, j - 1, j] matches empty iff p[j] is '*' and p[0..j - 2] matches empty for (j = 0; j < n; j++) { b[0][j + 1] = j > 0 && '*' == p[j] && b[0][j - 1]; } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (p[j] != '*') { b[i + 1][j + 1] = b[i][j] && ('.' == p[j] || s[i] == p[j]); } else { b[i + 1][j + 1] = b[i + 1][j - 1] && j > 0 || b[i + 1][j] || //前两种情况,‘c*’ 中, 第一种 c*都不匹配,跳过;第二种,只匹配 c, *跳过 b[i][j + 1] && j > 0 && ('.' == p[j - 1] || s[i] == p[j - 1]); //第三种情况, c* 都匹配 } } } return b[m][n]; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 30 void error_handling(char *message); int main(int argc, char *argv[]) { int server_socket, client_socket; FILE *fp; char buf[BUF_SIZE]; int read_count; struct sockaddr_in server_address, client_address; socklen_t client_address_size; if (argc != 2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } fp = fopen("file_server.c", "rb"); server_socket = socket(PF_INET, SOCK_STREAM, 0); memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(atoi(argv[1])); bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)); listen(server_socket, 5); client_address_size = sizeof(client_address); client_socket = accept(server_socket, (struct sockaddr *) &client_address, &client_address_size); while (1) { read_count = fread((void *)buf, 1, BUF_SIZE, fp); if (read_count < BUF_SIZE) { write(client_socket, buf, read_count); break; } write(client_socket, buf, BUF_SIZE); } shutdown(client_socket, SHUT_WR); read(client_socket, buf, BUF_SIZE); printf("Message from client: %s \n", buf); fclose(fp); close(client_socket); close(server_socket); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
#include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #define MYPORT 2220 #define BUF_LEN 1000 #define IP "127.0.0.1" int main(){ int sock, len; struct sockaddr_in serv; socklen_t addlen = sizeof(serv); char buf[BUF_LEN]; sock = socket(PF_INET, SOCK_STREAM, 0); serv.sin_family = AF_INET; serv.sin_port = htons(MYPORT); inet_aton( "127.0.0.1",&serv.sin_addr); if(connect(sock, (struct sockaddr *) &serv, addlen) != 0 ){ printf("connection with the server failed...\n"); exit(0); } while(1){ printf("Enviar mensagem: "); scanf("%s", buf); //fgets(buf,BUF_LEN, stdin); len=send(sock, buf, strlen(buf)+1, 0); if(!strcmp("exit", buf)){ printf("Closed"); break; } } close(sock); return 1; }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include <time.h> #include <unistd.h> int *a; char filename[100]=""; //!stores the current string char stri[]=""; //!stores the encrypted version char encrypted[]=""; //!A function to take and check for correct integral. int* readinput() { a=(int*)malloc(3*sizeof(int)); char inp[500];fgets(inp,500,stdin); char *token = strtok(inp," "); if(!token) { printf("Wrong input"); exit(0); } a[0]=atoi(token); token=strtok(NULL," "); if(!token) { printf("Wrong input"); exit(0); } a[1]=atoi(token); token=strtok(NULL," "); if(!token) { printf("Wrong input"); exit(0); } a[2]=atoi(token); token=strtok(NULL," "); if(!token) { printf("Wrong input"); exit(0); } strcpy(filename,token); token=strtok(NULL," "); if(token) { printf("Wrong input"); exit(0); } return a; } //!A function to read data or text from file int encrypt_read(int n) { FILE* f =fopen("Sample_testcase_1.txt","r"); if(!f) {printf("Cannot open file"); return 0; } else { int x=0; char ch; while((ch=getc(f))!=EOF) { if(ch=='\r') continue; stri[x]=ch; x++; } stri[x]='\0'; while((x%n)!=0) { strcat(stri,"\0"); x++; } fclose(f); printf("%s \n",stri); return x; } } /*!This function encrypts the output following all the rules of the question*/ void encrypt(int x,int n,int aa,int b) { char str[x];strcpy(str,stri); int size=x/n; int count=0; while(count<size) { for(int i=0;i<n;i++) { int k=((aa*i)+b)%n; if(k<0) k=k+n; int q=k+count*n; char c=str[q]; if(c=='\0') encrypted[i+count*n]='\t'; else encrypted[i+count*n]=c; } count++; } encrypted[x]='\0'; printf("Encrypted\n"); //printf("%s\n",encrypted); } //!A function to display the encrypted output for checking void output() { FILE *f=fopen("outputfile.txt","w"); if(!f) printf("error"); else {fprintf(f,"%s",encrypted); } fclose(f); } int main() { double time_spent = 0.0; clock_t begin = clock(); int *b=(int *)malloc(3*sizeof(int)); b=readinput(); //printf("%d %d %d ",b[0],b[1],b[2]); int c=encrypt_read(b[0]); //printf("%d\n",c); encrypt(c,b[0],b[1],b[2]); //printf("%s\n",encrypted); output(); //printf("%d %d %d ",b[0],b[1],b[2]); clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("Time elpased is %f seconds", time_spent); }
C
#include<stdio.h> #include<string.h> void main() { char s[100]; int i,count=0; gets(s); for(i=0;s[i]!='\0';i++) { count++; } printf("%d",count); }
C
#include <stdio.h> /** * main - Prints all single digit numbers of base 10 * * Return: 0 if succes */ int main(void) { printf("0123456789\n"); return (0); }
C
#ifndef _KEYBOARD_H #define _KEYBOARD_H #include "types.h" /*** * * if err == KEY_NO_ERROR , then check nonPrintableAscii variable * otherwise, an error exists. * KEY_ERR1: a general keyboard error was detected as scancode 0x00 or 0xFF * KEY_ERR2: internal failure was detected as scancode 0xFD * KEY_ERR3: "keyboard fails to acknowledge, please resend" was detected as scancode 0xFE * KEY_ERR4: scancode not in error, but unrecognized key pressed on keyboard. This results from unrecognized keyboard models or custom keys. * ***/ typedef enum KEY_ERROR{ KEY_NO_ERROR , KEY_ERR1 , KEY_ERR2 , KEY_ERR3 , KEY_ERR4 , } KEY_ERROR; typedef enum KEY_NON_PRINTABLE_ASCII{ KEY_IS_PRINTABLE_ASCII , KEY_POWER , KEY_VOL_MUTE , KEY_VOL_UP , KEY_VOL_DOWN , KEY_MOUSE_LOCK , KEY_ESC , KEY_F1 , KEY_F2 , KEY_F3 , KEY_F4 , KEY_F5 , KEY_F6 , KEY_F7 , KEY_F8 , KEY_F9 , KEY_F10 , KEY_F11 , KEY_F12 , KEY_INSERT , KEY_DELETE , KEY_NUMLOCK , KEY_SCROLLLOCK , KEY_PRTSC , KEY_PAUSE , KEY_CAPS , KEY_ENTER , KEY_SHIFT_L , KEY_SHIFT_R , KEY_FN , KEY_CTRL_L , KEY_WIN , KEY_ALT_L , KEY_ALT_R , KEY_MENU , KEY_CTRL_R , KEY_PGUP , KEY_PGDN , KEY_UP , KEY_LEFT , KEY_RIGHT , KEY_DOWN , KEY_SHIFT , KEY_MOUSE_LEFT , KEY_MOUSE_RIGHT } KEY_NON_PRINTABLE_ASCII; typedef enum KEY_EVENT{ KEY_EVENT_UP , KEY_EVENT_DOWN } KEY_EVENT; /*** * * Key pressed will be stored in the alphaNumeric variable unless either of 2 cases are valid * 1) there was an error associated with this kepress. In this case, the KEY_ERR will be set to a non KEY_NO_ERROR value. * 2) the key pressed was a non-alpha numeric key, ie shift was pressed. In this case the KEY_NON_ALPHANUMERIC variable will be set * to a non KEY_IS_ALPHANUMERIC value. Additionally in this case, disregard the alphaNumeric variable and use KEY_NON_ALPHANUMERIC value. * ***/ typedef struct KEY{ uint8 printableAscii; KEY_NON_PRINTABLE_ASCII nonPrintableAscii; KEY_ERROR err; KEY_EVENT event; } KEY; // *************************************************** // FUNCTIONS // *************************************************** void decodeKey( KEY * key , uint8 scancode ); #endif
C
#ifndef NUC_LOCAL_H #define NUC_LOCAL_H // C Standard Library #include <string.h> // Nucleus Headers #include "../../common.h" #include "../emit.h" #include "../global.h" #include "../lexer/token.h" #include "../parser/declaration/variable.h" #include "../parser/expression.h" #include "../parser/parser.h" #include "type.h" /**************************** * LOCAL VARIABLE METHODS * ****************************/ /** * Adds a local variable into the current fuser scope. * @param name Token name of local. * @param immutable Whether the local is immutable */ static void fuser_addLocal(Token name, bool immutable) { // check if exceeded local defintions if (current->localCount == UINT16_COUNT) { PARSER_ERROR_AT("Too many local variables within scope."); return; } // and create a new local with the desired depth and name nuc_Local* local = &current->locals[current->localCount++]; local->name = name; local->depth = -1; local->immutable = immutable; } /** * Adds a closure upvalue to the current compiler. * @param fuser Fuser to compare upvalue indices from. * @param index Index of upvalue. * @param isLocal Whether upvalue is a local variable. * @param immutable If an upvalue is immutable. */ static int fuser_addUpvalue(nuc_Fuser* fuser, uint16_t index, bool isLocal, bool immutable) { int uvCount = fuser->reaction->uvCount; // grab the current upvalue count // check for duplication before proceeding to creation for (int i = 0; i < uvCount; i++) { nuc_Upvalue* upvalue = &fuser->upvalues[i]; if (upvalue->index == index && upvalue->isLocal == isLocal) return i; } // make sure we haven't exceeded the upvalue limit if (uvCount == UINT16_COUNT) { PARSER_ERROR_AT("Too many closure variables within reaction."); return 0; } // and add as could not find it fuser->upvalues[uvCount].isLocal = isLocal; fuser->upvalues[uvCount].index = index; fuser->upvalues[uvCount].immutable = immutable; return fuser->reaction->uvCount++; } /** * Compares two identifier tokens to see if they are equal. * @param a Identifier A. * @param b Identifier B. */ static bool fuser_areIdentifiersEqual(Token* a, Token* b) { if (a->length != b->length) return false; return memcmp(a->start, b->start, a->length) == 0; } /** * Resolves a local reference by name. * @param fuser Compiler to resolve a local of. * @param name Name of local variable. */ static int fuser_resolveLocal(nuc_Fuser* fuser, Token* name) { for (int i = fuser->localCount - 1; i >= 0; i--) { nuc_Local* local = &fuser->locals[i]; if (fuser_areIdentifiersEqual(name, &local->name)) { if (local->depth == -1) PARSER_ERROR_AT("Cannot read local variable in its own initialiser."); return i; } } return -1; } /** * Find the origin of an upvalue and check's if it is immutable. * @param fuser Compiler to derive upvalue from. * @param name Name of upvalue to check immutability of. */ static bool fuser_findUpvalueImmutability(nuc_Fuser* fuser, Token* name) { if (fuser->enclosing == NULL) return NUC_MUTABLE; // here doesn't matter, as will FAIL later anyway int local = fuser_resolveLocal(fuser->enclosing, name); if (local != -1) return fuser->enclosing->locals[local].immutable; return fuser_findUpvalueImmutability(fuser->enclosing, name); // continue looking recursively } /** * Resolves a closure upvalue by name. * @param fuser Compiler to resolve upvalue from. * @param name Name of upvalue to resolve. */ static int fuser_resolveUpvalue(nuc_Fuser* fuser, Token* name) { if (fuser->enclosing == NULL) return -1; int local = fuser_resolveLocal(fuser->enclosing, name); if (local != -1) { fuser->enclosing->locals[local].isCaptured = true; return fuser_addUpvalue(fuser, (uint16_t)local, true, fuser->enclosing->locals[local].immutable); } // recursion to help resolve upvalues int upvalue = fuser_resolveUpvalue(fuser->enclosing, name); if (upvalue != -1) return fuser_addUpvalue(fuser, (uint16_t)upvalue, false, fuser_findUpvalueImmutability(fuser->enclosing, name)); // otherwise bad match return -1; } #endif
C
#include <stdio.h> #include <math.h> int main() { float floatNum; printf("Please input a float number:"); scanf("%f", &floatNum); printf("floatNum=[%0.16f]\n", floatNum); if(fabs(floatNum - 0.0) < 1e-6) { printf("floatNum is zero\n"); } else if(floatNum > 1e-6) { printf("floatNum bigger than zero\n"); } else if(floatNum < -1e-6) { printf("floatNum litter than zero\n"); } return 0; }
C
/* ** por compatibilidad se omiten tildes ** ================================================================================ TRABAJO PRACTICO 3 - System Programming - ORGANIZACION DE COMPUTADOR II - FCEN ================================================================================ definicion de funciones del scheduler */ #include "sched.h" #include "defines.h" #include "screen.h" unsigned char proximaViva(TAREA_INFO* lista, unsigned int cantidad, unsigned int* actual, unsigned int* tssIdx); void inicializarListaTarea(TAREA_INFO* lista, unsigned int cantidad, unsigned int baseTssIdx); unsigned int actual_health; unsigned int actual_a; unsigned int actual_b; unsigned int actual_tipo; unsigned int tssActual; TAREA_INFO tareas_health[15]; TAREA_INFO tareas_a[5]; TAREA_INFO tareas_b[5]; void inicializar_scheduler() { inicializarListaTarea(tareas_health, 15, TAREA_HEALT_BASE); inicializarListaTarea(tareas_a, 5, TAREA_A_BASE); inicializarListaTarea(tareas_b, 5, TAREA_B_BASE); actual_tipo = 0; actual_health = 0; actual_a = 0; actual_b = 0; tssActual = 0; } unsigned short proximaLibre(unsigned int jugador) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); int size = jugador == 2 ? 15 : 5; unsigned short i = 0; for(i = 0; i < size; i++) { if(t[i].viva == 0) { return i; } } //suponemos que no deberia llegar aca return POS_INVALIDA; } unsigned int lanzarTarea(unsigned int jugador) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); unsigned short i = proximaLibre(jugador); if(i == POS_INVALIDA) return i; t[i].viva = 1; return t[i].tssIdx; } void matarTarea(unsigned int jugador, unsigned int tssIdx, unsigned short* pagina_x, unsigned short* pagina_y) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); int size = jugador == 2 ? 15 : 5; unsigned short i = 0; for(i = 0; i < size; i++) { if(t[i].tssIdx == tssIdx) { t[i].viva = 0; *pagina_x = t[i].pagina_x; *pagina_y = t[i].pagina_y; t[i].pagina_x = POS_INVALIDA; t[i].pagina_y = POS_INVALIDA; } } } void obtenerPosPaginaAnterior(unsigned int tssIdx, unsigned short* x, unsigned short* y) { unsigned int jugador = 0; //recorro los 3 vectores y para buscar el tssIdx que coinciden for(jugador = 0; jugador < 3; jugador++) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); int size = jugador == 2 ? 15 : 5; unsigned short i = 0; for(i = 0; i < size; i++) { if(t[i].tssIdx == tssIdx) { *x = t[i].pagina_x; *y = t[i].pagina_y; return; } } } *x = POS_INVALIDA; *y = POS_INVALIDA; } unsigned char getJugadoresPagina(unsigned short x, unsigned short y) { unsigned char res = POS_INVALIDA; unsigned int jugador = 0; //recorro los 3 vectores y para buscar el tssIdx que coinciden for(jugador = 0; jugador < 3; jugador++) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); int size = jugador == 2 ? 15 : 5; unsigned short i = 0; for(i = 0; i < size; i++) { if(t[i].pagina_x == x && t[i].pagina_y == y) { if(res == POS_INVALIDA || res == jugador) res = jugador; else { res = 3; return res; } } } } return res; } void tareaMapeaPagina(unsigned int tssIdx, unsigned short x, unsigned short y) { unsigned int jugador = 0; //recorro los 3 vectores y para buscar el tssIdx que coinciden for(jugador = 0; jugador < 3; jugador++) { TAREA_INFO* t = jugador == 0 ? tareas_a : (jugador == 1 ? tareas_b : tareas_health); int size = jugador == 2 ? 15 : 5; unsigned short i = 0; for(i = 0; i < size; i++) { if(t[i].tssIdx == tssIdx) { t[i].pagina_x = x; t[i].pagina_y = y; return; } } } } void saltasteAIdle() { tssActual = 0; } void reloj() { //posicon y valor char r0[] = "|"; char r1[] = "/"; char r2[] = "-"; char r3[] = "\\"; char* relojstr[] = {r0, r1,r2, r3}; unsigned int i; unsigned int x; unsigned int y; for(i = 0; i<15; i++) { x = 3 + (i * 2); y = 48; if(tareas_health[i].viva == 0) { print("*",x, y, C_FG_WHITE); } else { print(relojstr[tareas_health[i].tick], x, y, C_FG_WHITE); } } print("<A", 13, 46, C_FG_WHITE); for(i = 0; i<5; i++) { x = 3 + (i * 2); y = 46; if(tareas_a[i].viva == 0) { print("*", x, y, C_FG_WHITE); } else { print(relojstr[tareas_a[i].tick], x, y, C_FG_WHITE); } } print("B>", 20, 46, C_FG_WHITE); for(i = 0; i<5; i++) { x = 23 + (i * 2); y = 46; if(tareas_b[i].viva == 0) { print("*", x, y, C_FG_WHITE); } else { print(relojstr[tareas_b[i].tick], x, y, C_FG_WHITE); } } } unsigned short sched_proximo_indice() { unsigned int i = 0; unsigned int proxima = 0; unsigned char encontro = 0; for(i = 0; i<3 && encontro == 0; i++) { //print_int(i, 10, 10, C_FG_WHITE); actual_tipo = (actual_tipo + 1) % 3; if(actual_tipo == 0) { encontro = proximaViva(tareas_health, 15, &actual_health, &proxima); } else if(actual_tipo == 1) { encontro = proximaViva(tareas_a, 5, &actual_a, &proxima); } else { encontro = proximaViva(tareas_b, 5, &actual_b, &proxima); } } reloj(); if(encontro == 1) { unsigned int nuevoIndice = proxima + INDICE_PRIMER_TSS_EN_GDT; #ifdef DEBUG print_int(nuevoIndice, 30, 0, C_FG_WHITE); #endif if(tssActual == nuevoIndice) { return 0; } else { tssActual = nuevoIndice; return tssActual; } } else { return 0; //TAREA_IDLE + INDICE_PRIMER_TSS_EN_GDT; } } unsigned char proximaViva(TAREA_INFO* lista, unsigned int cantidad, unsigned int* actual, unsigned int* tssIdx) { unsigned int i = 0; for(i = 1; i <= cantidad; i++) { unsigned int j = (*actual + i) % cantidad; if(lista[j].viva) { *actual = j; *tssIdx = lista[j].tssIdx; lista[j].tick = (lista[j].tick+1) % 4; return 1; } } *actual = 0; return 0; } void inicializarListaTarea(TAREA_INFO* lista, unsigned int cantidad, unsigned int baseTssIdx) { unsigned int i = 0; for(i = 0; i < cantidad; i++) { lista[i].viva = 0; lista[i].estado = 0; lista[i].tssIdx = i + baseTssIdx; lista[i].pagina_x = POS_INVALIDA; lista[i].pagina_y = POS_INVALIDA; } }
C
#include<stdio.h> main() { int l,s,i,a,b; while(scanf("%d%d",&l,&s)) { if(l==0&&s==0) break; while(s--) { scanf("%d%d",&a,&b); l-=-a+b+1; } printf("%d\n",l+1); } }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "checkSum.h" #include <assert.h> #include "../include/trie.h" void acknowledge(); static void addBrand(Trie); int main(int argc, char **argv) { acknowledge(); Trie t = newTrie(); addBrand(t); // ============================================ // validate card number from file if (argc > 1) { validateFromFile(argv[1], t); return 0; } // ============================================ // validate number from stdin char *cardNumber = calloc(1000, sizeof(char)); assert(cardNumber != NULL); while(true) { printf("please enter your card number(Press Q to exit): "); fgets(cardNumber, 1000, stdin); if (strcmp(cardNumber,"Q\n")==0 || strcmp(cardNumber, "q\n")==0){ break; } char *brand = getBrand(t, cardNumber); printf("Your card brand is \"%s\"\n", brand); int res = validateNumber(cardNumber); if (res == 1) { printf("your card number is valid!\n"); } else if (res == 2) { printf("The card number your entered contains invalid digits\n"); } else { printf("The card number your entered is invalid!\n"); } free(brand); } free(cardNumber); freeTrie(t); return 0; } void acknowledge() { printf("Welcome to this simple credit card validator(Version 1.0)!\n"); printf("========================made by Alex======================\n"); printf("Just letting you know:\n1.the method used to valid your credit card number"); printf(" is a purely mathematical-based.\n2.this app WILL NOT send your card number"); printf(" to ANYONE and store ANY data inside your computer\n\n"); printf("Now let's get started!\n"); } static void addBrand(Trie t) { insertBrand(t, "34", "American Express"); insertBrand(t, "37", "American Express"); insertBrand(t, "31", "China T-Union"); insertBrand(t, "62", "China Union Pay"); // diners Club 300-305 int i; for (i = 300; i <= 305; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "Diners Club International"); free(num); } insertBrand(t, "3095", "Diners Club International"); insertBrand(t, "38", "Diners Club International"); insertBrand(t, "39", "Diners Club International"); insertBrand(t, "6011", "Discover Card"); insertBrand(t, "64", "Discover Card"); insertBrand(t, "65", "Discover Card"); insertBrand(t, "60", "RuPay"); insertBrand(t, "6521", "RuPay"); insertBrand(t, "636", "InterPayment"); // insert JCB 3528-3589 for(i = 3258; i<=3589; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "JCB"); free(num); } insertBrand(t,"50", "Maestro"); insertBrand(t,"56", "Maestro"); insertBrand(t,"57", "Maestro"); insertBrand(t,"58", "Maestro"); insertBrand(t,"639", "Maestro"); insertBrand(t,"67", "Maestro"); insertBrand(t, "5019", "Dankort"); insertBrand(t, "2200", "MIR"); insertBrand(t, "2201", "MIR"); insertBrand(t, "2202", "MIR"); insertBrand(t, "2203", "MIR"); insertBrand(t, "2204", "MIR"); for(i = 222100; i<=272099; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "MasterCard"); free(num); } for(i = 51; i<=55; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "MasterCard"); free(num); } for(i = 979200; i<=979289; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "Troy"); free(num); } insertBrand(t, "4", "Visa"); insertBrand(t, "1", "UATP"); for(i = 506099; i <= 506198; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "Verve"); free(num); } for(i = 650002; i<=650027; i++) { char *num = calloc(10, sizeof(char)); sprintf(num, "%d", i); insertBrand(t, num, "Verve"); free(num); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "fk_circular_buffer.h" void free_buffer(circularBuffer_t *p_buffer) { free(p_buffer->p_data_location); p_buffer->p_data_location = NULL; } int init_buffer(circularBuffer_t *p_buffer, size_t buffer_size, size_t data_size) { void *storage; free_buffer(p_buffer); storage = malloc(buffer_size); return circularBuffer_init(p_buffer, storage, buffer_size, data_size); } int main(void) { char *line = NULL; size_t size; int ret; size_t data_size = 0; size_t buffer_size = 0; size_t peek_size; size_t pushNSize; size_t pop_fifo_size; size_t remove_size; size_t pop_lifo_size; circularBuffer_t buf; buf.p_data_location = NULL; void *pushData = NULL; void *peekData = NULL; void *pushNData = NULL; while(getline(&line, &size, stdin) != -1) { if (line[0] == 'i') { //init if (buf.p_data_location != NULL) continue; ret = sscanf(line, "i %zu %zu", &buffer_size, &data_size); if (ret == 2) { if (data_size > 4096 || buffer_size > 4096) continue; if (data_size == 0 || buffer_size == 0) continue; ret = init_buffer(&buf, buffer_size, data_size); free(pushData); pushData = malloc(data_size); if (ret != CIRC_BUF_NO_ERROR) { break; } } } if (!buf.p_data_location) continue; if (line[0] == 'L') { //flush circularBuffer_flush(&buf); } else if (line[0] == 'u') { //push ret = circularBuffer_push(&buf, pushData, memcpy); } else if (line[0] == 'E') { // pEek ret = sscanf(line, "E %zu", &peek_size); if (ret == 1) { if (peek_size > 1 << 16) continue; free(peekData); peekData = malloc(peek_size * data_size); ret = circularBuffer_peek(&buf, peekData, peek_size, memcpy); } } else if (line[0] == 'N') { // push N ret = sscanf(line, "N %zu", &pushNSize); if (ret == 1) { if (pushNSize > 1 << 16) continue; free(pushNData); pushNData = malloc(data_size * pushNSize); circularBuffer_push_n(&buf, pushNData, pushNSize, memcpy); } } else if (line[0] == 'o') { //pop fifo free(peekData); peekData = malloc(data_size); ret = circularBuffer_popFIFO(&buf, peekData, memcpy); } else if (line[0] == 'f') { // pop fifo N ret = sscanf(line, "f %zu", &pop_fifo_size); if (ret == 1) { if (pop_fifo_size > 1 << 16) continue; free(peekData); peekData = malloc(data_size * pop_fifo_size); ret = circularBuffer_popFIFO_n(&buf, peekData, pop_fifo_size, memcpy); } } else if (line[0] == 'r') { // remove n ret = sscanf(line, "r %zu", &remove_size); if (ret == 1) { circularBuffer_remove_records(&buf, remove_size); } } else if (line[0] == 'l') { // pop lifo free(peekData); peekData = malloc(data_size); ret = circularBuffer_popLIFO(&buf, peekData, memcpy); } else if (line[0] == 'I') { // pop lifo N ret = sscanf(line, "I %zu", &pop_lifo_size); if (ret == 1) { if (pop_lifo_size > 1 << 16) continue; free(peekData); peekData = malloc(data_size * pop_lifo_size); ret = circularBuffer_popLIFO_n(&buf, peekData, pop_lifo_size, memcpy); } } } free(pushData); free(peekData); free(pushNData); free_buffer(&buf); free(line); return 0; }
C
/* ============================================================================ Name : S-2-2.c Author : Gonzalez Ricardo 1-F Ejercicio 2-2: Realizar un programa que permita el ingreso de 10 nmeros enteros. Determinar el promedio de los positivos, la cantidad de ceros y del menor de los negativos la suma de los antecesores. ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include int main(void) { setbuf(stdout, NULL); puts(""); /* prints setbuf(stdout, NULL); */ return EXIT_SUCCESS; }
C
#include "adc.h" void Adc_Init(void) { ADC_InitTypeDef ADC_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC|RCC_APB2Periph_ADC1|RCC_APB2Periph_ADC2, ENABLE ); //ʹADC1ͨʱ RCC_ADCCLKConfig(RCC_PCLK2_Div6); //ADCƵ6 72M/6=12,ADCʱ䲻ܳ14M //PA1 Ϊģͨ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; //ģ GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1; GPIO_Init(GPIOB, &GPIO_InitStructure); ADC_DeInit(ADC1); //λADC1, ADC1 ȫĴΪȱʡֵ ADC_DeInit(ADC2); //λADC1, ADC2 ȫĴΪȱʡֵ ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; //ADCģʽ:ADC1ADC2ڶģʽ ADC_InitStructure.ADC_ScanConvMode = DISABLE; //ģתڵͨģʽ ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; //ģתڵתģʽ ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; //תⲿ ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; //ADCҶ ADC_InitStructure.ADC_NbrOfChannel = 1; //˳йתADCͨĿ ADC_Init(ADC1, &ADC_InitStructure); //ADC_InitStructָIJʼADCxļĴ ADC_Init(ADC2, &ADC_InitStructure); //ADC_InitStructָIJʼADCxļĴ ADC_Cmd(ADC1, ENABLE); //ʹָADC1 ADC_Cmd(ADC2, ENABLE); //ʹָADC1 ADC_ResetCalibration(ADC1); //ʹܸλУ׼ while(ADC_GetResetCalibrationStatus(ADC1)); //ȴλУ׼ ADC_StartCalibration(ADC1); //ADУ׼ while(ADC_GetCalibrationStatus(ADC1)); //ȴУ׼ ADC_ResetCalibration(ADC2); //ʹܸλУ׼ while(ADC_GetResetCalibrationStatus(ADC2)); //ȴλУ׼ ADC_StartCalibration(ADC2); //ADУ׼ while(ADC_GetCalibrationStatus(ADC2)); //ȴУ׼ } //ADCֵ //ch:ֵͨ 0~3 u16 Get_Adc(u8 ch) { ADC_RegularChannelConfig(ADC1,ch,1,ADC_SampleTime_239Cycles5); ADC_SoftwareStartConvCmd(ADC1, ENABLE); //ʹָADC1ת while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC ));//ȴת return ADC_GetConversionValue(ADC1); //һADC1ת } u16 Get_Adc2(u8 ch) { ADC_RegularChannelConfig(ADC2,ch,1,ADC_SampleTime_239Cycles5); ADC_SoftwareStartConvCmd(ADC2, ENABLE); //ʹָADC1ת while(!ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC ));//ȴת return ADC_GetConversionValue(ADC2); //һADC1ת } //ȡƽֵ u16 Get_Adc_Average(u8 ch,u8 times) { u32 temp_val=0; u8 t; for(t=0;t<times;t++) { temp_val+=Get_Adc2(ch); } return temp_val/times; }
C
#include "../include/race.h" #include "race_int.h" race_t *race_job_new(void) { return (calloc(1, sizeof(race_t))); } void race_job_free(race_t *r) { race_conn_param_deinit(&r->conn_param); free(r); } int race_set_option(race_t *r, race_option_t opt, size_t arg) { unsigned p_uint = (unsigned)arg; switch (opt) { case RACE_OPTION_PARALELLS: r->race_param.mode = RACE_PARALELLS; break; case RACE_OPTION_PIPELINE: r->race_param.mode = RACE_PIPELINE; break; case RACE_OPTION_DELAY_USEC: r->race_param.delay = (struct timeval){ .tv_sec = p_uint / 1000000, .tv_usec = p_uint % 1000000 }; break; case RACE_OPTION_LAST_CHUNK_SIZE: r->race_param.last_chunk_size = p_uint; break; default: return (-1); } return (0); } int race_run(race_t *r) { int rc = 0; struct event_base *base; race_module_t module; if (!(base = event_base_new())) { return (-1); } switch (r->race_param.mode) { case RACE_PARALELLS: race_module_paraleels_init(&module); break; case RACE_PIPELINE: race_module_pipeline_init(&module); break; default: return (-1); } if (race_module_init(&module, r, base) < 0) { rc = -1; goto done; } rc = event_base_dispatch(base); race_module_deinit(&module); done: while (!TAILQ_EMPTY(&r->data)) { race_storage_item_t *item = TAILQ_FIRST(&r->data); TAILQ_REMOVE(&r->data, item, node); race_storage_item_free(item); } event_base_free(base); return (rc); }
C
#include "command_other.h" int launch(char **args) { char path[100]; bzero(path, 100); strcat(path, "/bin/"); //将两个char类型连接 ///bin: /usr/bin: 可执行二进制文件的目录,如常用的命令ls、tar、mv、cat等。 strcat(path, args[0]); int rc = fork(); if (rc > 0) { //父进程 waitpid(-1, 0, 0); } else if (rc == 0) { //子进程 int result = execve(path, args, 0); if (result == -1) { printf("can not find %s\n", inputs[0]); } exit(0); } else { //创建失败 fprintf(stderr, "🙀🙀🙀❌error:fork failed!\n"); //把格式字符串输出到指定文件设备中 //在这里是输出到标准错误输出设备,默认输出到屏幕 return 0; } return 1; }
C
#include <stdio.h> /********************************************* Nome: Samuel Toyoshi Ishida RA: 160250 Turma: T Laboratorio Fruit Crush Saga - Part II **********************************************/ #define MAX 52 /*remove as frutas e ajusta o tabuleiro*/ void remFrutas(char tab[][MAX], int x, int y) { int i; for(i=x; i>=1; i--) tab[i][y] = tab[i-1][y]; } int colocaX(char tab[][MAX], char aux, int m, int n, int x, int y) { int i, score; tab[x][y] = 'X'; score = 1;/*pelo menos a posio que ele jogou muda*/ /*cada for verifica as posies adjacentes (um pra cada direo) sendo que ele para o loop quando a posio for != de aux e em cada iterao ele troca o valor na matriz por 'X' e incrementa score*/ for(i=y+1; i<n; i++){ if(tab[x][i] != aux) break; tab[x][i] = 'X'; score++; } for(i=y-1; i>=0; i--){ if(tab[x][i] != aux) break; tab[x][i] = 'X'; score++; } for(i=x+1; i<=m; i++){ if(tab[i][y] != aux) break; tab[i][y] = 'X'; score++; } for(i=x-1; i>=0; i--){ if(tab[i][y] != aux) break; tab[i][y] = 'X'; score++; } return score; } /*funo principal*/ int main() { int m, n, i, j, x, y, score, sumScore=0, num; char tab[MAX][MAX], aux; /******************************************* m = numero de linhas; n = numero de colunas; i, j = contadoras; x, y = coordenadas da jogada; tab = matriz do tabuleiro; aux = auxiliar; ********************************************/ scanf("%d %d %d",&m,&n,&num);/*le a entrada*/ /*coloca '.' na primeira linha da matriz para facilitar na substituio, pois s necessrio copiar o valor da linha de cima na hora de colocar os pontos no tabuleiro*/ for(i=0; i<n; i++) tab[0][i] = '.'; getc(stdin);/*tira o '\n' do buffer*/ for(i=1;i<=m;i++) fgets(tab[i],n+2,stdin);/*n+2 para o '\n' e para o '\0'*/ /*le todas as jogadas e as executa*/ while(num--) { scanf("%d %d", &x, &y);/*le as jogadas*/ y--; aux = tab[x][y];/*salva o valor*/ if(aux == '.') continue;/*se for um ponto no uma jogada vlida*/ /*colocaX coloca os X nas frutas adjacentes e retorna a pontuao*/ score = colocaX(tab,aux,m,n,x,y); for(i=1; i<=m; i++) for(j=0; j<n; j++) if(tab[i][j] == 'X') remFrutas(tab,i,j);/*remove os X e coloca os pontos*/ score *= score; sumScore += score;/*soma a pontuao*/ } printf("Score: %d\n",sumScore);/*imprime a pontuao final*/ for(i=1;i<=m;i++){ for(j=0;j<n;j++){ printf("%c",tab[i][j]);/*imprime a saida*/ } printf("\n");/*pula a linha*/ } /*fim do programa*/ return 0; }
C
#include <stdio.h> #include <stdlib.h> /* ó 迭 Ҵ 10¥ Ҵ Ŀ ڸ 0 Էҋ Է Է ޴ٰ 迭 ߰ 3 迭 ø 0 Է Է ڵ ϴ ڵ带 ۼ */ int main(void) { int* arr; int size = 10; int idx = 0, i, total = 0; //Ҵ arr = (int*)malloc(sizeof(int) * size); while (1) { // ڸ Ҵ if (idx == size) { size += 3; arr = (int*)realloc(arr, sizeof(int) * size); } printf(" Է : "); scanf_s("%d", &arr[idx]); idx++; if (arr[idx-1] == 0) break; } // for (i = 0; i < idx; i++) { total += arr[i]; } printf(" : %d\n", total); // free(arr); return 0; }
C
#include <stdio.h> #include <stdbool.h> void sort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } int max(int num1, int num2) { return (num1 > num2 ) ? num1 : num2; } bool isFeasible(int mid, int arr[], int m, int n) { int pos = arr[0]; int elements = 1; for (int i = 1; i < m; i++) { if (arr[i] - pos >= mid) { pos = arr[i]; elements++; if (elements == n) return true; } } return 0; } int largestMinDist(int arr[], int m, int n) { sort(arr, m); int res = -1; int left = 1, right = arr[m - 1]; while (left < right) { int mid = (left + right) / 2; if (isFeasible(mid, arr, m, n)) { res = max(res, mid); left = mid + 1; } else right = mid; } return res; } int main() { int n,m; scanf("%d %d",&n,&m); int arr[m]; for(int i=0;i<m;i++){ scanf("%d", &arr[i]); } printf("%d", largestMinDist(arr, m, n)); return 0; }
C
#include<stdio.h> #include<string.h> #define start m##a##i##n int start() { char str[30]; strcpy(str,"i am a coder"); printf("the contained string is %s",str); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; struct QueueNode { void * ptr; struct QueueNode *next; }; struct Queue{ struct QueueNode *front; struct QueueNode *tail; }; void push(struct Queue *queue, void *new_val) { struct QueueNode *new_node = (struct QueueNode *)malloc(sizeof(struct QueueNode)); new_node->ptr = new_val; new_node->next = NULL; if (queue->tail != NULL) { queue->tail->next = new_node; } queue->tail = new_node; if (queue->front == NULL) { queue->front = new_node; } } void * pop(struct Queue * queue) { void *ans; if (queue->front == NULL) { ans = NULL; } else { ans = queue->front->ptr; struct QueueNode *tmp = queue->front; queue->front = queue->front->next; if (queue->front == NULL) { queue->tail = NULL; } free(tmp); } return ans; } /** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *columnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) { if (root == NULL) return NULL; #define MAX 4096 int **ans = (int **)calloc(MAX, sizeof(int *)); *columnSizes = (int *)calloc(MAX, sizeof(int)); struct Queue q; q.front = q.tail = NULL; push(&q, root); ans[0] = (int *)calloc(1, sizeof(int)); /* for the root node */ *returnSize = 0; int next = 0; /* number of nodes in next level, except NULL nodes */ int cur = 1; /* number of nodes in current level, except NULL nodes */ int count = 0; /* count of nodes already traversed in current level */ while (q.front != NULL) { struct TreeNode *p = (struct TreeNode *)pop(&q); if (p) { /* push children into queue if parent is not NULL */ ans[*returnSize][count] = p->val; count++; if (p->left) { push(&q, p->left); next++; } if (p->right) { push(&q, p->right); next++; } } if (count == cur) { (*columnSizes)[*returnSize] = cur; (*returnSize)++; ans[*returnSize] = (int *)calloc(next, sizeof(int)); /* for next level */ cur = next; count = next = 0; } } return ans; } int main() { struct TreeNode *r = (struct TreeNode *)calloc(7, sizeof(struct TreeNode)); struct TreeNode *p = r; p->val = 3; p->left = r + 1; p->right = r + 2; p = r + 1; p->val = 9; p = r + 2; p->val = 20; p->left = r + 3; p->right = r + 4; p = r + 3; p->val = 15; p = r + 4; p->val = 7; int *columnSizes = NULL; int returnSize = 0; int **ret = levelOrder(r, &columnSizes, &returnSize); int i, j; for (i = 0; i < returnSize; i++) { for (j = 0; j < columnSizes[i]; j++) { printf("%d ", ret[i][j]); } printf("\n"); free(ret[i]); } free(ret); free(columnSizes); return 0; }
C
/***************************************** Filename: PWM_thru_GPIO.c Author: James Massucco Date: 11/03/2014 Purpose: Produce PWM signal which is on for 2000usec with a period of 20000usec. IMPORTANT NOTE: The GPIO initialization script, GPIO_Init.sh, MUST be run as root BEFORE running this program. *****************************************/ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> /** * open GPIO and return file handle * @param gpio_num GPIO number * @return file handle */ int open_GPIO(int gpio_num); /** * Generate numPerods periods of PWM signal. * Note function blocks while generating the signal. * * @param period PWM period [micro seconds] * @param onDuration on duration [micro seconds] * @param numPerods how many periods to generate? * @param fd file descriptor of GPIO device file */ void PWM_gen(int period, int onDuration, int numPeriods, int fd); int main() { printf("\n----------- Generate PWM Signal: -------------\n\n"); // file descriptor for 13 int fdNum; printf("Enter a servo number:\n"); scanf("%d", &fdNum); printf("Enter a position between 600 and 2400\n"); int pos; scanf("%d", &pos); int fd; // open device file on Linux file system fd = open_GPIO(fdNum); // generate PWM signal with 20ms period and 1.5ms on time // generate 400 periods, this will take 20ms * 400 iterations = 8s PWM_gen(20000, pos, 400, fd); sleep(1); // wait for an additional second close(fd); //Close Linux GPIO interface file before exiting return 0; } /* User should create unique fd in main for each opening of a GPIO port. Suggested naming scheme is "fd#" where # is the GPIO port number being opened */ int open_GPIO(int gpio_num) { // local var for device name char deviceName[128]; // local var for file handle int fileHandle; /// GPIO device files will follow the format /// /sys/class/gpio/gpio<NR>/value /// <NR> has to be replaced with the actual number sprintf(deviceName, "/sys/class/gpio/gpio%d/value",gpio_num); // open file in file system and get file pointer fileHandle = open(deviceName, O_WRONLY); // return file pointer return fileHandle; } /** * Generate numPerods periods of PWM signal. * Note function blocks while generating the signal. * * @param period PWM period [micro seconds] * @param onDuration on duration [micro seconds] * @param numPerods how many periods to generate? * @param fd file descriptor of GPIO device file */ void PWM_gen(int period, int onDuration, int numPeriods, int fd) { int i; // period counter // generate numPeriods periods of the PWM signal for (i = 0; i < numPeriods; i++) { write(fd, "1", 1 ); // write 1 to raise pin to 1, starting the "on" cycle usleep(onDuration); // wait for duration of on portion of cycle write(fd, "0", 1 ); // write 0 to start off portion usleep(period - onDuration); // wait for duration of off portion of cycle } return; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lemin__room_show.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abombard <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/08 18:10:55 by abombard #+# #+# */ /* Updated: 2016/12/08 18:10:56 by abombard ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin__room.h" #include "ft_printf.h" extern void room_show(t_room *room) { t_neighbor *n; t_room *r; t_list *pos; ft_fprintf(2, "Room {%s}:\nPos %d %d\nPath Index: %d\nNeighbors:", room->name, room->x, room->y, room->path_index); pos = &room->neighbors; while ((pos = pos->next) && pos != &room->neighbors) { n = CONTAINER_OF(pos, t_neighbor, list); ft_fprintf(2, " %s", n->room->name); } ft_fprintf(2, "\n"); } extern void rooms_show(t_list *head) { t_room *room; t_list *pos; pos = head; while ((pos = pos->next) && pos != head) { room = CONTAINER_OF(pos, t_room, list); room_show(room); } }
C
/* * main.c * * Created on: May 29, 2021 * Author: cory */ #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "tlpi_hdr.h" #include <string.h> struct path_list { char *name; __ino_t inode; __dev_t device; struct path_list *next; struct path_list *prev; }; struct path_head { struct path_list *first; struct path_list *last; size_t strlen; char *full_path; }; static void add_item_to_ph(struct path_head *ph, struct dirent *ent, __dev_t device) { struct path_list *item; item = malloc(sizeof(struct path_list)); item->name = strdup(ent->d_name); item->inode = ent->d_ino; item->device = device; item->next = NULL; item->prev = NULL; if (ph->last == NULL) { ph->last = item; ph->first = item; ph->strlen = strlen(item->name); } else { item->next = ph->first; ph->first->prev = item; ph->first = item; ph->strlen += strlen(item->name)+1; } } static void build_path(struct path_head *ph) { DIR *dir; struct dirent *ent; struct stat *st, *ost; int fd; __ino_t now; __ino_t then; ph->first = NULL; ph->last = NULL; then = 0; ost = NULL; st = NULL; for (;;){ if ((dir = opendir(".")) == NULL) errExit("opendir"); fd = dirfd(dir); if((st = malloc(sizeof(struct stat))) == NULL) errExit("malloc\n"); fstat(fd,st); while((ent = readdir(dir)) != NULL) { if (strcmp(ent->d_name,".") == 0) { now = ent->d_ino; if (now == then) { ent->d_name[0] = '/'; ent->d_name[1] = '\0'; goto build_path__out; } } if (then == ent->d_ino) { add_item_to_ph(ph, ent, ost->st_dev); } } if (ost != NULL) free(ost); then = now; ost = st; closedir(dir); chdir(".."); } build_path__out: if (ost != NULL) free(ost); if (st != NULL) free(st); ph->strlen++; return; } static void construct_path(struct path_head *ph) { char *full_path; struct path_list *cur, *swap; full_path = malloc(sizeof(char)*(ph->strlen+1)); if (full_path == NULL) errExit("malloc\n"); full_path[0] = '/'; full_path[1] = '\0'; cur = ph->first; swap = NULL; while(cur != NULL) { strcat(full_path,cur->name); if (swap != NULL) { free(swap->name); free(swap); } swap = cur; cur = cur->next; if (cur != NULL) strcat(full_path,"/"); } ph->full_path = full_path; } static char *my_getcwd(char *buf, size_t size) { struct path_head ph; struct stat s; char *ret; build_path(&ph); construct_path(&ph); ret = NULL; if (stat(ph.full_path,&s) == -1) { free((ph.last->name)); free((ph.last)); free((ph.full_path)); return NULL; } if (s.st_ino == ph.last->inode && s.st_dev == ph.last->device) ret = buf; else { free(ph.full_path); errno = ENOENT; return NULL; } free((ph.last->name)); free((ph.last)); if (strlen(ph.full_path)+1 > size) { errno = ERANGE; ret = NULL; free(ph.full_path); return NULL; } buf[0] = '\0'; strcat(buf,ph.full_path); return ret; } int main(int argc, char *argv[]) { char x[PATH_MAX]; if (my_getcwd(x,PATH_MAX) != NULL) printf("Current Working Directory: %s\n",x); }
C
#include <stdio.h> #include <string.h> #define maxn 100 int left, chance; char s[maxn], s2[maxn]; int win, lose; void guess(char ch); int main(int argc, char *argv[]) { int rnd; while (scanf("%d%s%s", &rnd, s, s2) == 3 && rnd != -1) { printf("Round %d\n", rnd); win = lose = 0; left = strlen(s); chance = 7; for (int i = 0; i < strlen(s2); i++) { guess(s2[i]); if (win || lose) break; } if(win) printf("You win.\n"); else if(lose) printf("You lose.\n"); else printf("You chickened out.\n"); } return 0; } void guess(char ch) { int bad = 1; for (int i = 0; i < strlen(s); i++) { if (s[i] == ch) { left--; s[i] = ' '; bad = 0; } //if (bad) {--chance;} //if (!chance) lose = 1; //if (!left) win = 1; } if (bad) {--chance;} if (!chance) lose = 1; if (!left) win = 1; }
C
/* File Comment * --------------------------------------------------------------------------------------------------- * [FILE NAME]: <adc.h> * * [AUTHOR]: Abdallah Hossam-Eldin Hosny * * [DATE CREATED]: <31 - 10 - 2020> * * [DESCRIPTION]: <Header file for ADC(Analog to Digital Converter> * --------------------------------------------------------------------------------------------------- */ /* * NOTE THAT : * The ADC must Work with FREQUENCY between 50 KHz to 200 KHz */ #ifndef ADC_H_ #define ADC_H_ #include "common_macros.h" #include "std_types.h" #include "micro_config.h" #define INTERRUPT 1 /* * set it to 0 to work with Polling * set it to 1 to work with Interrupts */ #if INTERRUPT == 1 /* * Variable to get the data of ADC from ISR in interrupt mode */ extern volatile uint16 g_ADCdata; #endif #define VOLTAGE_REFERENCE 0 /* * set it to 0 to work with AREF PIN * set it to 1 to work with AVCC * set it to 2 to work with internal 2.56V */ #define PRESCALER 8 /* * to choose ADC prescaler * the Available input is {2, 4, 8, 16, 32, 64, 128} * The ADC must Work with FREQUENCY between 50 KHz to 200 KHz */ #if (INTERRUPT == 0) /* * TO make the return type of the function (ADC_readChannel) is (uint16) */ #define VOID_UINT16 uint16 #elif(INTERRUPT == 1) #define VOID_UINT16 void /* * TO make the return type of the function (ADC_readChannel) is (void) */ #endif void ADC_init(void); VOID_UINT16 ADC_readChannel(uint8 a_channelNum); #endif /* ADC_H_ */
C
#include <stdio.h> #include <stdlib.h> #define TAM 2 int buscarLibre(int[], int); void mostrarAlumnos(int[], char[][20], int[], int[], float[], int); float calcularPromedio(int, int); int cargarAlumno(int[], char[][20], int[], int[], float[], int); void pedirDatos(int[], char[][20], int[], int[], float[], int, int); int buscarAlumno(int num, int* legajo, int); void ordenarNombre(char [][20], int , int *, int *, int *, float*); int main() { int legajo[TAM]= {}; char nombre[TAM][20]; int nota1[TAM]; int nota2[TAM]; float promedio[TAM]; int opcion; int index; int legajoAux; do { printf("1. ALTAS\n2. MOSTRAR\n3. MODIFICAR\n4.BAJA\n5.ORDENAR (por nombre)\n9. SALIR\nElija una opcion: "); scanf("%d", &opcion); switch(opcion) { case 1: index = cargarAlumno(legajo, nombre, nota1, nota2, promedio, TAM); if(index == -1) printf("No hay lugar\n"); else printf("Alumno ingresado\n"); break; case 2: mostrarAlumnos(legajo, nombre, nota1, nota2, promedio, TAM); break; case 3: printf("Legajo: "); scanf("%d", &legajoAux); index = buscarAlumno(legajoAux, legajo, TAM); if(index == -1) printf("Alumno inexistente\n"); else { pedirDatos(legajo, nombre, nota1, nota2, promedio, TAM, index); printf("Alumno modificado\n"); } break; case 4: printf("Padron: "); scanf("%d", &legajoAux); index = buscarAlumno(legajoAux, legajo, TAM); if(index == -1) printf("Alumno inexistente\n"); else { legajo[index] = 0; printf("Registro borrado\n"); } break; case 5: ordenarNombre(nombre, TAM, legajo, nota1, nota2, promedio); mostrarAlumnos(legajo, nombre, nota1, nota2, promedio, TAM); break; case 9: opcion = 9; printf("Programa finalizado"); break; default: printf("Opcion invalida\n"); break; } } while(opcion != 9); return 0; } int buscarLibre(int legajo[], int tam) { int index = -1; int i; for(i = 0; i < tam; i++) { if(legajo[i] == 0) { index = i; break; } } return index; } int cargarAlumno(int legajo[], char nombre[][20], int nota1[], int nota2[], float promedio[], int tam) { int index ; index = buscarLibre(legajo, tam); if(index != -1) pedirDatos(legajo, nombre, nota1, nota2, promedio, tam, index); return index; } float calcularPromedio(int nota1, int nota2) { float promedio; promedio = (float)(nota1 + nota2) / 2; return promedio; } void mostrarAlumnos(int legajo[], char nombre[][20], int nota1[], int nota2[], float promedio[], int tam) { int i; for(i = 0; i < tam; i++) { if(legajo[i] != 0) printf("Legajo: %d\n Nombre: %s\n 1er nota: %d\n 2da nota: %d\n Promedio: %f\n", legajo[i], nombre[i], nota1[i], nota2[i], promedio[i]); } } void pedirDatos(int legajo[], char nombre[][20], int nota1[], int nota2[], float promedio[], int tam, int index) { printf("Nombre: "); fflush(stdin); gets(nombre[index]); printf("Legajo: "); scanf("%d", &legajo[index]); printf("1era nota: "); scanf("%d", &nota1[index]); printf("2da nota: "); scanf("%d", &nota2[index]); promedio[index] = calcularPromedio(nota1[index], nota2[index]); } int buscarAlumno(int alumno, int* legajo, int len) { int i; int index = -1; for(i = 0; i < len; i++) { if(legajo[i] == alumno) { index = i; break; } } return index; } void ordenarNombre(char nombre[][20], int len, int *legajo, int *nota1, int *nota2, float *promedio) { int i; int j; char aux[20]; int legajoAux; int nota2Aux; int nota1Aux; float promedioAux; for(i = 0; i < len - 1; i++) { for(j = i + 1; j < len; j++) { if(stricmp(nombre[i], nombre[j]) > 0) { strcpy(aux, nombre[i]); strcpy(nombre[i], nombre[j]); strcpy(nombre[j], aux); //break; legajoAux = legajo[i]; legajo[i] = legajo[j]; legajo[j] = legajoAux; nota1Aux = nota1[i]; nota1[i] = nota1[j]; nota1[j] = nota1Aux; nota2Aux = nota2[i]; nota2[i] = nota2[j]; nota2[j] = nota2Aux; promedioAux = promedio[i]; promedio[i] = promedio[j]; promedio[j] = promedioAux; } } } }
C
// 二叉树搜索 #include<stdio.h> #include<stdlib.h> // Definition for a binary tree node. typedef struct TreeNode* tree_node_t; struct TreeNode { int val; tree_node_t left; tree_node_t right; int left_space,right_space,pre_space; }; tree_node_t create_tree_node(int *nums,int len,int idx); // 创建二叉树 tree_node_t create_tree(int *nums,int size) { // 递归创建根节点 tree_node_t root = create_tree_node(nums,size,0); if (NULL==root) { printf("create tree fail"); } return root; } tree_node_t create_tree_node(int *nums,int len,int idx) { if (idx >= len) { return NULL; } tree_node_t node = (tree_node_t)malloc(sizeof(*node)); node->val = nums[idx]; node->left = create_tree_node(nums,len,2*idx+1); node->right = create_tree_node(nums,len,2*idx+2); return node; } // 打印二叉树 void print_tree(tree_node_t root) { } tree_node_t calc_space(tree_node_t node) { if (node->left == NULL && node->right == NULL) { node->left_space = 0; node->right_space = 0; } else { if (node->right != NULL) { node->right->pre_space = 1; node->right_space = calc_space(node->right)->left_space + 1 + calc_space(node->right)->right_space; } if (node->left != NULL) { node->left->pre_space = node->pre_space; node->left_space = calc_space(node->left)->left_space +1 +calc_space(node->left)->right_space; } } return node; } // 释放二叉树 void free_tree(tree_node_t root) { if (root) { free_tree(root->left); free_tree(root->right); free(root); } } // bfs遍历二叉树 void bfs_visit_tree(tree_node_t root) { } // dfs遍历二叉树 void dfs_visit_tree(tree_node_t root) { if (root) { printf("val:%d\n",root->val); dfs_visit_tree(root->left); dfs_visit_tree(root->right); } } int main() { int size = 8; int *nums = (int *)malloc(size*sizeof(int)); int i; for (i=0;i<size;i++) { *(nums+i) = i; } tree_node_t root = create_tree(nums,size); dfs_visit_tree(root); free(nums); free_tree(root); }
C
/* 5-17-19 Plays a simple tune, broadcasts it in the AM radio band. We wiggle the volume envelop of the carrier with a pitch. The idea is to create a radio signal that has a carrier (high constant frequency signal 1 MhZ) and a radio signal that will modulate the amplitude of the carrier. The radio signal has a frequency between 61Hz and 1560Hz timer0 will toggle pin PD5 at a frequency of 1MHz and timer 1 will turn on and off this carrier to produce a pitch (note) using an interrupt. so timer0 is the carrier. Timer0: The tick clock is 16MHz. It is in CTC mode. it is toggling PD5 (antenna pin according to pinDefines.h_ non stop but only if PD5 is in output mode. so if PD5 is not in an output mode then the carrier can not be emitted. by changing the direction (output or input) of PD5 we will modulate the volume of the carrier (just HIGH or LOW at the pitch frequency) So the value of the counter of timer0 does not change (OCR0A). It will toggle every time the counter reaches its max value set in register OCR0A. if the value is 7 and the tick frequency is 16MHz (prescaler =1 so 0.063us between tick) that means the counts counts 7+1 ticks before toggling. so every tick = 0.063 x 8 us. The counter counts till 0.5us. The period of the carrier is 0.5us x 2 = 1us so the frequency of the carrier is 1Mhz. So the carrier is controlled by timer 0. its job is to toggle the PD5 at a frequency of 1MHz as long as PD5 direction=1 Note if the uC has a frequency of 8MHz without external cristal then the number of the counter to reach is 3. for a 8Mhz and a prescaler of 1 then we need a counter value of 3. but here we have an external cristal so we don't have to mess up with the fuses. timer1 creates the radio signal that modulates the timer0. Timer1 is attached to an interrupt. The interrupt routine is called when the value in the counter 0CR1A is reached. The routine will toggle PD5 thus modulating the carrier. The routine till toggle PD5 (turning on and off the carrier) by cahding the direction of PD5. The frequency of the clock tick for timer 1 is reduced to 2Mhz. (prescaler of 8) the value of the counter (OC1R!A) will change with the note we want to play. For example A0 (note) is 5946x2 for the value of the counter to reach. It is a 16bits counter so max is 65,535. We are supposed to get a better accuracy than we the 8 bits timer from last code (counter_waveform). so in our example for A0 the counter counts 5947x2 ticks = 5942 x 2 (1/2000000) = 6ms/ so a period of 12ms or frequency of 84Hz this is 3 times *27.5Hz the fundamental of A0. So the radio plays the third harmonics. https://pages.mtu.edu/~suits/notefreqs.html see for fundamentals. The values of the counter for timer1 to reach to play a given note are defined in scale16.h (I multiplied the values by 2 because my clock runs at 2MHz and not 1MHz. prescaler of 8 so 16MHx/2 = 8 MHz). for example 5946x2 for A2. When the timer 1 reaches this value the interrupt is called and we change the direction of PD5 to turn it on and off. So the 1MHz carrier is modulates with a period defined by 5947x2x2x(2/1000000)-> 84Hz (A2 note). When we are done with emitting the note only the carrier is emitted. (PD5 has a direction of 1). reference: https://www.sparkfun.com/datasheets/Components/SMD/ATMega328.pdf */ // ------- Preamble -------- // #include <avr/io.h> /* Defines pins, ports, etc */ #include <util/delay.h> /* Functions to waste time */ #include <avr/power.h> #include <avr/interrupt.h> #include "pinDefines.h" #include "scale16.h" #define COUNTER_VALUE 7 /* determines carrier frequency . 1Mhz here. the carrier is the frequency the radio (reciever) has to be tuned to to hear the signal. we have a 16MHz uC with external cristal and a prescaler of 1. If the counter has a value of 7 it counts till 8 so the frequency is 1MHz 1/16000000 = time between tick. that value X (COUNTER-VALUE + 1) = time for counter to reach max. that value X 2 = period. frequency= 1/T */ static inline void initTimer0(void) { // timer0 is the carrier. It will toggle the pd5 as long as its output is 1 (output mode) TCCR0A |= (1 << WGM01); /* CTC mode */ TCCR0A |= (1 << COM0B0); /* Toggles pin each time through */ TCCR0B |= (1 << CS00); /* Clock at CPU frequency, 16MHz prescaler is 1 */ OCR0A = COUNTER_VALUE; /* carrier frequency */ } static inline void initTimer1(void) { TCCR1B |= (1 << WGM12); /* CTC mode */ TCCR1B |= (1 << CS11); /* Clock at CPU/8 frequency, ~2MHz because I have an external cristal 16MHz. we are supposed to get 1Mhz because the code (and the scale16.h) was written for a 8MHz standalone chip. So to fix this problem I will multiply the pitch (max counter) is the routine transmitBeep by 2. It is a 16 bits counter so it should not be a problem. max value for counter is 10,000 for a C2 . 10,000x2 = 20,000 smaller than (2^16 -1) */ TIMSK1 |= (1 << OCIE1A); /* enable output compare interrupt . For timer1 ISR will be called when interrupts are on and when the counter reach the pitch value or max counter given in 0CR1A counter*/ } // if interrupts are on . as soon as pitch is reached the PD5 is toggled by changing the mode output on/off. Only when it is on the carrier is emitted. ISR(TIMER1_COMPA_vect) { /* ISR for audio-rate Timer 1 */ ANTENNA_DDR ^= (1 << ANTENNA); /* toggle carrier on and off */ } static inline void transmitBeep(uint16_t pitch, uint16_t duration) { OCR1A = 2*pitch; /* set pitch for timer1 . I multiply by 2 because I don't have a 1MHz tick clock but 2Mhz and the music scale is for a 1MHz. */ sei(); /* turn on interrupts */ do { _delay_ms(1); /* delay for pitch cycles */ duration--; } while (duration > 0); cli(); /* and disable ISR so that it stops toggling */ ANTENNA_DDR |= (1 << ANTENNA); /* back on full carrier . carrier is on when there is no pitch. It is a flat signal. to remove noise.*/ } int main(void) { // -------- Inits --------- // //clock_prescale_set(clock_div_1); /* if we don't have an external clock. I don't need that because I have an external cristal // If you buy a chip without external chrystal they divide the clock by 8 to reduce power apparently. this command is to get back the full clock/ initTimer0(); //initialization of timers. initTimer1(); // ------ Event loop ------ // while (1) { transmitBeep(A0, 200); // play the radio signal that will modulate the volume of the carrier. /* if you want to check if we get the right frequency you can repeat the above line for ever.You get the carrier modulated by A0 = 84Hz * which is the third harmonix 27.5 x 3. The counter max value is 5946x2 . With a clock tick of 2Mhz (16Mhz/8). * if I connect an ocilloscope to the signal I can detect only the carrier 1Mhz. So you can connect the singal to a low pass filter RC with * R = 5Kohms and C=0.1uF pin PD5 -> R -> C -> gnd. I connect the oscilloscope across the C and I do get the 84Hz!! (plus some residual Mhz on top. * but most if it is gone. */ _delay_ms(200); transmitBeep(E3, 200); _delay_ms(200); transmitBeep(E3, 200); _delay_ms(200); transmitBeep(C3, 200); transmitBeep(E3, 200); _delay_ms(200); transmitBeep(G3, 400); _delay_ms(500); transmitBeep(G2, 400); _delay_ms(2500); } /* End event loop */ return 0; /* This line is never reached */ }
C
/*************************************************************************************************************************************** Problem: Write a program that calls fork(). Before calling fork(), have the main process access a variable (e.g., x) and set its value to something (e.g., 100). What value is the variable in the child process? What happens to the variable when both the child and parent change the value of x? *****************************************************************************************************************************************/ //Solution #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int main() { int x = 100; printf("The intial value of x is %d\n", x); printf("Running the parent process with pid :%d\n", (int)getpid()); //Forking a new process int rc = fork(); if (rc < 0){ // Fork has failed fprintf(stderr,"Fork Failed"); } else if (rc==0){ printf("Inside the chlid process with pid: %d\n", (int)getpid() ); printf("The initial value of x in child is %d\n", x); x= 20; printf("The final value of x in child is %d\n", x); }else{ printf("Inside the Parent process with pid: %d\n", (int)getpid() ); printf("The initial value of x in parent is %d\n", x); x= 30; printf("The final value of x in parent is %d\n", x); } } /************************************************************************************************************** Result The intial value of x is 100 Running the parent process with pid :8622 Inside the Parent process with pid: 8622 The initial value of x in parent is 100 The final value of x in parent is 30 Inside the chlid process with pid: 8626 The initial value of x in child is 100 The final value of x in child is 20 **************************************************************************************************************/
C
//еĻʵ #ifndef _QUEUE_H_ #define -QUEUE_H_ typedef struct QNode { QElemType data; struct QNode *next; }QNode,*QueuePtr; typedef struct { // QueuePtr front;//ͷָ룻 QueuePtr rear;//βָ }LinkQueue; Status InitQueue(LinkQueue &Q); Status DestroyQueue(LinkQueue &Q); Status ClearQueue(LinkQueue &Q); Status QueueEmpty (LinkQueue &Q); int QueueLength (LinkQueue &Q); Status GetHead (LinkQueue Q,QElemType &e); Status Enqueue (LinkQueue Q,QElemType &e); Status Dequeue (LinkQueue Q,QElemType &e); Status QueueTraverse (LinkQueue Q, Status (*visit)(QElemType &e)); Status visit_display(QElemType &e);
C
/* * ReadIndex.c * * Created on: Oct 26, 2012 * Author: Jonas Schreiber */ #ifndef READINDEX_C_ #define READINDEX_C_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "Files.h" #include "Words.h" #include "Search.h" struct Words * readIndex(FILE * file) { struct Words word = malloc(sizeof(struct Words)); return *word; } void interactiveMode(struct Words * word) { char * input = "blank"; printf("enter q to quit at any time"); printf("search> "); scanf("%s", &input); while (strcmp(input, "q") != 0) { //to protect against program terminating upon someone mistakenly pressing enter while (strcmp(input, NULL) == 0) { printf("search> "); scanf("%s", &input); } /* * Steps from here: * 1. determine if first two chars are so or sa, if not print help and do not proceed to next step * 2. break search terms into tokens omitting first word, (which is either so or sa) * 3. send to search Operations with params * (1, **searchTerms) for an "so" search * OR * (2, **searchTerms) for an sa search */ printf("search> "); scanf("%s", &input); } return; } /** * searchTypes * 1. so (search with OR operations, as in which of the files contains any of these terms) * 2. sa (search with AND operations, as in which of the files contains all of these terms) */ void searchOperations(int searchType, char **searchTerms) { } int main(int argc, char **argv) { if (argc != 2 || (argc == 2 && strcmp(argv[1], "-h") == 0)) { printf("USAGE:\tsearch <inverted-index file name>"); printf("HELP: \tsearch -h "); } else { FILE *file = fopen(argv[1], "r"); if (file == NULL) { /* could not open file */ fprintf(stderr, "Could not open %s\n", argv[1]); return 0; } else { struct Words word = readIndex(file); interactiveMode(word); } } return 0; } #endif /* READINDEX_C_ */
C
#include "console.h" #include "gdt.h" #include "idt.h" #include "isrs.h" #include "irq.h" #include "timer.h" #include "kernel.h" #include "kbd.h" #include "multiboot.h" #include "rand.h" /* We will use this later on for reading from the I/O ports to get data * from devices such as the keyboard. We are using what is called * 'inline assembly' in these routines to actually do the work */ unsigned char inb (unsigned short _port) { unsigned char rv; __asm__ __volatile__ ("inb %1, %0" : "=a" (rv) : "dN" (_port)); return rv; } /* We will use this to write to I/O ports to send bytes to devices. This * will be used in the next tutorial for changing the textmode cursor * position. Again, we use some inline assembly for the stuff that simply * cannot be done in C */ void outb (unsigned short _port, unsigned char _data) { __asm__ __volatile__ ("outb %1, %0" : : "dN" (_port), "a" (_data)); } /** issue a single request to CPUID. Fits 'intel features', for instance * note that even if only "eax" and "edx" are of interrest, other registers * will be modified by the operation, so we need to tell the compiler about it. */ inline void cpuid(int code, dword *a, dword *d) { asm volatile("cpuid":"=a"(*a),"=d"(*d):"0"(code):"ecx","ebx"); } /** issue a complete request, storing general registers output as a string */ inline int cpuid_string(int code, dword where[4]) { int highest; asm volatile("cpuid":"=a"(*where),"=b"(*(where+1)), "=c"(*(where+2)),"=d"(*(where+3)):"0"(code)); return highest; } #define LEFT 0 #define RIGHT 1 #define UP 2 #define DOWN 3 #define HEAD_C '#' #define BODY_C '*' #define FRUIT_C '@' #define BACK 0x0 #define FORE 0xF void gameLoop() { kcls(); unsigned short attrib = (BACK << 4) | ((FORE & 0x0F) << 8); unsigned short *vgaBuffer = (unsigned short*) 0xB8000; unsigned int playerPositions[256]; unsigned int playerCount = 1; playerPositions[0] = (5 * 80) + 30; unsigned int direction = RIGHT; unsigned int last_tick; unsigned int fruitLocation = genrand_int32() % 2000; for(;;) { last_tick = timer_ticks; // check keypresses switch (keyDown) { case ARROW_LEFT: if (direction == RIGHT) break; direction = LEFT; break; case ARROW_RIGHT: if (direction == LEFT) break; direction = RIGHT; break; case ARROW_UP: if (direction == DOWN) break; direction = UP; break; case ARROW_DOWN: if (direction == UP) break; direction = DOWN; break; } int clearPlayerPosition = playerPositions[playerCount - 1]; // shift positions if (playerCount > 1) { int i = 0; for (i = playerCount - 2; i >= 0; i--) playerPositions[i+1] = playerPositions[i]; } int tr = playerPositions[0] / 80; int tc = playerPositions[0] % 80; // move player switch (direction) { case LEFT: tc--; break; case RIGHT: tc++; break; case UP: tr--; break; case DOWN: tr++; break; } // edge check if (tc >= 80) tc = 0; if (tc < 0) tc = 79; if (tr < 0) tr = 24; if (tr >= 25) tr = 0; // update for edge check playerPositions[0] = (tr * 80) + tc; // collision check char c = vgaBuffer[playerPositions[0]] & 0xFF; if (c == BODY_C || c == HEAD_C) { // game over kputs("Game over!\n"); kputs("Your Score: "); kputi(playerCount); return; } if (c == FRUIT_C) { playerCount++; playerPositions[playerCount - 1] = clearPlayerPosition; clearPlayerPosition = -1; fruitLocation = genrand_int32() % 2000; } // draw // clear old position if (clearPlayerPosition >= 0) vgaBuffer[clearPlayerPosition] = attrib; // draw new position vgaBuffer[playerPositions[0]] = attrib | (HEAD_C & 0xFF); // draw fruit vgaBuffer[fruitLocation] = attrib | (FRUIT_C & 0xFF); if (playerCount > 1) { // redraw previous position vgaBuffer[playerPositions[1]] = attrib | (BODY_C & 0xFF); } // 18 "fps" while (last_tick == timer_ticks); } } unsigned char readCMOS(unsigned char addr) { unsigned char r; outb(0x70,addr); __asm__ __volatile__ ("jmp 1f; 1: jmp 1f;1:"); r = inb(0x71); __asm__ __volatile__ ("jmp 1f; 1: jmp 1f;1:"); return r; } #define BCD2BIN(bcd) ((((bcd)&15) + ((bcd)>>4)*10)) void get_time_stuff() { asm("cli"); /* now.sec = BCD2BIN(readCMOS(0x0)); now.min = BCD2BIN(readCMOS(0x2)); now.hour = BCD2BIN(readCMOS(0x4)); now.day = BCD2BIN(readCMOS(0x7)); now.month = BCD2BIN(readCMOS(0x8)); now.year = BCD2BIN(readCMOS(0x9)); */ asm("sti"); } void seedRandomUsingRTC() { unsigned long seed = 0; asm("cli"); seed = BCD2BIN(readCMOS(0x0)); seed |= (BCD2BIN(readCMOS(0x2)) << 6); seed |= (BCD2BIN(readCMOS(0x4)) << 12); seed |= (BCD2BIN(readCMOS(0x7)) << 18); seed |= (BCD2BIN(readCMOS(0x8)) << 24); seed |= (BCD2BIN(readCMOS(0x9)) << 30); asm("sti"); init_genrand(seed); } void kmain( multiboot_info_t* mbd, unsigned int magic ) { gdt_install(); idt_install(); isrs_install(); irq_install(); __asm__ __volatile__ ("sti"); unsigned char* video = (unsigned char*)0xA0000; int i = 0; for (; i < 255; i++) { video[i] = (unsigned char) i; } // fuck all this shit console_s con; con.buffer = (unsigned short *)0xB8000; con.c_back = 0x0; con.c_fore = 0xF; con.c_col = 0; con.c_row = 0; cur_c = &con; kcls(); kputs("Hello, World!\n"); get_time_stuff(); seedRandomUsingRTC(); timer_install(); //timer_phase(2); // this doesn't work right in virtualbox, so leave at default 18.222hz keyboard_install(); gameLoop(); for(;;); }
C
#include "stdio.h" #include "string.h" #include "bsp.h" #include "CC1101.H" #define LED_GPIO_PORT GPIOA #define LED_GPIO_PINS GPIO_Pin_6 volatile u16 Cnt1ms = 0; // 1msÿ1msһ int RecvWaitTime = 0; // յȴʱ u16 SendCnt = 0; // ͵ݰ // ֡ͷ Դַ Ŀַ distance*10 ֡β u8 SendBuffer[SEND_LENGTH] = {0x55, 0, 0xff, 15, 0x0d, 0x0a}; // ӻ // ֡ͷ Դַ Ŀַ ֡β u8 AckBuffer[ACK_LENGTH] = {0x55, 0xff, 0, 0x0d, 0x0a}; // Ӧ void TIM3_Set(u8 sta); // TIM3Ŀ sta:0ر 1 void USART1_SendStr(unsigned char *Str); // USARTַ void System_Initial(void); // ϵͳʼ void Sleep_Initial(void); // AWUʱѳʼ u8 RF_SendPacket(u8 *Sendbuffer, u8 length); // ӻݰ void DelayMs(u16 x); // printf֧ int putchar(int c) { while(!USART_GetFlagStatus (USART_FLAG_TXE));//ȴ USART_SendData8((uint8_t)c); return (c); } void Delay(__IO uint16_t nCount) { /* Decrement nCount value */ while (nCount != 0) { nCount--; } } void main(void) { volatile u8 res = 0; volatile u8 Timer_30s = 6; // ϵ緢 System_Initial(); // ʼϵͳ CC1101Init(); // ʼCC1101Ϊģʽ SendBuffer[1] = TX_Address; // ݰԴַӻַ //Sleep_Initial(); // AWUʱѳʼ // ͨŲ // while(1) // { // LED_ON(); // LED˸ָʾͳɹ // CC1101Init(); // send: // res = RF_SendPacket(SendBuffer, SEND_LENGTH); // if(res != 0) // { // printf("Send ERROR:%d\r\nRetry now...\r\n", (int)res); // ʧ // DelayMs(300); // goto send; // } // else printf("Send OK!\r\n"); // ͳɹ // LED_OFF(); // DelayMs(1000);DelayMs(1000);DelayMs(1000); // } while(1) { printf("Timer_30s=%d\r\n", (int)Timer_30s); if(Timer_30s++ == 6) // Լ 3 Min 30s * 6 { SWITCH_ON(); LED_ON(); // LED˸ָʾͳɹ CC1101Init(); send: res = RF_SendPacket(SendBuffer, SEND_LENGTH); if(res != 0) { printf("Send ERROR:%d\r\nRetry now...\r\n", (int)res); // ʧ DelayMs(10); //DelayMs(350); goto send; } else printf("Send OK!\r\n"); // ͳɹ SWITCH_OFF(); LED_OFF(); Timer_30s = 1; } halt();//͹ } } // TIM3Ŀ // sta:0ر 1 void TIM3_Set(u8 sta) { if(sta) { TIM3_SetCounter(0); // TIM3_ITConfig(TIM3_IT_Update,ENABLE); // ʹTIM3ж TIM3_Cmd(ENABLE); // ʹTIM3 } else { TIM3_Cmd(DISABLE); // رTIM3 TIM3_ITConfig(TIM3_IT_Update,DISABLE); // رTIM3ж } } /*=========================================================================== * : DelayMs() => ʱ(ms) * * x, Ҫʱ(0-65535) * ============================================================================*/ void DelayMs(u16 x) { volatile u16 timer_ms = x; Cnt1ms = 0; TIM3_Set(1); while(Cnt1ms <= timer_ms); TIM3_Set(0); } /*=========================================================================== * TIM3_1MS_ISR() => ʱ3, ʱʱ׼Ϊ1ms * ============================================================================*/ void TIM3_1MS_ISR(void) { Cnt1ms++; if(RecvWaitTime > 0) RecvWaitTime--; // ݽռʱ } /*=========================================================================== * : System_Initial() => ʼϵͳ * ============================================================================*/ void System_Initial(void) { SClK_Initial(); // ʼϵͳʱӣ16M GPIO_Initial(); // ʼGPIO LED USART1_Initial(); // ʼ1 TIM3_Initial(); // ʼʱ3׼1ms SPI_Initial(); // ʼSPI enableInterrupts(); // ж printf("Oil_Can_Drone\r\n"); // ַĩβ } /*=========================================================================== * : BSP_RF_SendPacket() => ߷ݺ * * Sendbufferָ͵ݣlengthݳ * * 0ͳɹ 1ȴӦʱ 2ݰȴ 3ݰ֡ͷ 4ݰԴַ 5ݰĿַ 6ݰ֡β ============================================================================*/ INT8U RF_SendPacket(INT8U *Sendbuffer, INT8U length) { uint8_t i = 0, ack_len = 0, ack_buffer[15] = {0}; RecvWaitTime = (int)RECV_TIMEOUT; // ȴӦʱ1500ms CC1101SendPacket(SendBuffer, length, ADDRESS_CHECK); // //DelayMs(5); //CC1101Init(); // ʼL01Ĵ CC1101SetTRMode(RX_MODE); // ׼Ӧ TIM3_Set(1); // TIM3 printf("waiting for ack...\r\n"); while(CC_IRQ_READ() != 0) // ȴݰ { if(RecvWaitTime <= 0) { TIM3_Set(0); // رTIM3 printf("RecvWaitTime0=%d\r\n", RecvWaitTime); return 1; // ȴӦʱ } } //TIM3_Set(0); //printf("RecvWaitTime1=%d\r\n", RecvWaitTime); RecvWaitTime = 50; // ȴӦʱ50ms //TIM3_Set(1); // TIM3 while(CC_IRQ_READ() == 0) { if(RecvWaitTime <= 0) { TIM3_Set(0); // رTIM3 printf("RecvWaitTime1=%d\r\n", RecvWaitTime); return 1; // ȴӦʱ } } printf("RecvWaitTime2=%d\r\n", RecvWaitTime); TIM3_Set(0); // رTIM3 ack_len = CC1101RecPacket(ack_buffer); // ȡյ // // ֡ͷ Դַ Ŀַ ֡β //AckBuffer[ACK_LENGTH] = {0x55, 0xff, 0, 0x0d, 0x0a}; // Ӧ // if((strlen((const char*)ack_buffer) <= 0) || (strlen((const char*)ack_buffer)) > 29) // { // CC1101Init(); // printf("ack_len0=%d\r\n", ack_len); // return 2; // ݰȴ // } if(ack_len <= 0 || ack_len > 15) { CC1101Init(); printf("ack_len1=%d\r\n", ack_len); return 2; // ݰȴ } if(ack_len != ACK_LENGTH) return 2; // ݰȴ if(ack_buffer[0] != 0x55) return 3; // ݰ֡ͷ if(ack_buffer[1] != 0xff) return 4; // ݰԴַ if(ack_buffer[2] == 0xff) return 5; // ݰĿַ if((ack_buffer[ack_len-2] != 0x0d) || (ack_buffer[ack_len-1] != 0x0a)) return 6; // ݰ֡β // Ӧȷ printf("ack_len=%d;ack_buffer:", (int)ack_len); for(i = 0; i < ack_len; i++) { printf("%d ", (int)ack_buffer[i]); } printf("\r\n"); return 0; } /******************************************************************************* ****ڲҪ͵ַ ****ڲ ****עUSARTַ *******************************************************************************/ void USART1_SendStr(unsigned char *Str) { while(*Str!=0)//Ϊ { USART_SendData8(*Str); // while(!USART_GetFlagStatus (USART_FLAG_TXE));//ȴ Str++;//һ } } // AWUʱѳʼ void Sleep_Initial(void) { // IOȫ͵ƽ ͹ GPIO_Init(GPIOA, GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_7, GPIO_Mode_Out_PP_Low_Slow); GPIO_Init(GPIOB, GPIO_Pin_0|GPIO_Pin_1, GPIO_Mode_Out_PP_Low_Slow); GPIO_Init(GPIOC, GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_7, GPIO_Mode_Out_PP_Low_Slow); GPIO_Init(GPIOD, GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7, GPIO_Mode_Out_PP_Low_Slow); CLK_PeripheralClockConfig(CLK_Peripheral_AWU, ENABLE); // ʹAWUʱ AWU_DeInit(); // AWUָʼ״̬ AWU_LSICalibrationConfig(12800); // AWU LSIУ׼ΪAWUDZLSI AWU_Init(AWU_Timebase_30s); // 30sʱ AWU_Cmd(ENABLE); // ʹAWU }
C
/* Primer mejoramiento: { Solicitar datos de la cuenta Validar si el usuario excede el limite de credito de su cuenta Si excede el limite de credito de su cuenta entonces escribir en pantalla que excedio el limite de crédito. \ } Segundo mejoramiento: { Solicitar numero de cuenta, saldo inicial del mes, total de elementos cargados al cliente este mes y limite autorizado para su cuenta hasta que el usuario introduzca -1 en el numero de cuenta Calcular el nuevo saldo del la cuenta Validar si el nuevo saldo excede el limite de crédito para la cuenta Si se excede el limite imprimir el numero de cuenta, el limite de la cuenta, el saldo y un mensaje "Límite de crédito excedido" } Tercer mejoramiento: { Declarar la variable entera numeroCuenta Declarar las variables tipo flotante saldoInicial, cargosDelMes, totalCreditos, limiteCreditos, saldoActual Mientras el numero de cuenta sea diferente a -1 Solicitar el numero de cuenta y asignarlo a la variable numeroCuenta Si numero cuenta es diferente a -1 Solicitar el saldo inicial y asignarlo a la variable saldoInicial Solicitar el total de cargos y asignarlo a la variable cargosDelMes Solicitar el total de créditos y asignarlo a la variable totalCreditos Solicitar el límite de crétidos y asignarlo a la variable limiteCreditos Operar saldoInicial mas cargosDelMes menos totalCreditos y asignar el valor a saldoActual Validar si el saldoActual es mayor a limiteCreditos Imprimir "Cuenta: " y numeroCuenta Imprimir "Limite de crédito: " limiteCredito Imprimir "Saldo: " saldoActual Imprimir "Límite de crédito excedido." } */ #include <stdio.h> /* Inicio del main */ int main(){ int numeroCuenta = 0; float saldoInicial = 0.0; float cargosDelMes = 0.0; float totalCreditos = 0.0; float limiteCretditos = 0.0; float saldoActual = 0.0; while (numeroCuenta != -1){ printf("Introduzca el número de cuenta (-1 para terminar): \n"); scanf("%d", &numeroCuenta); if (numeroCuenta != -1){ printf("Introduzca el saldo inicial: \n"); scanf("%f", &saldoInicial); printf("Introduzca el total de cargos: \n"); scanf("%f", &cargosDelMes); printf("Introduzca el total de créditos: \n"); scanf("%f", &totalCreditos); printf("Introduzca el límite de créditos: \n"); scanf("%f", &limiteCretditos); saldoActual = saldoInicial + cargosDelMes - totalCreditos; if (saldoActual > limiteCretditos){ printf("Cuenta: %d\nLimite de crédito: %.2f\nSaldo: %.2f\nLímite de crédito excedido.\n", numeroCuenta, limiteCretditos, saldoActual); }/*end if */ }/* end if */ }/* end while */ }/* end main */
C
#include <stdbool.h> #include <stdlib.h> #include "backpack.h" #include "item.h" #include "container.h" struct backpack* create_backpack(const int capacity) { struct backpack* batoh = calloc((size_t) 1, sizeof(struct backpack)); if(batoh == NULL) { return NULL; } batoh->capacity = capacity; batoh->size = 0; return batoh; } struct backpack* destroy_backpack(struct backpack* backpack) { if(backpack == NULL) { return NULL; } destroy_containers(backpack->items); free(backpack); return NULL; } bool add_item_to_backpack(struct backpack* backpack, struct item* item) { if(backpack == NULL || item == NULL) { return false; } if(backpack->size == backpack->capacity) { return false; } backpack->items = create_container(backpack->items, ITEM, item); backpack->size += 1; return true; } void delete_item_from_backpack(struct backpack* backpack, struct item* item) { if(backpack == NULL || item == NULL) { return; } backpack->items = remove_container(backpack->items, item); backpack->size -= 1; } struct item* get_item_from_backpack(const struct backpack* backpack, char* name) { if(backpack == NULL || name == NULL) { return NULL; } return get_from_container_by_name(backpack->items, name); }
C
#include <stdio.h> int p1() { long long n; int i; int k; int num; while(scanf("%lld", &n) == 1 && n != 0) { while(n>0) { k = 0; scanf("%d", &num); for(i = 1; i*i < num; i++) if(num % i == 0) k += 2; if(i*i == num) k++; printf("%d\n", k); n--; } } }
C
int strcmp(const char *str1, const char *str2) { const char *it1 = str1; const char *it2 = str2; while (*it1 && *it2 && it1 == it2) { it1 += 1; it2 += 1; } return *it1 - *it2; }
C
#include <stdio.h> #include <cs50.h> #include <math.h> unsigned long sumDigits(long long number) { unsigned long sum = 0; while (number != 0) { int digit = number % 10; sum += digit; number /= 10; } return sum; } int main() { // get input from user and save it to variable printf("Enter some number\n"); long long input = GetLongLong(); unsigned long sum = sumDigits(input); // display result printf("Sum is %lu\n", sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include<locale.h> #include<string.h> #include<conio.c> #include<windows.h> #include<ctype.h> #include "funcoes.c" #include "parteprodutos.c" #include "RCL.c" int main(){ int cont=0; char vet[30]=""; while(cont <= 100){ gotoxy(5,10); printf("Carregando...\n"); gotoxy(5,12); strcat(vet,"\xDB"); printf("%s %d%%",vet, cont ); Sleep(50); if(cont!=100) system("cls"); cont+=4; } getch(); setlocale(LC_ALL, "PTB"); int opcao, tam = 1; char resp; do{ fflush(stdin); opcao = 66; system("cls"); printf("\n 1 - Cadastrar Clientes\t\t\t5 - Cadastrar produto"); printf("\n 2 - Consultar Clientes Cadastrados\t\t6 - Consultar produto por descrio"); printf("\n 3 - Excluir Cliente por CPF\t\t\t7 - Excluir Produto por cdigo"); printf("\n 4 - Alterar dados de Cliente\t\t\t8 - Alterar dados do produto"); printf("\n\n"); printf("\t\t\t\t9 - Realizar vendas"); printf("\n\t\t\t\t10 - Consultar Estoque"); printf("\n\t\t\t\t11 - Lista produto vendidos com lucro"); printf("\n\t\t\t\t0 - SAIR"); printf("\n\n"); printf("Digite uma opo: "); scanf("%d", &opcao); switch(opcao){ case 0: printf("Volte Sempre\n"); getch(); break; case 1: cadastro(tam); break; case 2: consultar(tam); break; case 3: excluir(); break; case 4: alterar(); break; case 5: cadastroP(tam); break; case 6: consultarP(tam); break; case 7: excluirP(); break; case 8: alterarP(); break; case 9: realizar_venda(); break; case 10: estoque(); break; case 11: lpvcl(); break; default: printf("\nNumero invalido\n"); getch(); } }while(opcao != 0); getch(); return 0; }
C
#include "player.h" #include "dice.h" static int keep [N_DICE]; int keepWhichDice(void){ int answer; printf("input one die at the time that you want to keep, Finish with a 0\n"); while(TRUE){ answer = GetInteger(); if(answer == 0) break; keep[answer - 1] = KEEP; } }/* int getrow(int index){ int row; while(TRUE){ printf("what row do you want to out in your score?"); row=GetInteger(); } }*/ bool keepDie(int keep){ if (keep == 1){ return TRUE; } else{ return FALSE; } }
C
/* * Ficheiro: mesh.h * * Definicao da malha de entrada. * * Input mesh definition. */ #ifndef _MESH_H_ #define _MESH_H_ /* Constants. */ /* To ensure the minimal distance of the main distribution wires. */ #define Y_BASE_STEP 3 /* Data structures. */ typedef struct Clock_Zone_Str{ int clk; /* Numerical value of the clock zone's clock. */ int start; /* Point of start of this clock zone along the wire. */ }clock_zone; /* Array of copies. */ /* Functions. */ int input_mesh( circuit cir ); clock_zone border_find( clock_zone* array, unsigned int n_elements, int x ); int raise_y_base( int* y_base_array, unsigned int n_elements, unsigned int y, unsigned int delta ); int find_in_array( int* array, unsigned int n_elements, int value ); int find_clk_min( gate* array, unsigned int n_elements ); int find_y_min( gate* array, unsigned int n_elements ); int find_x_min( gate* array, unsigned int n_elements ); int find_x_max( gate* array, unsigned int n_elements ); int copy_comparator( void* a, void* b ); /* static int copy_comparator( const void* a, const void* b ); */ /* Macros. */ #define Y_BASE_INIT(y) \ ( ( ((y)%(Y_BASE_STEP)) )? \ ( (((y)/(Y_BASE_STEP))+1)*(Y_BASE_STEP) ) \ : (y) ) #endif /* * EOF */
C
/** * @file : LESSON_33 project file * @author : MEHMET AKSU * @note : [email protected] * @date : 11 / September / 2020 * @code : normal_termination_exit.c file * @details : */ #include <stdio.h> #include <stdlib.h> void f4() { printf("f4() basladi\n"); exit(EXIT_FAILURE); printf("f4() sona erdi\n"); } void f3() { printf("f3() basladi\n"); f4(); printf("f3() sona erdi\n"); } void f2() { printf("f2() basladi\n"); f3(); printf("f2() sona erdi\n"); } void f1() { printf("f1() basladi\n"); f2(); printf("f1() sona erdi\n"); } int main(void) { printf("main() basladi\n"); f1(); printf("main() sona erdi\n"); return 0; }
C
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++* * Stego.c: A program for manipulating images * *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #include <string.h> #include "image.h" /* THE WAY BYTES ARE INDEXED 00000000 00000000 00000000 00000000 3 2 1 0 */ #define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d\n" #define BYTETOBINARY(byte) \ (byte & 0x80 ? 1 : 0), \ (byte & 0x40 ? 1 : 0), \ (byte & 0x20 ? 1 : 0), \ (byte & 0x10 ? 1 : 0), \ (byte & 0x08 ? 1 : 0), \ (byte & 0x04 ? 1 : 0), \ (byte & 0x02 ? 1 : 0), \ (byte & 0x01 ? 1 : 0) #define PRINTBIN(x) printf(BYTETOBINARYPATTERN, BYTETOBINARY(x)); byte getByte(byte b0,int byteNum) { return b0>>byteNum*8; } byte getbit(byte b0, int bitnum) { //passing in a byte and getting the bit at index bitnum b0 = b0>>bitnum; //what does >> do? b0 = b0 & 0x01; return b0; } //Setting the bit at a specific index: byte setbit(byte *b0, int bitnum, int val) { byte mask=1; mask=mask<<bitnum; if(val)//meaning val is equal to 1 { byte ch= mask | *b0; return ch; } else //meaning val = 0 { byte ch = ~mask & *b0; return ch; } } void setlsbs(byte *p,int val) { //Replacing the bits of p with lsb of b0 *p=setbit(p,0,val); } int main(int argc, char *argv[]) { int i, j, k, cover_bits, bits; struct Buffer b = {NULL, 0, 0}; struct Image img = {0, NULL, NULL, NULL, NULL, 0, 0}; char *s; byte b0; if (argc != 4) { printf("\n%s <cover_file> <stego_file> <file_to_hide> \n", argv[0]); exit(1); } ReadImage(argv[1],&img); // read image file into the image buffer img // the image is an array of unsigned chars (bytes) of NofR rows // NofC columns, it should be accessed using provided macros ReadBinaryFile(argv[3],&b); // Read binary data s = strchr(argv[3],(int)'.'); if (strlen(s)!=4) s = ".txt"; printf("hidden file type = <%s>\n",s+1); // hidden information // first two bytes is the size of the hidden file // next 4 bytes is the extension (3 letters & \0) if (!GetColor) cover_bits = img.NofC*img.NofR; else cover_bits = 3*img.NofC*img.NofR; bits = (6+b.size)*8; if (bits > cover_bits) { printf("Cover file is not large enough %d (bits) > %d (cover_bits)\n",bits,cover_bits); exit(1); } // embed two size bytes //getting the 2 least significant BYTES of the integer: b0 = getByte(b.size,0); byte b1 = getByte(b.size,1); int bitItter; //THE FIRST LSB of the size is inserted into the image: for(bitItter=0;bitItter<8;bitItter++) { byte needToModify=GetGray(bitItter); //changing this byte setlsbs(&needToModify,getbit(b0,bitItter)); //then setting this byte into the image: SetGray(bitItter,needToModify); } for(bitItter+1;bitItter<16;bitItter++) { byte needToModify=GetGray(bitItter); //changing this byte setlsbs(&needToModify,getbit(b1,bitItter-8)); //then setting this byte into the image: SetGray(bitItter,needToModify); } // embed 4 file extension characters (to make it easy for the extraction) // //I need bitItter to go from 16 to 48 int extIndex=0; //droppping the . in the file extension and adding a null terminator char subs[4]; s=memcpy(subs,&s[1],3); s[3]='\0'; for(bitItter+1;bitItter<48;bitItter) { int counter=0; while(counter<8) { byte needToModify=GetGray(bitItter); byte extByte=s[extIndex] | 0x00; setlsbs(&needToModify,getbit(extByte,counter)); SetGray(bitItter,needToModify); bitItter++; counter++; } extIndex++; } //time to add data! for (i=0; i<b.size; i++) { // here you embed information into the image one byte at the time // note that you should change only the least significant bits of the image int counter=0; while(counter<8) { byte needToModify=GetGray(bitItter); setlsbs(&needToModify,getbit(b.data[i],counter)); SetGray(bitItter,needToModify); bitItter++; counter++; } } WriteImage(argv[2],img); // output stego file (cover_file + file_to_hide) }