language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* Given a positive integer n, find the pivot integer x such that: The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively. Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input. Example 1: Input: n = 8 Output: 6 Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. Example 2: Input: n = 1 Output: 1 Explanation: 1 is the pivot integer since: 1 = 1. Example 3: Input: n = 4 Output: -1 Explanation: It can be proved that no such integer exist. Constraints: 1 <= n <= 1000 */ #include <assert.h> #include <stdio.h> #include <math.h> typedef long long vlong; /* https://oeis.org/A001109 1 + 2 + ... + x = x + ... + n (1+x)*x/2 = (x+n)*(n-x+1)/2 Solve for x x = sqrt((n^2 + n) / 2) */ vlong pivotint(vlong n) { vlong x, z; if (n < 0) return -1; z = ((n * n) + n) / 2; x = sqrt(z); return (x * x == z) ? x : -1; } int main(void) { assert(pivotint(8) == 6); assert(pivotint(1) == 1); assert(pivotint(4) == -1); return 0; }
C
/* Author:Alphonce F. Stephano Email/: alphoncesteven@gmail.com Company-Group: afsaTech || SuperMesh */ #include <stdio.h> int factorial(int numb) { if(numb > 1) { return numb*factorial(numb-1); } else { return 1; } } int main(void) { int numb; tryagain: printf("Enter an integer number 1 and 10 inclusive:"); scanf("%d",&numb); if(numb >= 1 && numb <= 10) { printf("The factorial of number %d is:%d\n",numb,factorial(numb)); printf("The square of number %d is:%d\n",numb,numb*numb); } else { printf("The number is out of the range. Try again\n\n"); goto tryagain; } return 0; }
C
#include <stdio.h> #define dprint(expr) printf("<main>"#expr"=%d\n",expr) #define DPRINT(fmt,args...) printf(fmt,###args) #define paste(front,back) front##back int main(int argc, const char *argv[]) { int x = 100, y=2, name1 = 100; dprint(x/y); dprint(x+y); dprint(x+y+2); printf("name1 = %d \n", name1); paste( name,1) = 123; printf("name1 = %d \n", name1); #if 0 DPRINT("a = %d b = %d ", 100, 200); #endif return 0; }
C
#include "hclib.h" int ____num_tasks[32] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; # include <stdlib.h> # include <stdio.h> # include <math.h> # include <time.h> # include <string.h> # include "poisson.h" # include "main.h" # include "timer.h" double r8mat_rms(int nx, int ny, double *a_); void rhs(int nx, int ny, double *f_, int block_size); void timestamp(void); double u_exact(double x, double y); double uxxyy_exact(double x, double y); /* Purpose: MAIN is the main program for POISSON_OPENMP. Discussion: POISSON_OPENMP is a program for solving the Poisson problem. This program uses OpenMP for parallel execution. The Poisson equation - DEL^2 U(X,Y) = F(X,Y) is solved on the unit square [0,1] x [0,1] using a grid of NX by NX evenly spaced points. The first and last points in each direction are boundary points. The boundary conditions and F are set so that the exact solution is U(x,y) = sin ( pi * x * y) so that - DEL^2 U(x,y) = pi^2 * ( x^2 + y^2) * sin ( pi * x * y) The Jacobi iteration is repeatedly applied until convergence is detected. For convenience in writing the discretized equations, we assume that NX = NY. Licensing: This code is distributed under the GNU LGPL license. Modified: 14 December 2011 Author: John Burkardt */ /******************************************************************************/ double run(struct user_parameters* params) { int matrix_size = params->matrix_size; if (matrix_size <= 0) { matrix_size = 512; params->matrix_size = matrix_size; } int block_size = params->blocksize; if (block_size <= 0) { block_size = 128; params->blocksize = block_size; } int niter = params->titer; if (niter <= 0) { niter = 4; params->titer = niter; } double dx; double dy; double error; int ii,i; int jj,j; int nx = matrix_size; int ny = matrix_size; double *f = (double *)malloc(nx * nx * sizeof(double)); double *u = (double *)malloc(nx * nx * sizeof(double)); double *unew = (double *)malloc(nx * ny * sizeof(double)); /* test if valid */ if ( (nx % block_size) || (ny % block_size) ) { params->succeed = 0; params->string2display = "*****ERROR: blocsize must divide NX and NY"; return 0; } /// INITIALISATION dx = 1.0 / (double) (nx - 1); dy = 1.0 / (double) (ny - 1); // Set the right hand side array F. rhs(nx, ny, f, block_size); /* Set the initial solution estimate UNEW. We are "allowed" to pick up the boundary conditions exactly. */ hclib_pragma_marker("omp", "parallel", "pragma116_omp_parallel"); { hclib_pragma_marker("omp", "single", "pragma118_omp_single"); //for collapse(2) for (j = 0; j < ny; j+= block_size) { for (i = 0; i < nx; i+= block_size) { hclib_pragma_marker("omp", "task firstprivate(i,j) private(ii,jj)", "pragma122_omp_task"); for (jj=j; jj<j+block_size; ++jj) { for (ii=i; ii<i+block_size; ++ii) { if (ii == 0 || ii == nx - 1 || jj == 0 || jj == ny - 1) { (unew)[ii * ny + jj] = (f)[ii * ny + jj]; } else { (unew)[ii * ny + jj] = 0.0; } } } } } } /// KERNEL INTENSIVE COMPUTATION START_TIMER; sweep(nx, ny, dx, dy, f, 0, niter, u, unew, block_size); END_TIMER; if(params->check) { double x; double y; double *udiff = (double *)malloc(nx * ny * sizeof(double)); /// CHECK OUTPUT // Check for convergence. for (j = 0; j < ny; j++) { y = (double) (j) / (double) (ny - 1); for (i = 0; i < nx; i++) { x = (double) (i) / (double) (nx - 1); (udiff)[i * ny + j] = (unew)[i * ny + j] - u_exact(x, y); } } error = r8mat_rms(nx, ny, udiff); double error1; // Set the right hand side array F. rhs(nx, ny, f, block_size); /* Set the initial solution estimate UNEW. We are "allowed" to pick up the boundary conditions exactly. */ for (j = 0; j < ny; j++) { for (i = 0; i < nx; i++) { if (i == 0 || i == nx - 1 || j == 0 || j == ny - 1) { (unew)[i * ny + j] = (f)[i * ny + j]; } else { (unew)[i * ny + j] = 0.0; } } } sweep_seq(nx, ny, dx, dy, f, 0, niter, u, unew); // Check for convergence. for (j = 0; j < ny; j++) { y = (double) (j) / (double) (ny - 1); for (i = 0; i < nx; i++) { x = (double) (i) / (double) (nx - 1); (udiff)[i * ny + j] = (unew)[i * ny + j] - u_exact(x, y); } } error1 = r8mat_rms(nx, ny, udiff); params->succeed = fabs(error - error1) < 1.0E-6; free(udiff); } free(f); free(u); free(unew); return TIMER; } /* R8MAT_RMS returns the RMS norm of a vector stored as a matrix. */ double r8mat_rms(int nx, int ny, double *a_) { double (*a)[nx][ny] = (double (*)[nx][ny])a_; int i; int j; double v; v = 0.0; for (j = 0; j < ny; j++) { for (i = 0; i < nx; i++) { v = v + (*a)[i][j] * (*a)[i][j]; } } v = sqrt(v / (double) (nx * ny)); return v; } /* RHS initializes the right hand side "vector". */ void rhs(int nx, int ny, double *f, int block_size) { int i,ii; int j,jj; double x; double y; // The "boundary" entries of F store the boundary values of the solution. // The "interior" entries of F store the right hand sides of the Poisson equation. hclib_pragma_marker("omp", "parallel", "pragma225_omp_parallel"); { hclib_pragma_marker("omp", "single", "pragma227_omp_single"); //for collapse(2) for (j = 0; j < ny; j+=block_size) { for (i = 0; i < nx; i+=block_size) { hclib_pragma_marker("omp", "task firstprivate(block_size,i,j,nx,ny) private(ii,jj,x,y)", "pragma231_omp_task"); for (jj=j; jj<j+block_size; ++jj) { y = (double) (jj) / (double) (ny - 1); for (ii=i; ii<i+block_size; ++ii) { x = (double) (ii) / (double) (nx - 1); if (ii == 0 || ii == nx - 1 || jj == 0 || jj == ny - 1) (f)[ii * ny + jj] = u_exact(x, y); else (f)[ii * ny + jj] = - uxxyy_exact(x, y); } } } } } } /* Evaluates the exact solution. */ double u_exact(double x, double y) { double pi = 3.141592653589793; double value; value = sin(pi * x * y); return value; } /* Evaluates (d/dx d/dx + d/dy d/dy) of the exact solution. */ double uxxyy_exact(double x, double y) { double pi = 3.141592653589793; double value; value = - pi * pi * (x * x + y * y) * sin(pi * x * y); return value; }
C
/*Implemente uma função que receba como parâmetro um array de números reais de tamanho N e retorne quantos números negativos há nesse array. Essa função deve obedecer ao protótipo: int negativos(float *vet, int N);*/ #include<stdio.h> #include<stdlib.h> #define tam 9 int negativos(float*, int); int main(int argc, char *argv[]){ float vet[tam] = {5, -2, 15, 3, -7, 15,-8, 6, 15}; int numeros_negativos; numeros_negativos = negativos(vet,tam); printf("Negativos: %d\n", numeros_negativos); return 0; } int negativos(float* vet, int N){ int nnegativo = 0; for(int i=0; i<N; i++){ if(vet[i]<0) nnegativo++; } return nnegativo; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lm_path_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: clianne <clianne@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/26 08:09:01 by clianne #+# #+# */ /* Updated: 2020/01/08 11:42:56 by clianne ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" /* ** to sort conn nodes by length */ void path_sort_by_length(t_path **path) { t_path *start_path; t_path *end_path; if (!*path || !(*path)->next) return ; path_length_count(*path); start_path = *path; end_path = path_get_last_elem(*path); do_alg_quick_sort(start_path, end_path); path_calc_med(*path); } /* ** to copy path: del and copy src to dest paths */ t_path *path_copy(t_path **src) { t_path *new_path; t_path *node; if (!*src) return (0); new_path = 0; node = *src; while (node) { path_push_back(&new_path, node->lnks); node = node->next; } return (new_path); } /* ** to count len of paths */ void path_length_count(t_path *path) { t_path *node; t_rconn *rconn; if (!path) return ; node = path; while (node) { node->length = 0; rconn = node->lnks; while (rconn) { if (rconn->room->room_type != -2 || (rconn->room->room_type == -2 && !((rconn->next && rconn->next->room->split_room == rconn->room) || (rconn->prev && rconn->prev->room->split_room == rconn->room)))) node->length++; rconn = rconn->next; } node = node->next; } } /* ** to get path with min length */ t_path *path_get_min_length(t_path *head) { t_path *min; if (!head) return (NULL); min = head; while (head) { if (head->length < min->length) min = head; head = head->next; } return (min); } /* ** to calculate med for paths */ void path_calc_med(t_path *head) { t_path *node_1; t_path *node_2; int med; if (!head) return ; node_1 = head; while (node_1) { med = 0; node_2 = head; while (node_2 != node_1) { med += node_1->length - node_2->length; node_2 = node_2->next; } node_1->med = med; node_1 = node_1->next; } }
C
#include <iostream> #include <fstream> #include <vector> //#include "MyFunc.h" using namespace std; //!targetFile.eof() unsigned long long gcd(unsigned long long a, unsigned long long b) { for (;;) { if (a == 0) return b; b %= a; if (b == 0) return a; a %= b; } } unsigned long long PrevLcm(unsigned long long *arr,int cell){ unsigned long long result =1; if(cell==0) return arr[cell]; //check if we are at border already for ( int i=0; i<cell; i++){ result = lcm(arr[i], result); } return result; } unsigned long long AheadLcm(unsigned long long *arr,int cell,int size){ unsigned long long result =1; //cout<<" cell "<<cell<<" result: "; if(cell==size-1) { //cout<<"gotcha"<<endl; return arr[size]; } for ( int i=size-1; i>cell; i--){ result = lcm(arr[i], result); } return result; } unsigned long long lcm(unsigned long long a, unsigned long long b) { unsigned long long temp = gcd(a, b); if(temp>0) return ((b/temp)* a ); else return 0; //return temp ? (a / temp * b) : 0; } int main(int argc, char *argv[]) { if (argc > 1) { ifstream targetFile; targetFile.open(argv[1]); //open txt given as argument if(targetFile.fail()){ //give error message in case file doesnt open cout<<"Error opening File"<<endl; exit(1); } int villages,tmp,counter=0; unsigned long long *vill,*tmp2,*tmp3; targetFile >>villages; //get first char which just gives number of villages vill= new unsigned long long[villages]; // cout<<villages<<endl; cout<<"hello world"<<end; tmp2=vill; while(!targetFile.eof()){ //get each char till you reach eof //cout<<"entered loop "<<endl; targetFile>>tmp; *tmp2=tmp; //cout<<"tmp"<<tmp<<" what we got "<<*tmp2<<" at counter "<<counter<<endl; tmp2++; //xi.push_back(tmp); cout<<counter<<" "<<endl; counter++; } cout<<endl; unsigned long long tmp5,result=lcm(PrevLcm(vill,0),AheadLcm(vill,0,villages)); int pistolVillage=0; // cout<<"0:"<<" gives "<<result<<endl; for(int i=1;i<villages;i++){ tmp5=lcm(PrevLcm(vill,i),AheadLcm(vill,i,villages)); //cout<<"i:"<<i<<" gives "<<tmp5<<endl; if(result>tmp5){ result=tmp5; pistolVillage=i;counter++; } } if(counter==villages){ cout<<result<<" 0"; } else cout<<result<<" "<<pistolVillage+1; return 0; } return 1; }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> #define PI 3.14159265 typedef long double Typ; struct point{Typ x, y, z; struct point * next;}; #define Point struct point Point * make_Point(Typ X, Typ Y, Typ Z) { Point * nowy = malloc(sizeof(Point)); nowy->x=X; nowy->y=Y; nowy->z=Z; nowy->next = NULL; return nowy; } struct vector{Point * first, * last;}; #define Vector struct vector Vector cube; int t; void append(Vector V) { if(cube.first == NULL) { cube = V; return; } (cube.last)->next = V.first; (cube.last) = V.last; } void Init(Point * start) { cube.first = start; start->next = NULL; cube.last = start; } Point * copy_Point(Point * it) { Point * res; res = make_Point(it->x,it->y,it->z); return res; } Vector copy_Vector(Vector V) { Vector res; (res.first) = copy_Point(V.first); Point * it = res.first; Point * jt = (V.first)->next; while(jt != NULL) { it->next = copy_Point(jt); it = (it->next); jt = (jt->next); } it->next = NULL; res.last = it; return res; } void clear(Vector V) { Point * it = V.first; Point * tmp; while(it != NULL) { tmp = it; it = it->next; free(tmp); } } void move(Vector V, Typ ox, Typ oy, Typ oz) { Point * it; for(it = V.first; it!=NULL; it=(it->next)) { (it->x)+=ox; (it->y)+=oy; (it->z)+=oz; } } void rotateA(Vector tmp) { Point * it; for(it = tmp.first; it!=NULL; it = (it->next)) { Typ c = it->y; it->y = t-it->z; it->z = c; } } void rotateB(Vector tmp) { Point * it; for(it = tmp.first; it!=NULL; it = (it->next)) { Typ c = it->x; it->x = it->z; it->z = t-c; } } void rotateC(Vector tmp) { Point * it; for(it = tmp.first; it!=NULL; it = (it->next)) { Typ c = it->x; it->x = t-it->y; it->y = c; } } Vector A(Vector tmp) { Vector res; res = copy_Vector(tmp); rotateA(res); rotateB(res); return res; } Vector B(Vector tmp) { Vector res; res = copy_Vector(tmp); rotateC(res); int i; for(i=0; i<3; i++) rotateB(res); return res; } Vector C(Vector tmp) { Vector res; res = copy_Vector(tmp); int i; for(i=0; i<2; i++) rotateC(res); return res; } Vector D(Vector tmp) { Vector res; res = copy_Vector(tmp); rotateC(res); rotateB(res); return res; } Vector E(Vector tmp) { Vector res; res = copy_Vector(tmp); int i; for(i=0; i<3; i++) rotateA(res); for(i=0; i<3; i++) rotateB(res); return res; } void draw_curve(int n) { Init(make_Point(0,0,0)); Vector next, tmp; int i; for(i=1; i<=n; i++) { tmp = copy_Vector(cube); clear(cube); cube.first = cube.last = NULL; int off = 1<<(i-1); t = off-1; next = A(tmp); move(next,off,off,0); append(next); next = B(tmp); move(next,off,0,0); append(next); next = B(tmp); move(next,0,0,0); append(next); next = C(tmp); move(next,0,off,0); append(next); next = C(tmp); move(next,0,off,off); append(next); next = D(tmp); move(next,0,0,off); append(next); next = D(tmp); move(next,off,0,off); append(next); next = E(tmp); move(next,off,off,off); append(next); clear(tmp); tmp.first = tmp.last = NULL; } } Point * middle; void scale(Point * p, Typ u) { p->x *= u; p->y *= u; p->z *= u; } Typ cosinus, sinus; void turnOX(Point * p) { p->x -= middle->x; p->y -= middle->y; p->z -= middle->z; Typ y = p->y, z = p->z; p->y = cosinus*y - sinus*z; p->z = sinus*y + cosinus*z; p->x += middle->x; p->y += middle->y; p->z += middle->z; } void turnOY(Point * p) { p->x -= middle->x; p->y -= middle->y; p->z -= middle->z; Typ x = p->x, z = p->z; p->x = cosinus*x + sinus*z; p->z = -sinus*x + cosinus*z; p->x += middle->x; p->y += middle->y; p->z += middle->z; } void projection(Point * p, Typ d) { p->x = (d * p->x) / (d + p->z); p->y = (d * p->y) / (d + p->z); } void transform_cube(int n, Typ s, Typ u, Typ d, int x, int y, int z, Typ alfa, Typ beta) { alfa *= -PI/180.0; beta *= PI/180.0; Typ edge_len = (Typ) (1<<n)-1; Point * it; for(it=cube.first; it!=NULL; it = (it->next)) { scale(it,u/edge_len); } Typ mid = u/2.0; middle = make_Point(mid,mid,mid); sinus = sin(alfa); cosinus = cos(alfa); for(it=cube.first; it!=NULL; it = (it->next)) { turnOX(it); } sinus = sin(beta); cosinus = cos(beta); for(it=cube.first; it!=NULL; it = (it->next)) { turnOY(it); } move(cube,(long double)x,(long double)y,(long double)z); for(it=cube.first; it!=NULL; it = (it->next)) { projection(it,d); } move(cube,(s-u)/2.0,(s-u)/2.0,0.0); } int main(int argc, char * argv[]) { int n, s, u, d, x, y, z; Typ alfa, beta; sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &s); sscanf(argv[3], "%d", &u); sscanf(argv[4], "%d", &d); sscanf(argv[5], "%d", &x); sscanf(argv[6], "%d", &y); sscanf(argv[7], "%d", &z); sscanf(argv[8], "%Lf", &alfa); sscanf(argv[9], "%Lf", &beta); Typ g = 0.4; draw_curve(n); transform_cube(n,s,u,d,x,y,z,alfa,beta); printf("\%%!PS-Adobe-2.0 EPSF-2.0\n%%%%BoundingBox 0 0 %d %d\nnewpath\n", s, s); printf("%.2Lf %.2Lf moveto\n", (cube.first)->x, (cube.first)->y); Point * it; for(it=cube.first; it != NULL; it = (it->next)) { printf("%.2Lf %.2Lf lineto\n", it->x, it->y); } printf("%.2Lf setlinewidth\nstroke\nshowpage\n%%%%Trailer\n\%%EOF\n", g); clear(cube); return 0; }
C
#include <stdio.h> //prototipo da funcao int somar(int a, int b); int subtrair(int a, int b); int multiplicar(int a, int b); int dividir(int a, int b); int somar(int a, int b){ return a+b; } int subtrair(int a, int b){ return a-b; } int multiplicar(int a, int b){ return a*b; } int dividir(int a, int b){ if (b != 0 && a>=b){ return a/b; } else{ return 0; } } //Funcao principal MAIN void main(){ int resultado = dividir(1,2); printf("Resultado: %d\n", resultado); }
C
#include<stdio.h> #include<stdlib.h> #define MAX 10007 int queue[MAX]; int rear = -1; int front = -1; void insert(int item); int del(); int peek(); int isEmpty(); int isFull(); void display(); int main(){ int choice,item; while(1){ printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display Front element\n"); printf("4.Display all\n"); scanf("%d",&choice); switch(choice){ case 1: scanf("%d",&item); insert(item); break; case 2: printf("%d deleted\n",del()); break; case 3: printf("%d\n",peek()); break; case 4: display(); break; default: exit(1); } } return 0; } void insert(int item){ if(isFull()){ printf("Full Queue!\n"); return; } if(front == -1) front =0; queue[++rear]= item; } int del(){ if(isEmpty()){ printf("Empty Queue!\n"); exit(1); } int item = queue[front]; front++; return item; } int peek(){ if(isEmpty()){ printf("Empty Queue!\n"); exit(1); } return queue[rear]; } int isEmpty(){ if(front == -1 || front == rear+1) return 1; else return 0; } int isFull(){ if(rear == MAX-1) return 1; else return 0; } void display(){ if(isEmpty()){ printf("Empty Queue!\n"); return; } int i; printf("Queue contents: \n"); for(i=front ;i<=rear ;i++) printf("%d\n",queue[i]); }
C
#pragma once #define Z 4 #define MODULE(x) x<0?x*(-1):x #define LOGIC(z) z > 3 #define STEPEN(x, y) pow(x, y) #define SQRT(x) sqrt(x) #define MAX(y,z) ((y)>(z))?(y):(z) // #define MIN(y,z) ((y)<(z))?(y):(z) #define PRINTI(w) puts("control output"); \ printf(#w"=%d\n",w) // '\' // '#' ᒺ // #define PRINTR(w) puts ("rezult :"); \ printf (#w"=%f\n",(float)w)
C
float maximum(float a, float b) { return (a>b)?a:b; } float funct(float a, float b) { return (a>b)?maximum(a,b):b; } int SIZE=1024; int main() { #ifdef __NVCUDA__ acc_init( acc_device_nvcuda ); #endif #ifdef __NVOPENCL__ acc_init( acc_device_nvocl ); //acc_list_devices_spec( acc_device_nvocl ); #endif float a[SIZE], b[SIZE], c[SIZE]; int i; for(i=0; i<2*SIZE; i++) { a[i%SIZE]=i; b[i%SIZE]=a[(i*13)%SIZE]; c[i%SIZE]=0; } #pragma acc kernels copyin(a,b) copyout(c) #pragma acc loop independent for(int i=0; i<SIZE; i++) { c[i] = funct (a[i], b[i]); //c[i] = a[i]>b[i]?a[i]:b[i]; } for (i = 0; i < SIZE; ++i) { if(c[i]!= funct(a[i],b[i])) { fprintf(stderr,"Error %d %16.10f!=%16.10f \n", i, c[i], funct(a[i],b[i])); return -1; } } fprintf(stderr,"'function call in kernels region' test was successful!\n"); return 0; }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int n; int i,j,a[n],temp; //n=5; printf("enter number"); scanf("%d",&n); printf("enter elements"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=n-1;i>=0;i--) { j=i-1; if(a[i]<a[j] && a[j]-a[i]==1) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } for(i=0;i<n;i++) { printf("%d\n",a[i]); } for(i=0;i<n;i++) { j=i+1; if(a[j]<a[i]) { printf("no"); break; } if(i==n-2) { printf("yes"); break; } } }
C
// Child process (or Player) for the "mind game". #include <stdio.h> #include <signal.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> void winhandler(int sig) { // you have won fprintf(stderr, "You have won.\n"); // pid_t ppid = getppid(); // kill(ppid, SIGCHLD); exit(0); } void lossHandler(int sig) { // you have lost fprintf(stderr, "You have lost.\n"); // pid_t ppid = getppid(); // kill(ppid, SIGCHLD); exit(0); } int main() { srand(time(NULL)); int n = 7; char choice = ' '; signal(SIGUSR1, winhandler); // handle the SIGUSR1 signal that you will get if you win signal(SIGUSR2, lossHandler); // handle the SIGUSR2 signla that you get if you lose while (1) { // srand(time(NULL)); choice = (char)((random() % 7) + '0'); putc(choice, stdout); } }
C
#include <stdio.h> /* Create a smartphone register application * Read the content of smartphones.txt and store the informations in a structure called "smartphone: * - the name of the gadget (which is shorter than 256 characters) (Don't bother with the underscore('_') character, it's the part of the name) * - the year of the release (e.g. 2016) * - the type of the screen size (as a custom type, see below) * * In the file the size is given in cm but you should store the screen size type in an enumeration ("screen_size"), * the valid types are: * - BIG -> (>= 15 cm) * - MEDIUM -> (>= 12 cm) * - SMALL -> (< 12 cm)*/ typedef enum { BIG, //-> (>= 15 cm) MEDIUM, //-> (>= 12 cm) SMALL // -> (< 12 cm) } screen_size_t; typedef struct { char name[255]; //gadget name which is shorter than 256 characters int _relase; //gadget relase year screen_size_t screen_size; // screen size enum } smartohone_t; int main () { return 0; }
C
/* * File: fileio.c * Author: Brendan McCane * Updated: Scott 2003 * Updated: Raymond 2005 * Updated: David 2014 * * Description: Contains the I/O routines. */ /* ----- INCLUDES ---------------------------------------------------------- */ /* standard libraries */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* prototypes, and type information */ #include "fileio.h" #include "typedefs.h" /* allow us to display colours, vectors, and matrices */ #include "colour_ops.h" #include "vector_ops.h" #include "matrix_ops.h" /* ---- FUNCTIONS ---------------------------------------------------------- */ /* * read the details from named file (or prompt for name if none given). * this assumes that the details are 'clean', and that all necessary * details are given in the file (such as ambient light etc...). */ void fileio_readfile(char *fname) { FILE *description_file; char filename[32]; char descriptor[20]; bool tried_opening_file = false; double x, y, z, angle; char axis; char ch; Matrix transformation; /* --- prepare the file for reading --- */ /* see if a filename has been passed in at the command line! */ if (fname) { /* dme FIX: complete with buffer overflow... */ strcpy(filename, fname); tried_opening_file = true; } else { filename[0] = '\0'; } printf("Going to try to open the file\n"); while (!(description_file=fopen(filename, "r"))) { if (tried_opening_file) { fprintf(stderr, "Error: couldn't open file %s - try again\n", filename); } else { tried_opening_file = true; } printf("Enter the name of the description file: "); fscanf(stdin, "%s", filename); printf("\n"); }; printf("Opened file\n"); /* --- prepare default values --- */ /* maximum number of reflections + Primary Ray */ MAX_RECURSE_DEPTH = 5; /* size of image on screen */ image_size = 320; super_samples = 1; /* background colour == (0, 0, 0) */ background_colour.red = 0.0; background_colour.green = 0.0; background_colour.blue = 0.0; /* ambient light == (0, 0, 0) */ ambient_light.red = 0.0; ambient_light.green = 0.0; ambient_light.blue = 0.0; /* default camera */ /* viewplane size is constant!! unless we do stupid FOV stuff * -- it is 32 units by 32 units (i.e., [-16.0, 16.0] ) */ camera.view_size = 32.0; camera.lens = 35.0; matrix_loadIdentity(&camera.transform); camera.dof_focus = 35.0; camera.dof_factor = 0; /* initial count */ num_lights = 0; num_objs = 0; /* --- Now read the rest of the values from the file --- */ fscanf(description_file, "%s", descriptor); while (strcmp(descriptor, "endview")) { /* Comment skipper */ if (descriptor[0] == '#') { ch = descriptor[0]; while ((ch != 10) && (ch != 13) && (ch != -1)) { fscanf(description_file, "%c", &ch); } } /* pixel size of the output image */ else if (!strcmp(descriptor, "imagesize")) { fscanf(description_file, "%d", &image_size); } /* background colour */ else if (!strcmp(descriptor, "background")) { fscanf(description_file, "%lf", &background_colour.red); fscanf(description_file, "%lf", &background_colour.green); fscanf(description_file, "%lf", &background_colour.blue); } /* ambient light */ else if (!strcmp(descriptor, "ambient")) { fscanf(description_file, "%lf", &ambient_light.red); fscanf(description_file, "%lf", &ambient_light.green); fscanf(description_file, "%lf", &ambient_light.blue); } /* camera lens */ else if (!strcmp(descriptor, "lens")) { fscanf(description_file, "%lf", &camera.lens); } /* super_samples */ else if (!strcmp(descriptor, "super_samples")) { fscanf(description_file, "%d", &super_samples); } /* dof_focal length */ else if (!strcmp(descriptor, "dof_focus")) { fscanf(description_file, "%lg", &camera.dof_focus); } /* dof blur factor */ else if (!strcmp(descriptor, "dof_factor")) { fscanf(description_file, "%lg", &camera.dof_factor); } /* lights */ else if (!strcmp(descriptor, "light")) { if (num_lights>=MAX_NUM_LIGHTS) { fprintf(stderr, "Error: max number of lights exceeded in description file\n"); exit(EXIT_FAILURE); } fscanf(description_file,"%lf", &light_source[num_lights].position.x); fscanf(description_file,"%lf", &light_source[num_lights].position.y); fscanf(description_file,"%lf", &light_source[num_lights].position.z); light_source[num_lights].position.w = 1.0f; fscanf(description_file,"%lf", &light_source[num_lights].colour.red); fscanf(description_file,"%lf", &light_source[num_lights].colour.green); fscanf(description_file,"%lf", &light_source[num_lights].colour.blue); num_lights++; } /* spheres */ else if (!strcmp(descriptor, "sphere")) { if (num_objs>=MAX_NUM_OBJS) { fprintf(stderr, "Error: max number of objects exceeded in description file\n"); exit(EXIT_FAILURE); } /* read the ambient colour details */ fscanf(description_file, "%s", descriptor); if (strcmp(descriptor, "ambient")) { fprintf(stderr, "ERROR IN FILE: expected keyword ambient for sphere\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%lf", &object[num_objs].material.ambient_colour.red); fscanf(description_file, "%lf", &object[num_objs].material.ambient_colour.green); fscanf(description_file, "%lf", &object[num_objs].material.ambient_colour.blue); /* read the diffuse colour details */ fscanf(description_file, "%s", descriptor); if (strcmp(descriptor, "diffuse")) { fprintf(stderr, "ERROR IN FILE: expected keyword diffuse for sphere\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%lf", &object[num_objs].material.diffuse_colour.red); fscanf(description_file, "%lf", &object[num_objs].material.diffuse_colour.green); fscanf(description_file, "%lf", &object[num_objs].material.diffuse_colour.blue); /* read the specular colour details */ fscanf(description_file, "%s", descriptor); if (strcmp(descriptor, "specular")) { fprintf(stderr, "ERROR IN FILE: expected keyword specular for sphere\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%lf", &object[num_objs].material.specular_colour.red); fscanf(description_file, "%lf", &object[num_objs].material.specular_colour.green); fscanf(description_file, "%lf", &object[num_objs].material.specular_colour.blue); fscanf(description_file, "%lf", &object[num_objs].material.phong); /* read the mirror colour details */ fscanf(description_file, "%s", descriptor); if (strcmp(descriptor, "mirror")) { fprintf(stderr, "ERROR IN FILE: expected keyword mirror for sphere\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%lf", &object[num_objs].material.mirror_colour.red); fscanf(description_file, "%lf", &object[num_objs].material.mirror_colour.green); fscanf(description_file, "%lf", &object[num_objs].material.mirror_colour.blue); /* read the texture ID */ fscanf(description_file, "%s", descriptor); if (strcmp(descriptor, "texture")) { fprintf(stderr, "ERROR IN FILE: expected keyword texture for sphere\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%d", &object[num_objs].material.texture); matrix_loadIdentity(&object[num_objs].transform); num_objs++; } /* translate last defined object (camera or sphere) */ else if (!strcmp(descriptor, "translate")) { fscanf(description_file, "%lf", &x); fscanf(description_file, "%lf", &y); fscanf(description_file, "%lf", &z); if(num_objs == 0){ matrix_make(&transformation, 1.0, 0.0, 0.0, x, 0.0, 1.0, 0.0, y, 0.0, 0.0, 1.0, z, 0.0, 0.0, 0.0, 1.0); matrix_multiply_right(&camera.transform, transformation); } else { /* store the inverse translation of the current object */ matrix_make(&transformation, 1.0, 0.0, 0.0, -x, 0.0, 1.0, 0.0, -y, 0.0, 0.0, 1.0, -z, 0.0, 0.0, 0.0, 1.0); matrix_multiply_left(&object[num_objs-1].transform, transformation); } } /* stretch last defined object (camera or sphere) */ else if (!strcmp(descriptor, "stretch")) { fscanf(description_file, "%lf", &x); fscanf(description_file, "%lf", &y); fscanf(description_file, "%lf", &z); /************************************************************/ if(num_objs == 0){ /* store the stretching of the camera */ matrix_make(&transformation, x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0); matrix_multiply_right(&camera.transform, transformation); } else { /* store the inverse stretching of the current object */ matrix_make(&transformation, 1/x, 0.0, 0.0, 0.0, 0.0, 1/y, 0.0, 0.0, 0.0, 0.0, 1/z, 0.0, 0.0, 0.0, 0.0, 1.0); matrix_multiply_left(&object[num_objs-1].transform, transformation); } } /* rotate last defined object (camera or sphere) */ else if (!strcmp(descriptor, "rotate")) { fscanf(description_file, " %c", &axis); if ((axis != 'x') && (axis != 'y') && (axis != 'z')) { fprintf(stderr, "ERROR IN FILE: expected axis for rotation\n"); exit(EXIT_FAILURE); } fscanf(description_file, "%lf", &angle); /*************************************************************/ /* deg to rads and if an object rotation => inverse rotation */ angle *= (num_objs == 0) ? (M_PI/180) : -(M_PI/180); switch(axis){ case 'x': matrix_make(&transformation, 1.0, 0.0 , 0.0 , 0.0, 0.0, cos(angle), -sin(angle), 0.0, 0.0, sin(angle), cos(angle) , 0.0, 0.0, 0.0 , 0.0 , 1.0); break; case 'y': matrix_make(&transformation, cos(angle) , 0.0, sin(angle) , 0.0, 0.0 , 1.0, 0.0 , 0.0, -sin(angle), 0.0, cos(angle) , 0.0, 0.0 , 0.0, 0.0 , 1.0); break; case 'z': matrix_make(&transformation, cos(angle) , -sin(angle), 0.0, 0.0, sin(angle) , cos(angle), 0.0, 0.0, 0.0 , 0.0 , 1.0, 0.0, 0.0 , 0.0 , 0.0, 1.0); break; } if(num_objs == 0){ /* store the rotation of the camera */ matrix_multiply_right(&camera.transform, transformation); } else { /* store the inverse rotation of the current object */ matrix_multiply_left(&object[num_objs-1].transform, transformation); } } /* unknown descriptor in file */ else { fprintf(stderr, "Error: Unknown descriptor in description file\n"); exit(-1); } /* read the next string in the file */ fscanf(description_file, "%s", descriptor); } /* close the file*/ fclose(description_file); } /* Display everything read from the file */ void fileio_printscene() { int i; printf("\n"); /* print out the size of the resultant picture */ printf("Image size %d\n", image_size); printf("\n"); /* print information about the viewing camera */ printf("Camera is:\n===\n"); printf("Viewplane size %3.1f\n", camera.view_size); printf("Lens %3.1f\n", camera.lens); printf("Transformation\n"); matrix_display(camera.transform); printf("\n"); /* print the background colour */ printf("background is: "); colour_display(background_colour); printf("\n"); /* print the ambient lighting */ printf("ambient is: "); colour_display(ambient_light); printf("\n\n"); /* print the lights */ for (i=0; i<num_lights; i++) { printf("light is: "); vector_display(light_source[i].position); printf(" "); colour_display(light_source[i].colour); printf("\n"); } printf("\n"); /* print the objects */ for (i=0; i<num_objs; i++) { printf("\nSphere is:\n===\n"); /* print this object's material details */ printf("Materials:\n Ambient: "); colour_display(object[i].material.ambient_colour); printf("\n Diffuse: "); colour_display(object[i].material.diffuse_colour); printf("\n Phong: "); colour_display(object[i].material.specular_colour); printf(" coeff [%2.4lf] \n", object[i].material.phong); printf(" Mirror: "); colour_display(object[i].material.mirror_colour); printf("\nTransformation\n"); matrix_display(object[i].transform); printf("\n"); } }
C
#include<stdio.h> int main(void){ int sum=1; int a=0,b=1,n; printf("Enter the nth term: "); scanf("%d",&n); printf("Fibonacii series till n:\n "); while (sum<=n){ printf("%d\t",sum); a=b; b=sum; sum=a+b; } //return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct node{ int val; struct node * next; }Node; Node * sumLists(Node *, Node *); void printList(Node * head); void push(Node ** head_ref, int data); void free(Node * head); int main(void){ Node * head1 = NULL, * head2 = NULL, * summed = NULL; push(&head1, 3); push(&head1, 0); push(&head1, 9); push(&head2, 2); push(&head2, 0); push(&head2, 0); printList(head1); printList(head2); summed = sumLists(head1, head2); printList(summed); free(summed); free(head1); free(head2); return 0; } void reverseList(Node ** first){ if (*first == NULL){ return; } Node * head = (*first)->next; Node * prev = *first; prev->next = NULL; while(head){ prev = head; head = head->next; prev->next = *first; *first = prev; } return; } Node * sumLists(Node * head1, Node * head2){ int carry = 0, sum = 0; Node * summed = NULL; while(head1 || head2){ sum = 0; if(head1) sum += head1->val; if(head2) sum += head2->val; Node * digit = (Node *) malloc(sizeof(Node)); digit->val = (sum +carry) % 10; carry = (sum + carry) /10; if(head1) head1 = head1->next; if(head2) head2 = head2->next; digit->next = summed; summed = digit; } if(carry){ Node * digit = (Node *) malloc(sizeof(Node)); digit->val = 1; digit->next = summed; summed = digit ; } return summed; } void push(Node ** head_ref, int data){ Node * new = (Node *)malloc(sizeof(Node)); new->val = data; new->next = *head_ref; *head_ref = new; } void printList(Node * head){ puts(""); while(head){ printf("%d->",head->val); head = head->next; } puts(""); } void free(Node * head){ while(head){ Node * prev = head; head = head->next; free(prev); } }
C
#include<stdio.h> void main() { int a,b; printf("Enter 2 numbers: "); scanf("%d %d",&a,&b); a^=b^=a^=b; printf("After swapping :a = %d b = %d",a,b); }
C
#include <stdio.h> #include <pthread.h> pthread_t thread1, thread2; void *fn1(void *arg){ int i = *(int *)arg; printf("i = %d\n", i); return ((void *)0); } struct parameter{ int size; int count; }; struct parameter arg; void *fn2(void *arg){ struct parameter *pstru; pstru = (struct parameter *) arg; printf("size = %d\n", pstru->size); printf("count = %d\n", pstru->count); return ((void *)0); } int main(){ int err1, err2; int i = 10; err1 = pthread_create(&thread1, NULL, fn1, &i); pthread_join(thread1, NULL); //pthread_join表示必须当前线程堵塞直到thread1执行完毕后才能开始执行 arg.size = 5; arg.count = 10; err1 = pthread_create(&thread2, NULL, fn2, &arg); //这里应注意如果输入的参数不是结构体arg而是i的话,则pstru = (struct parameter *) i;语句自动将i的值赋给pstru.size,而pstru.count的值为0 pthread_join(thread2, NULL); return 0; }
C
#include <stdio.h> void printd(int no); int main() { int no = 0; printf("Enter the number\n"); scanf("%d", &no); printd(no); return 0; } void printd(int n) { if (n < 0) { // /putchar('-'); n = -n; } printf("%d ", (n % 10)); if (n / 10) { printd(n / 10); } }
C
/* chronos/hvdf.c * * HVDF Single-Core Scheduler Module for ChronOS * * Author(s) * - Nahush Gondhalekar nahushg@vt.edu * * Copyright (C) 2009-2012 Virginia Tech Real Time Systems Lab */ #include <linux/module.h> #include <linux/chronos_types.h> #include <linux/chronos_sched.h> #include <linux/list.h> struct rt_info* sched_hvdf(struct list_head *head, int flags) { struct rt_info *task, *best = local_task(head->next); /*Check for each entry in the list*/ list_for_each_entry(task, head, task_list[LOCAL_LIST]){ /* Check if task is aborted, if yes, the return it. Otherwise check if the deadline is blown, if yes, abort the task using abort_thread(). {Done in handle_task_failure() function.} */ if(check_task_failure(task, flags)) return task; /* Calculate inverse value density for the current task.*/ livd(task, false, flags); /* Compare the inverse value densities and assign the higher value density task to best. */ if(task->local_ivd < best->local_ivd) best = task ; } if(flags & SCHED_FLAG_PI) best = get_pi_task(best, head, flags); return best; } struct rt_sched_local hvdf = { .base.name = "HVDF", .base.id = SCHED_RT_HVDF, .flags = 0, .schedule = sched_hvdf, .base.sort_key = SORT_KEY_DEADLINE, .base.list = LIST_HEAD_INIT(hvdf.base.list) }; static int __init hvdf_init(void) { return add_local_scheduler(&hvdf); } module_init(hvdf_init); static void __exit hvdf_exit(void) { remove_local_scheduler(&hvdf); } module_exit(hvdf_exit); MODULE_DESCRIPTION("HVDF single-Core Scheduling Module for ChronOS"); MODULE_AUTHOR("Nahush Gondhalekar <nahushg@vt.edu>"); MODULE_LICENSE("GPL");
C
/* * programs.h * * Author: rebecca */ #ifndef PROGRAMS_H_ #define PROGRAMS_H_ Instruction program1[] = { Instruction(increment, LONG, a1, a1, k, 0), Instruction(increment, LONG, a2, a2, k, 1), Instruction(multiply, SHORT, x0, x1, x1, 2), Instruction(multiply, SHORT, x6, x0, x2, 3), Instruction(increment, LONG, a3, a3, k, 4), Instruction(float_add, SHORT, x7, x6, x3, 5), Instruction(increment, LONG, a7, a7, k, 6) }; Instruction program2[] = { Instruction(increment, LONG, a1, a1, k, 0), Instruction(increment, LONG, a2, a2, k, 1), Instruction(multiply, SHORT, x0, x1, x1, 2), Instruction(multiply, SHORT, x6, x0, x2, 3), Instruction(increment, LONG, a3, a3, k, 4), Instruction(increment, LONG, a4, a4, k, 5), Instruction(multiply, SHORT, x3, x3, x1, 6), Instruction(float_add, SHORT, x5, x6, x3, 7), Instruction(float_add, SHORT, x7, x5, x4, 8), Instruction(increment, LONG, a7, a7, k, 9) }; Instruction program3[] = { Instruction(increment, LONG, a1, a1, k, 0), Instruction(increment, LONG, b0, x1, k, 1), /*loop:*/ Instruction(increment, LONG, a1, a2, k, 2), Instruction(increment, LONG, a7, a7, k, 3), Instruction(increment, LONG, a1, a1, k, 4), Instruction(multiply, SHORT, x0, x1, x1, 5), Instruction(increment, LONG, x2, b1, k, 6), Instruction(multiply, SHORT, x3, x0, x2, 7), Instruction(increment, LONG, x2, b2, k, 8), Instruction(multiply, SHORT, x4, x1, x2, 9), Instruction(float_add, SHORT, x3, x3, x4, 10), Instruction(increment, LONG, x2, b3, k, 11), Instruction(float_add, SHORT, x7, x2, x3, 12), Instruction(increment, LONG, b0, b0, k, 13), Instruction(increment, LONG, a7, a7, k, 14), Instruction(branch, SHORT, -13, 15) }; int size[] = {0, 7, 10, 72}; int program_3_loop = 5; #endif /* PROGRAMS_H_ */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_quotes.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: acase <acase@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/18 10:51:30 by acase #+# #+# */ /* Updated: 2021/01/28 13:43:38 by acase ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/pars.h" #include<stdio.h> static void singl_quote(char *str, t_flgs *flg) { if(flg->flg_one == 0) { if(flg->flg_two == 0) flg->flg_one = 1; else return; } else flg->flg_one = 0; } static void double_quote(char *str, t_flgs *flg) { if(flg->flg_two == 0) { if(flg->flg_one == 0) flg->flg_two = 1; else return ; } else flg->flg_two = 0; } int check_quotes(const char *str1, t_flgs *flg) { flg->flg_two = 0; flg->flg_one = 0; char *str = (char*)str1; while(*str) { printf("%s\n","i"); if(!ft_memcmp(str,"\'",1) || !ft_memcmp(str,"\"",1)) !ft_memcmp(str,"\'",1) ? singl_quote(str,flg) : double_quote(str,flg); str++; } return((flg->flg_two == 1 || flg->flg_one == 1) ? FALSE : TRUE); } int main() { t_all all; int i = check_quotes("a\"\'\"a",&all.flgs); printf("%d\n",i); }
C
/************************************************************************* > File Name: create.c > Author: Wangyao > Mail: Yaowang_future@163.com > Created Time: 2015年03月20日 星期五 21时26分19秒 > Function: 创建链表 ************************************************************************/ #include "stud.h" stu_list *create(stu_list *list) { stu_list *ptr1,*ptr2,*head; int i=1; int choice=1; head=(stu_list *)malloc(sizeof(stu_list)); for(ptr1=head;i++<=Len;) { printf("输入人名:\n"); scanf("%s",ptr1->name); printf("输入学号:\n"); scanf("%ld",&ptr1->stud_pid); printf("输入语文成绩:\n"); scanf("%d",&ptr1->Chinese_score); printf("输入英语成绩:\n"); scanf("%d",&ptr1->English_score); printf("是否继续输入学生信息:(1为确定 or 其他为否定)?\n"); scanf("%d",&choice); if(choice!=1) { ptr1->next=(char *)0; break; } ptr2=ptr1; ptr1=(stu_list *)malloc(sizeof(stu_list)); ptr2->next=ptr1; } return(head); }
C
#include <stdio.h> #include <stdlib.h> int* mergeEven(int M,int *arr1,int N,int *arr2) { int *merArr = malloc(sizeof(M+N)),index1=0,index2=0; for(int index=0;index<M+N;index++) { if(arr1[index1]%2!=0) merArr[index]=arr1[index1++]; else{ merArr[index]=arr1[index1++]; merArr[index+1]=arr2[index2++]; index++; } } return merArr; } int main() { int M,N; scanf("%d %d",&M,&N); int arr1[M],arr2[N]; for(int index=0;index<M;index++) scanf("%d",&arr1[index]); for(int index=0;index<N;index++) scanf("%d",&arr2[index]); int *mergedArr = mergeEven(M,arr1,N,arr2); printf("Array 1 : "); for(int index=0;index<M;index++) printf("%d ",arr1[index]); printf("\nArray 2 : "); for(int index=0;index<N;index++) printf("%d ",arr2[index]); printf("\nMerged Array : "); for(int index=0;index<M+N;index++) printf("%d ",mergedArr[index]); free(mergedArr); return 0; }
C
#include "errors.h" /* Global method which receive errorCode and lineIndex if exists and print error according to error type*/ void printError(const char* currFileName, ERROR_CODE errorCode, int lineIndex){ static char* fileName; if (errorCode == INITIALIZING) { fileName = calloc(strlen(currFileName) + strlen(".as") + 1, sizeof(char)); strcpy(fileName, currFileName); strcat(fileName, ".as"); return; }else if(errorCode == FINISHIZING){ if (fileName) { free(fileName); } return; } IS_ERROR = TRUE; switch (errorCode) { case MISSING_FILENAME: printf("\nPlease specify file name.\n"); break; case NO_SUCH_FILE: fprintf(stderr, "\nError opening file: %s, %s \n",fileName ,strerror( errno )); break; case LINE_TOO_LONG: printf("\nError at file: %s, line %d, exceeded max permitted size, 80 chars\n", fileName, lineIndex); break; case DATA_NOT_NUMBER | NUMBER_OUT_OF_BOUNDS_12BITS: printf("\nError at file: %s, line %d, all data values should be numbers in a range from %d to %d\n", fileName, lineIndex, MIN_12BIT_NUMBER, MAX_12BIT_NUMBER); break; case CANNOT_PARSE_LINE: printf("\nError at file: %s, line %d, couldn't find any valid directive or command\n", fileName, lineIndex); break; case INVALID_LABEL: printf("\nError at file: %s, line %d, Invalid label. Label should contain only letters or digits and shouldn't be more then 30 chars\n", fileName, lineIndex); break; case WRONG_NUMBER_OF_OPERATORS: printf("\nError at file: %s, line %d, Invalid number of operands\n", fileName, lineIndex); break; case LABEL_ALREADY_EXISTS: printf("\nError at file: %s, line %d, Line already exists, you can't redifine label\n", fileName, lineIndex); break; case WRONG_ADDRESSING_MODE: printf("\nError at file: %s, line %d, Wrong addressing mode\n", fileName, lineIndex); break; case NUMBER_OUT_OF_BOUNDS_10BITS: printf("\nError at file: %s, line %d, all data values should be numbers in a range from %d to %d\n", fileName, lineIndex, MIN_10BIT_NUMBER, MAX_10BIT_NUMBER); break; case LABEL_DOESNT_EXISTS: printf("\nError at file: %s, line %d, You're trying reference to label which does't exist\n", fileName, lineIndex); break; case DISPLACEMENT_EXTERNAL_LABELS_ERROR: printf("\nError at file: %s, line %d, You're cannot using external label in DISPOSAL addressing mode\n", fileName, lineIndex); /*DISPOSAL - miun mirhak*/ break; case MAX_RAM_SIZE_EXCEEDED: printf("\nError at file: %s, You exceded max RAM size of %d words\n", fileName, MAX_RAM_SIZE); break; default: break; } }
C
#include <assert.h> #include <math.h> #include "quaternion_exp.h" VOID_t quaternion_exp(const Quaternion_t* q, Quaternion_t* output) { assert(output != NULL); Real64_t s; Real64_t e; Real64_t fq1Squared = q->fy * q->fy; Real64_t fq2Squared = q->fz * q->fz; Real64_t fq3Squared = q->dt * q->dt; Real64_t fVectSquaredNorm = fq1Squared + fq2Squared + fq3Squared; Real64_t fVectNorm = sqrt(fVectSquaredNorm); if (fVectNorm > _QUATERNION_EPS) { s = sin(fVectNorm) / fVectNorm; e = exp(q->dx); quaternion_set(e * cos(fVectNorm), e * s * q->fy, e * s * q->fz, e * s * q->dt, output); } else { quaternion_set(exp(q->dx), 0, 0, 0, output); } return; }
C
#include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <mpi.h> #include "gui.h" #include "nbody.h" #define STRINGIFY1(x) #x #define STRINGIFY(x) STRINGIFY1(x) #if !defined(BUILD_PAR) && !defined(BUILD_SEQ) && !defined(BUILD_UNIT) #define BUILD_PAR #endif #define DEFAULT_LEAVES 31 #define DEFAULT_GUI false #define DEFAULT_STEPS 1 #define DEFAULT_FILE_REF "output_unit_ref.svg" #ifdef BUILD_PAR #define DEFAULT_POINTS 100 #define DEFAULT_FILE "output_par.svg" #define DEFAULT_TIMESTEP 0.01f #elif defined(BUILD_SEQ) #define DEFAULT_POINTS 100 #define DEFAULT_FILE "output_seq.svg" #define DEFAULT_TIMESTEP 0.01f #elif defined(BUILD_UNIT) #define DEFAULT_POINTS 20 #define DEFAULT_FILE "output_unit_out.svg" #define DEFAULT_TIMESTEP 1.f #endif void simulate_seq(int steps, int num_leaves, Node* root); void simulate_par(int steps, int num_leaves, Node* root); double time_diff(struct timespec* first, struct timespec* second) { struct timespec tmp; struct timespec *tmp_ptr; if (first->tv_sec > second->tv_sec || (first->tv_sec == second->tv_sec && first->tv_nsec > second->tv_nsec)) { tmp_ptr = first; first = second; second = tmp_ptr; } tmp.tv_sec = second->tv_sec - first->tv_sec; tmp.tv_nsec = second->tv_nsec - first->tv_nsec; if (tmp.tv_nsec < 0) { tmp.tv_sec -= 1; tmp.tv_nsec += 1000000000; } return tmp.tv_sec + tmp.tv_nsec / 1000000000.0; } int main(int argc, char **argv) { int num_points = DEFAULT_POINTS; int num_leaves = DEFAULT_LEAVES; char file_name[256] = DEFAULT_FILE; char file_name_ref[256] = DEFAULT_FILE_REF; bool show_gui = DEFAULT_GUI; int num_steps = DEFAULT_STEPS; float timestep = DEFAULT_TIMESTEP; int rank, num_procs; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); #ifdef BUILD_PAR num_leaves = num_procs; #endif int c; while ((c = getopt(argc, argv, "p:l:f:t:gs:")) != -1) { switch (c) { case 'p': if (sscanf(optarg, "%d", &num_points) != 1) goto error; break; case 's': if (sscanf(optarg, "%d", &num_steps) != 1) goto error; break; case 't': if (sscanf(optarg, "%f", &timestep) != 1) goto error; break; case 'l': if (sscanf(optarg, "%d", &num_leaves) != 1) goto error; if (num_leaves != num_procs) { num_leaves = num_procs; fprintf(stderr, "Warning: -l option ignored, numer of leaves is the same as the number of processes\n"); } break; case 'f': strncpy(file_name, optarg, sizeof(file_name)-1); file_name[sizeof(file_name)-1] = 0; break; case 'r': strncpy(file_name_ref, optarg, sizeof(file_name_ref)-1); file_name[sizeof(file_name_ref)-1] = 0; break; case 'g': show_gui = true; break; case '?': error: fprintf(stderr, "Usage:\n %s [-p <num_points>] [-l <num_leaves>] [-s <num_steps>] [-f <file>] [-r <file_ref>] [-g]\n" " -p <num_points> [default: " STRINGIFY(DEFAULT_POINTS) "]\n" " Initialise with (approximately) this number of points per leaf node.\n" " -l <num_leaves> [default: " STRINGIFY(DEFAULT_LEAVES) "]\n" " Generate this many leaf nodes. Must be 1+3*n for some n. Only used for sequential execution!\n" " -t <timestep> [default: " STRINGIFY(DEFAULT_TIMESTEP) "]\n" " How much time a single step of the simulation simulates.\n" " -s <num_steps> [default: " STRINGIFY(DEFAULT_STEPS) "]\n" " How many steps of the simulation to perform.\n" " -f <file> [default: " DEFAULT_FILE "]\n" " Name of the output SVG file.\n" " -r <file_ref> [default: " DEFAULT_FILE_REF "]\n" " Name of the output SVG file for the reference code.\n" " -g [default: off]\n" " Whether to show the animation in a window as it runs.\n", argv[0]); MPI_Finalize(); exit(138); } } global_timestep = timestep; if (show_gui) { num_steps = 1 << 30; } if (rank != 0) { show_gui = false; #ifdef BUILD_SEQ fprintf(stderr, "WARNING: Trying to run sequential code with multiple processes\n"); #endif } global_show_gui = show_gui; if (show_gui) { gui_create_window(1, argv); } #ifdef BUILD_PAR struct timespec begin, end; Node* root = node_create(num_leaves, num_points); clock_gettime(CLOCK_MONOTONIC, &begin); simulate_par(num_steps, num_leaves, root); clock_gettime(CLOCK_MONOTONIC, &end); if (rank == 0) { printf("Time: %lf seconds\n", time_diff(&begin, &end)); node_draw_svg(root, file_name); } #elif defined(BUILD_SEQ) struct timespec begin, end; Node* root = node_create(num_leaves, num_points); clock_gettime(CLOCK_MONOTONIC, &begin); simulate_seq(num_steps, num_leaves, root); clock_gettime(CLOCK_MONOTONIC, &end); printf("Time: %lf seconds\n", time_diff(&begin, &end)); node_draw_svg(root, file_name); #elif defined(BUILD_UNIT) Node* root = node_create(num_leaves, num_points); simulate_par(num_steps, num_leaves, root); if (rank == 0) { node_draw_svg(root, file_name); Node* root_ref = node_create(num_leaves, num_points); simulate_seq(num_steps, num_leaves, root_ref); node_draw_svg(root_ref, file_name_ref); node_check_almost_equal(root, root_ref, 1e-8); } #endif MPI_Finalize(); }
C
//1. eloforditoi direktiva #include <stdio.h> #include <stdlib.h> //2. fv. prototipus //void arfolyamBekerese(double *arfolyamok, int meret); void arfolyamBekerese(double *, int); //void arfolyamBekerese(double arfolyamok[], int meret); //void arfolyamokKiirasa(double *arfolyamok, int meret); void arfolyamokKiirasa(double arfolyamok[], int meret); //3. main int main() { const int meret = 2; double arfolyamok[meret]; printf("EURO arfolyamok\n"); //arfolyamBekerese(arfolyamok, meret); arfolyamBekerese(&arfolyamok[0], meret); arfolyamokKiirasa(arfolyamok, meret); return 0; } //4. fv. definiciok void arfolyamBekerese(double *arfolyamok, int meret) { int joEAzAdat; int i; for(i = 0; i < meret; i++) { do { joEAzAdat = 1; printf("%d. arfolyam: ", i+1); if(scanf("%lf", &arfolyamok[i]) != 1 || arfolyamok[i] < 340 || arfolyamok[i] > 370) { printf("rossz adat\n"); joEAzAdat = 0; } while(getchar() != '\n'); } while(!joEAzAdat); } return; } void arfolyamokKiirasa(double arfolyamok[], int meret) { int i; for(i = 0; i < meret; i++) { printf("%2d. ertek: %.2lf\n", i + 1, arfolyamok[i]); } return; }
C
#include<stdio.h> #include<ctype.h> void main(){ int len = 0; char ch; printf("Enter a sentence:"); while((ch = tolower(getchar())) != '\n'){ if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){ len++; } } printf("Your sentence contains %d vowels.\n", len); }
C
//3.1 Circular Queue, front->enqueue, rear->dequeue, simple array, compromising one place (0th index at start) #include<stdio.h> #include<stdlib.h> #define SIZE 5 int rear=0,front=0; void enqueue(int a[],int e) { if((rear+1)%SIZE==front) { printf("Queue Full\n"); } else { rear = (rear+1)%SIZE; a[rear]=e; printf("%d Enqueued\n",e); } } void dequeue(int a[]) { if(rear==front) { printf("Queue Empty\n"); } else { front = (front+1)%SIZE; printf("%d Dequeued\n",a[front]); } } void display(int a[]) { int i,flag; printf("Elements in the Queue : "); flag = (rear+1)%SIZE; i=front+1; while(i!=flag) { printf("%d ",a[i]); i=(i+1)%SIZE; } printf("\n"); } int main() { int a[SIZE],i,n,e; do { printf("Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit :\n "); scanf("%d",&i); switch(i) { case 1:printf("Enter element : "); scanf("%d",&e); enqueue(a,e); break; case 2:dequeue(a); break; case 3:display(a); break; case 4: exit(0); default: printf("Wrong Input -_- ! Please Enter the Correct Choice \n"); break; } }while(1); return 0; } /* sayali@sayali:~/Desktop/ds$ cc cirQfr.c sayali@sayali:~/Desktop/ds$ ./a.out Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 12 12 Enqueued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 3 3 Enqueued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 4 4 Enqueued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 5 5 Enqueued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 6 Queue Full Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 3 Elements in the Queue : 12 3 4 5 Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 12 Dequeued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 3 Elements in the Queue : 3 4 5 Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 3 Dequeued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 3 Elements in the Queue : 4 5 Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 1 Enter element : 567 567 Enqueued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 3 Elements in the Queue : 4 5 567 Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 4 Dequeued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 5 Dequeued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 567 Dequeued Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 2 Queue Empty Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 3 Elements in the Queue : Enter choice 1:Enqueue 2:Dequeue 3:Display 4:Exit : 4 sayali@sayali:~/Desktop/ds$ */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* float_flag.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: japarbs <japarbs@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/28 20:54:39 by japarbs #+# #+# */ /* Updated: 2019/11/19 20:51:50 by japarbs ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" static long double get_nb(t_format *fmt) { long double va_float; va_float = 0; if (fmt->varg_size == 0) va_float = va_arg(fmt->valst, double); else if (fmt->varg_size == 'l') va_float = va_arg(fmt->valst, double); else if (fmt->varg_size == 'L') va_float = va_arg(fmt->valst, long double); return (va_float); } /* ** Places signs and padding in the proper position with ** consideration for alignment. */ static void handle_flags(t_format *fmt, \ char *res, long long va_float) { int signpos; if ((fmt->neg_flag && va_float < 0) || fmt->space_flag || fmt->pos_flag) fmt->width++; if (!fmt->neg_flag) signpos = fmt->width - fmt->precision; else signpos = 0; if ((fmt->pos_flag || fmt->space_flag) || va_float < 0) { if (va_float < 0) res[signpos] = '-'; else if (fmt->pos_flag && va_float >= 0) res[signpos] = '+'; else if (fmt->space_flag && va_float >= 0) res[signpos] = ' '; } } /* ** Does the math to find the size of the string to allocate. ** Ensures that width is as wide or wider than the len of the number. ** Checks for needed additional space for pos and space flags. ** Creates the padding string with the proper set of chars with NULL. */ static char *format_float(t_format *fmt, long long va_float, int len) { char *res; fmt->width = (fmt->width < len) ? len : fmt->width; fmt->precision = len; if ((fmt->pos_flag || fmt->space_flag) || va_float < 0) { ++fmt->precision; if (fmt->width == len) ++fmt->width; } if (fmt->zero_flag && !fmt->pre_flag) fmt->precision = fmt->width; if ((fmt->neg_flag && va_float < 0) || fmt->space_flag || fmt->pos_flag) fmt->width--; if ((fmt->width - len) >= 1) res = (char *)malloc(fmt->width - len); else return (ft_strnew(0)); if (res && fmt->zero_flag && !fmt->pre_flag) ft_memset(res, '0', (fmt->width - len) + 1); else if (res) ft_memset(res, ' ', (fmt->width - len) + 1); if (res) res[fmt->width - len] = '\0'; return (res); } static char *handle_float(t_format *fmt, long double va_float) { char *res; char *ftoares; if (fmt->pos_flag && fmt->space_flag) fmt->space_flag = 0; if (fmt->neg_flag && fmt->zero_flag) fmt->zero_flag = 0; ftoares = (va_float < 0) ? \ ft_ftoa(-va_float, fmt->precision) : ft_ftoa(va_float, fmt->precision); res = ftoares; return (res); } /* ** The function that handles int flag conversion. ** Logic: ** Grabs varg with proper byte sizing. ** Finds len with Precision consideration if 0. ** Uses itoa for int conversion. If neg it will treated as a positive. ** Allocs int padding with flag consideration. ** Joins the two strings together with alignment. ** Handles placement of flags and sign placement. ** Free and return res to be joined with the buffer. */ char *flag_float(t_format *fmt) { char *res; char *floatres; char *formatres; long double va_float; int len; va_float = get_nb(fmt); len = ft_intlen((long long)va_float) + fmt->precision; len += (fmt->precision) ? 1 : 0; floatres = handle_float(fmt, va_float); if ((fmt->neg_flag && va_float < 0) || fmt->space_flag || fmt->pos_flag) { res = ft_strjoin("0", floatres); ft_strdel(&floatres); floatres = res; } formatres = format_float(fmt, va_float, len); res = (!fmt->neg_flag) ? \ ft_strjoin(formatres, floatres) : ft_strjoin(floatres, formatres); ft_strdel(&formatres); ft_strdel(&floatres); handle_flags(fmt, res, va_float); return (res); }
C
#include "alias_map.h" #include "config.h" #include "debug.h" #if NODE == TBC #define BITWORD 8 #define SHIFT 3 #define MASK 0x07 static u8t alias_map[1 + TBIM_NUM/BITWORD]; static u8t first_free=1; static u8t test(u8t i) { return alias_map[i >> SHIFT] & (1 << (i & MASK)); } /******************************************************** * עﲻǷ䲻 ********************************************************/ u8t alloc_alias_map() { u8t r; u8t i; r=first_free; alias_map[r >> SHIFT] |= (1 << (r & MASK)); for(i=first_free+1;i<=TBIM_NUM;i++) { if(!test(i)) { first_free=i; break; } } // SSNP_DEBUG_PRINT("alloc_alias_map():alloc alias in alias map.\r\n"); // printf("alloc_alias_map():the alloc alias is %d.\r\n",r); return r; } void del_alias_map(u8t alias) { if(first_free >= alias) first_free=alias; alias_map[alias >> SHIFT] &= ~(1 << (alias & MASK)); } #endif
C
#include <stdint.h> #include <math.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "apcilib.h" #define DEVICEPATH "/dev/apci/pcie_da16_6_0" #define BAR_REGISTER 2 int apci; //------------------------------------------------------------------------------------ int main (int argc, char **argv) { uint32_t Version = 0; apci_read32(apci, 1, BAR_REGISTER, 0x68, &Version); printf("\nPCIe-DA16-6 Family ADC Sample 0\n"); apci = -1; if (argc > 1) { apci = open(argv[1], O_RDONLY); // open device file from command line if (apci < 0) printf("Couldn't open device file on command line [%s]: do you need sudo? /dev/apci? \n", argv[1]); } if (apci < 0) // if the command line didn't work, or if they didn't pass a parameter { apci = open(DEVICEPATH, O_RDONLY); if (apci < 0) { printf("Device file %s could not be opened. Please ensure the APCI driver module is loaded or try sudo?.\n", DEVICEPATH); } } int chan; __u8 data_ignore; apci_write16(apci, 0, BAR_REGISTER, 0x00, 0x8000); // set DAC0 to midscale apci_write16(apci, 0, BAR_REGISTER, 0x02, 0x8000); apci_write16(apci, 0, BAR_REGISTER, 0x04, 0x8000); apci_write16(apci, 0, BAR_REGISTER, 0x06, 0x8000); apci_write16(apci, 0, BAR_REGISTER, 0x08, 0x8000); apci_write16(apci, 0, BAR_REGISTER, 0x0A, 0x8000); // set DAC5 to midscale apci_read8(apci, 0, BAR_REGISTER, 0x0F, &data_ignore); printf("Demonstrating Async (non-simultaneous) DAC updates"); apci_read8(apci, 0, BAR_REGISTER, 0x0A, &data_ignore); // take DACs out of simultaneous mode for (int counts = 0; counts < 0xFFFF; counts += 0x1000) { for (chan = 0; chan < 6; chan++) { apci_write16(apci, 0, BAR_REGISTER, chan * 2, counts); } printf("wrote [%04x] to DACs\n", counts); sleep(2); } printf("Demonstrating Simultaneous DAC updates"); apci_read8(apci, 0, BAR_REGISTER, 0x00, &data_ignore); // put DACs into simultaneous mode without updating outputs for (int counts = 0; counts < 0xFFFF; counts += 0x1000) { for (chan = 0; chan < 6; chan++) { apci_write16(apci, 0, BAR_REGISTER, chan * 2, counts); } printf("wrote [%04x] to DACs without updating outputs; now updating all at once\n", counts); apci_read8(apci, 0, BAR_REGISTER, 0x08, &data_ignore); // update all outputs at once and leave DACs in simultaneous mode sleep(2); } printf("\nSample Done.\n"); // never prints due to CTRL-C abort }
C
#include <stdio.h> #include <string.h> int vis[10]; int valid(int x) { int y = x % 10; int z = x / 10; return x >= 10 && x < 100 && !(y == z || vis[y] || vis[z]); } int use(int x) { return valid(x) && (vis[x % 10] = vis[x / 10] = 1); } void unuse(int x) { vis[x % 10] = vis[x / 10] = 0; } void reset() { memset(vis, 0, sizeof(vis)); vis[1] = 1; } int main() { int ab, cd, ef, gh; reset(); for (ab = 20; ab < 100; ab++) if (use(ab)) { for (cd = 20; cd < ab; cd++) if (use(cd)) { ef = ab - cd; gh = 111 - ef; if (use(ef)) { if (use(gh)) { printf("%d - %d = %d, %d + %d = 111\n", ab, cd, ef, ef, gh); unuse(gh); } unuse(ef); } unuse(cd); } unuse(ab); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int n; srand(time(0)); n = rand() % 100 + 1;// Generate a random number between 1 to 100 printf("The number is %d", n); scanf("%d", &n); // keep running until number is guesssed return 0; }
C
#include<stdio.h> int main(void){ char c[100]; int i=0,x=0,d=0; printf("ingrese el numero \n"); gets(c); while(c[i]!='\0'){ if (c[i]=='0'||c[i]=='1'||c[i]=='2'||c[i]=='3'||c[i]=='4'||c[i]=='5'||c[i]=='6'||c[i]=='7'||c[i]=='8'||c[i]=='9') x++; else d++; i++; } printf("la cantidad de digitos es %d\n",x); return 0; }
C
#include<stdio.h> int swap(int *p, int *q) { return 0; } int main() { int a=10,b=20; int *temp,*p,*q; p=&a; q=&b; temp = p; p=q; q=temp; printf("a=%d, b=%d\n",a,b); printf("*p=%d, *q=%d\n",*p,*q); return 0; }
C
#include<stdio.h> int main() { float s1,s2,s3; printf(" Enter 3 sides of the Triangle : \n"); scanf("%f%f%f",&s1,&s2,&s3); if( s1<=s2+s3 || s2<=s1+s3 || s3<=s1+s2 ) { printf("\nTriangle is valid."); } else { printf("\nTriangle is not valid."); } return 0; }
C
// this code sets up counter1 for an 4kHz, 10bit, Phase Corrected PWM // @ 16Mhz Clock #include <avr/io.h> #include <util/delay.h> int main(void){ DDRC |= 0xEF; // PC4 is now an input, everything else is an output DDRB |= 0x03; // PB1 is now an output PORTC |= (1<<PC0) | (1<<PC1) | (1<<PC2); // sets HIGH on PC0, PC1, PC2 - high frequency, rgb PORTB |= 0x01; OCR1A = 0x0093; //DUTY //Micro 92=90Lewo 75=lewo45(2ms), 55=srodek(1,5ms), 37=prawo(1ms), 22=prawo90 //Std 93=90Lewo, 74=lewo45(2ms), 54=srodek(1,5ms), 36=prawo45(1ms), 21=prawo90 ICR1 = 0x04E0; //TOP //11 1111 1111 TCCR1A |= (1 << COM1A1); // set none-inverting mode TCCR1A |= (1 << WGM11); // set 10bit phase corrected PWM Mode TCCR1B |= (1 << WGM13) | (1 << CS11) | (1 <<CS10); // set prescaler to 64 and starts PWM while (1) { if(PINC & 0x08){ OCR1A = 0x0055; } } }
C
#include<stdio.h> #include "intstack.h" int main(){ IntStack s; if(Initialize(&s, 64) == -1){ puts("failed to excute stack."); return 1; } while(1){ int menu,x; printf("data space: %d/%d\n",Size(&s),Capacity(&s)); printf("(1)Push (2)Pop (3)Peek (4)Print (0)Exit: "); scanf("%d",&menu); if(menu == 0) { break; } switch(menu) { case 1: printf("data: "); scanf("%d",&x); if(Push(&s,x) == -1) { puts("\aerror : failed to Push."); } break; case 2: if(Pop(&s,&x) == -1) printf("\aError : failed to Pop"); else printf("popped data is %d.\n",x); break; case 3: if(Peek(&s,&x) == -1) printf("\aError : failed to Peek %d.\n",x); else printf("Peeked data is %d.\n",x); break; case 4: Print(&s); break; } } Terminate(&s); return 0; }
C
#include <stdio.h> /* Return 1 when any odd bit of x equals 1; 0 otherwise Assume w=32 */ int any_odd_one(unsigned x) { return !!(0x55555555 & x); } /* int main(void) { for(int i = 0; i < 64; i++) printf("%d %d\n", i, any_odd_one(i)); } */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: scornaz <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/17 17:39:36 by scornaz #+# #+# */ /* Updated: 2018/04/14 11:48:28 by scornaz ### ########.fr */ /* */ /* ************************************************************************** */ #include "printf.h" void print_arg(t_num *num, t_array *buffer) { if (num->left && num->padding) print_padding(num->padding, num->zero ? '0' : ' ', buffer); if (num->alternate) print_alternate(num, buffer); if (num->sign || num->space) print_sign(num->sign, num->type, num->space, buffer); if (num->precision) print_padding(num->precision, '0', buffer); if (num->str_len) array_add(buffer, num->value, num->str_len); if (num->padding && !num->left) print_padding(num->padding, ' ', buffer); } void print_alternate(t_num *num, t_array *buffer) { if (num->type == 'X') array_add(buffer, "0X", 2); else if (num->type == 'x') array_add(buffer, "0x", 2); else if (num->type == 'p') array_add(buffer, "0x", 2); } void print_padding(size_t count, char with, t_array *buffer) { while (count) { array_add(buffer, &with, 1); --count; } } void print_sign(int sign, char type, int space, t_array *buffer) { (void)type; if (sign == -1) array_add(buffer, "-", 1); else if (sign == 1) array_add(buffer, "+", 1); else if (space) array_add(buffer, " ", 1); }
C
#include <stdio.h> #include <stdlib.h> #include <tagfs.h> #include <errno.h> int main(int argc, char *argv[]) { char buf[255]; int result; result = getcwt(buf, 255); if(result == -1) { switch(errno) { case ENOSYS: printf("Function has not been implemented. Did you insert the tagfs module?\n"); break; default: printf("Function failed with error #%d\n", errno); break; } exit(1); } printf("%s\n", buf); }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<string.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 #define MAXNUM 100 typedef char SElemType ; typedef enum{ ERROR, OK, OVERFLOW }Status; typedef struct { SElemType *base; SElemType *top; int stacksize; }SqStack; //create a new stack Status InitStack(SqStack *S) { //need free S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!S->base) { return OVERFLOW;//fail to allocate memory } S->top = S->base; S->stacksize = STACK_INIT_SIZE; return OK; }//end of InitStack Status Push(SqStack *S, SElemType e)// { //if(S->top - S->base >= S->stacksize) { // //re-alloc // return OVERFLOW; //}//黄大大 if(S->top - S->base >= S->stacksize) { S->base = (SElemType *)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(SElemType)); if(!S->base) { return OVERFLOW; } S->top = S->base + S->stacksize; S->stacksize += STACKINCREMENT; }//课本 *S->top++ = e; return OK; }//end of Push Status Pop(SqStack *S, SElemType e) { if(S->top == S->base) { return ERROR; } e = * --S->top;//待检测 return OK; }//end of Pop //判断空栈 Status StackEmpty(SqStack *S) { if(S->base == S->top) { return OK; } else{ return ERROR; } }//end of StackEmpty //获取栈顶元素的函数 Status GetTop(SqStack *S, SElemType *e) { if(S->top == S->base){ return ERROR; } *e = *(S->top-1); return OK; } Status matching(SqStack *S, char *c) { int state = 1; int i = 0; SElemType e;// //e = *(S->top); while ( c[i]!='\0' && state ) { switch(c[i]) { case '(': { Push(S, c[i]); i++; break; } case ')': { GetTop(S,&e); if(! StackEmpty(S) && e == '(') { Pop(S,e); //printf("The nearest ( has been matched."); } else { state = 0; } i++; break; } case '{': { Push(S, c[i]); i++; break; } case '}': { GetTop(S,&e); if(! StackEmpty(S) && e == '{') { Pop(S,e); //printf("The nearest { has been matched."); } else { state = 0; } i++; break; } case '[': { Push(S, c[i]); i++; break; } case ']': { GetTop(S,&e); if(! StackEmpty(S) && e == '[') { Pop(S,e); //printf("The nearest [ has been matched."); } else { state = 0; } i++; break; } } } if ( StackEmpty(S) && state) { return OK; } else { return ERROR; } } int main() { SqStack S; char c[MAXNUM]; int flag=0; //char enter; InitStack(&S); printf("Input a group of brackets as you like!\n"); scanf("%s",c); flag = matching(&S,c); //scanf("%c",&enter); if(matching(&S,c)) printf("Matching succeed!"); else printf("Matching fail!"); return 0; } //{[[()]]}
C
#include <stdio.h> /* Standard Library of Input and Output */ #include <complex.h> /* Standard Library of Complex Numbers */ #include <locale.h> int main() { setlocale(LC_ALL, ""); double complex z1 = 1.0 + 3.0 * I; double complex z2 = 1.0 - 4.0 * I; printf("\t\tTrabalhando com nmeros complexos:"); printf("\n\nValores iniciais: \n\t Z1 = %.2f %+.2fi \n\t Z2 = %.2f %+.2fi", creal(z1), cimag(z1), creal(z2), cimag(z2)); double complex sum = z1 + z2; printf("\n\nA soma: Z1 + Z2 = %.2f %+.2fi", creal(sum), cimag(sum)); double complex difference = z1 - z2; printf("\nA subtrao: Z1 - Z2 = %.2f %+.2fi", creal(difference), cimag(difference)); double complex product = z1 * z2; printf("\nO produto: Z1 x Z2 = %.2f %+.2fi", creal(product), cimag(product)); double complex quotient = z1 / z2; printf("\nA diviso: Z1 / Z2 = %.2f %+.2fi", creal(quotient), cimag(quotient)); double complex conjugate = conj(z1); printf("\nO conjugado de Z1 = %.2f %+.2fi", creal(conjugate), cimag(conjugate)); return 0; }
C
// ********************************************************************************* // ***** Christopher Crews - February 2012 ******** // ***** Program Name: main.c ******** // ***** main - initalizes all the hardware and veriables. it sets up ******** // ***** and starts all the threads. this c file also holds the Main_Thread.***** // ********************************************************************************* // ***** Formated for Monospaced Type ******** #ifdef _GUM // ********************************************************************************* // ***** Include Statments ******** #include "main.h" // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** Global Variables ******** int v_i2c_device, v_uart_device; // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** Main ******** // ********************************************************************************* int main (int argc, char **argv) { // ********************************************************************************* // ***** Variable Declaratins ******** int v_returnvalue; pthread_t main_thread_ID; pthread_t gps_thread_ID; pthread_t alt_thread_ID; pthread_t humidity_thread_ID; pthread_t temperature_thread_ID; pthread_t uv_thread_ID; pthread_t solar_thread_ID; pthread_t hb_thread_ID; // ---------- END ---------------------------------------------------------------- // Set system CPU frequency system("cpufreq-set -f 600MHz"); // ********************************************************************************* // ***** Initalize GPIO pins ******** system("echo 147 > /sys/class/gpio/export"); system("echo out > /sys/class/gpio/gpio147/direction"); system("echo 0 > /sys/class/gpio/gpio147/value"); // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** OPEN I2C PORT ******** v_i2c_device = i2c_open(); i2c_print_messages(OFF); if (v_i2c_device == 0) { printf("error on opening i2c port...exiting program.\n\n"); return 0; } // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** Save I2C device ID in all files that use I2C ******** save_alt_i2c_device_id(v_i2c_device); save_gps_i2c_device_id(v_i2c_device); save_temperature_i2c_device_id(v_i2c_device); save_humidity_i2c_device_id(v_i2c_device); save_uv_i2c_device_id(v_i2c_device); save_solar_i2c_device_id(v_i2c_device); // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** OPEN UART PORT ******** v_uart_device = uart_open(); uart_print_messages(OFF); if (v_uart_device == 0) { printf("error on opening uart port...exiting program.\n\n"); return 0; } // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** create threads ******** v_returnvalue = pthread_create(&main_thread_ID, NULL, main_thread, NULL); v_returnvalue = pthread_create(&gps_thread_ID, NULL, GPS_Thread, NULL); v_returnvalue = pthread_create(&alt_thread_ID, NULL, Alt_Thread, NULL); v_returnvalue = pthread_create(&humidity_thread_ID, NULL, Humidity_Thread, NULL); v_returnvalue = pthread_create(&temperature_thread_ID, NULL, Temperature_Thread, NULL); v_returnvalue = pthread_create(&uv_thread_ID, NULL, UV_Thread, NULL); v_returnvalue = pthread_create(&solar_thread_ID, NULL, Solar_Thread, NULL); v_returnvalue = pthread_create(&hb_thread_ID, NULL, Hb_Thread, NULL); // ---------- END ---------------------------------------------------------------- // ********************************************************************************* // ***** Closing Code ******** pthread_join(main_thread_ID, NULL); // ---------- END ---------------------------------------------------------------- return 0; } // ---------- END MAIN ------------------------------------------------------------ // ********************************************************************************* // ***** Function Name: main_thread ******** // ***** Reads all data output from all the other threads ******** // ********************************************************************************* void *main_thread(void *ptr) { // ********************************************************************************* // ***** Veriable Declaratins ******** gps_struct strc_gps_data; alt_struct strc_alt_data; humidity_struct strc_humidity_data; temperature_struct strc_temperature_data; uv_struct strc_uv_data; solar_struct strc_solar_data; printall = 0; int printall_solar = 0; printall_gps = 0; FILE *pFile; SDL_Event Event; struct timeval start; struct timeval start2; struct timeval start3; struct timeval end; struct timeval end2; struct timeval end3; int timediff; int timediff2; int timediff3; int time_count = 0; unsigned char v_string[2000], v_temp_string[2000]; int ret; v_record_data = 0; v_tx_gps = 0; v_landed = 0; v_tx_data = 0; int v_wifi_off = 1; // ---------- END ---------------------------------------------------------------- SDL_Init(SDL_INIT_EVERYTHING); gettimeofday(&start,NULL); gettimeofday(&start2,NULL); gettimeofday(&start3,NULL); // ********************************************************************************* // ***** MAIN LOOP ******** for(;;) { usleep(100000); if(v_record_data == 1) { gettimeofday(&end,NULL); timediff = (end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec); if(timediff >= 500000) { pFile = fopen("//home/root/Programs/results","a"); fprintf(pFile,"$CHDAT,%d/%d/20%d,",strc_gps_data.day,strc_gps_data.month,strc_gps_data.year); fprintf(pFile,"%d:%d:%d,",strc_gps_data.hours,strc_gps_data.minutes,strc_gps_data.seconds); fprintf(pFile,"%f,",strc_gps_data.v_latitude); fprintf(pFile,"%f,",strc_gps_data.v_longitude); fprintf(pFile,"%f,",strc_solar_data.v_Solar); fprintf(pFile,"%f,",strc_uv_data.v_UV); fprintf(pFile,"%f,",strc_humidity_data.v_Humidity); fprintf(pFile,"%f,",strc_alt_data.v_Pressure); fprintf(pFile,"%f\n",strc_temperature_data.v_Temperature); fclose(pFile); gettimeofday(&start,NULL); } } if(v_tx_gps == 1) { gettimeofday(&end2,NULL); timediff2 = end2.tv_sec - start2.tv_sec; if(timediff2 >= 5) { sprintf(v_string,"$CHGPS,%07f,%07f,%02d:%02d:%02d,%d,%d,%d\n",strc_gps_data.latitude, strc_gps_data.longitude, strc_gps_data.hours,strc_gps_data.minutes,strc_gps_data.seconds, strc_gps_data.fix_type,strc_gps_data.num_sats,strc_gps_data.data_valid); ret = uart_write(v_uart_device,v_string); gettimeofday(&start2,NULL); } } if(v_wifi_off == 1) { gettimeofday(&end3,NULL); timediff3 = end3.tv_sec - start3.tv_sec; if(timediff3 >= 60) { system("echo 0 > /sys/class/gpio/gpio16/value"); v_wifi_off = 0; } } if(v_tx_data == 1) { pFile = fopen("//home/root/Programs/results","r"); while((fscanf(pFile,"%s",v_temp_string)) != EOF) { sprintf(v_string,"%s\n",v_temp_string); ret = uart_write(v_uart_device,v_string); usleep(60000); } fclose(pFile); v_tx_data = 0; } if(new_gps_data == 1) { Get_GPS_Data(&strc_gps_data); if(printall_gps) { printf("\nLat = %.06f, Long = %.06f\n",strc_gps_data.latitude,strc_gps_data.longitude); printf("Altitude = %.02f m, Speed = %.02f km/h\n",strc_gps_data.altitude,strc_gps_data.ground_speed); printf("Course over Ground = %.02f deg.\n",strc_gps_data.ground_course); printf("Number of Satellites = %d\n", strc_gps_data.num_sats); printf("Date: %d/%d/%d \n",strc_gps_data.day,strc_gps_data.month,strc_gps_data.year); printf("UTC Time: %d:%d:%d \n",strc_gps_data.hours,strc_gps_data.minutes,strc_gps_data.seconds); printf("Fix Type: %d\n\n", strc_gps_data.fix_type); } } if(new_alt_data == 1) { Get_Alt_Data(&strc_alt_data); if(printall) { printf("Barometric Pressure = %f mbars\n",strc_alt_data.v_Pressure); printf("Altitude = %f ft\n",strc_alt_data.v_Altitude); } } if(new_humidity_data == 1) { Get_Humidity_Data(&strc_humidity_data); if(printall) { printf("Relative Humidity = %f %% \n",strc_humidity_data.v_Humidity); } } if(new_temperature_data == 1) { Get_Temperature_Data(&strc_temperature_data); if(printall) { printf("Temperature = %f degrees C\n",strc_temperature_data.v_Temperature); } v_temperature_c = strc_temperature_data.v_Temperature; } if(new_uv_data == 1) { Get_UV_Data(&strc_uv_data); if(printall) { printf("UV = %f\n",strc_uv_data.v_UV); } } if(new_solar_data == 1) { Get_Solar_Data(&strc_solar_data); if(printall_solar) { printf("Solar = %f\n",strc_solar_data.v_Solar); } } if(SDL_PollEvent(&Event)!=0) { if(Event.type==SDL_QUIT) { break; } } } // ---------- END ---------------------------------------------------------------- i2c_close(v_i2c_device); uart_close(v_uart_device); SDL_Quit(); exit(0); } // ---------- END MAIN_THREAD ---------------------------------------------------- #endif /* _GUM */
C
#include "holberton.h" /** * main - make change with infinite amounts of 25, 10, 5, 2 and 1. * @argc: The number of arguments. * @argv: The argument vector. * * Description: makes change given an infinite ammount of coins of 25, 10, 5, 2 * and 1. Implemented with a greedy algorithm. * Return: 1 if number of arguments isn't 2 (program name and change to make), * 0 otherwise. */ int main(int argc, char *argv[]) { int coins[] = {25, 10, 5, 2, 1}; int cents, index, remainder; cents = index = remainder = 0; if (argc != 2) { printf("Error\n"); return (1); } remainder = atoi(argv[1]); if (remainder <= 0) { printf("0\n"); return (0); } while (remainder > 0 && index < 5) { cents += remainder / coins[index]; remainder = remainder % coins[index]; index++; } printf("%d\n", cents); return (0); }
C
void merge_seq(int *A, int n1, int *B, int n2, int* C); void mergesort_seq(int *A, int start, int end, int* aux); void merge_seq(int *A, int n1, int *B, int n2, int* C){ int i = 0; int j = 0; while(i < n1 && j < n2){ if(A[i] <= B[j]){ C[i+j] = A[i]; i++; }else{ // A[i] > B[j] C[i+j] = B[j]; j++; } } while(i < n1){ C[i+j] = A[i]; i++; } while(j < n2){ C[i+j] = B[j]; j++; } } void mergesort_seq(int *A, int start, int end, int* aux){ if(start >= end) return; int mid = start + (end - start) / 2; mergesort_seq(A, start, mid, aux); mergesort_seq(A, mid + 1, end, aux); merge_seq(A+start, mid - start + 1, A + mid + 1, end - mid, aux); for(int i = start; i <= end; i++){ // cout << result[i - start] << ", "; A[i] = aux[i - start]; } }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int i, carry, tmp; char *init, *current; init = (char*) malloc(10000001); current = (char*) malloc(10000001); scanf("%s %s", init, current); carry = 1; for (i = 0; current[i] != 0; i++) { tmp = (current[i] == init[i] ? 0 : 1) + carry; carry = tmp > 1; current[i] = (tmp == 1 ? '1' : '0') == init[i] ? '0' : '1'; } printf("%s\n", current); free(init); free(current); return 0; }
C
/* The Robot Arm Manager receives requests to grasp objects at specific points in space (x, y, z) and time (t). It first computes an arm trajectory via the and produces a set of nSteps actions (up to 100). Each action is composed of a set of commands to each of the seven servos. If the goal is achievable, then Robot Arm Manager calls executeStep() function nSteps times to step through the computed action sequence. At each step, any command can return an error code (non-zero) which causes the graspAt() function to abort with an error code. Note that the computation of the arm path via the sum of the movements of the various arm joints is a complex exercise in geometry which, while interesting, is outside the scope of concern for this book. */ #include "robot_arm_manager.h" #include <stdio.h> #include <stdlib.h> #define NUM_ROTATINT_JOINT (4) #define NUM_SLIDING_JOINT (3) #define R_MOTOR_1 (0) #define R_MOTOR_2 (1) #define R_MOTOR_3 (2) #define R_MOTOR_4 (3) #define S_MOTOR_1 (0) #define S_MOTOR_2 (1) #define S_MOTOR_3 (2) int main(int argc, char const *argv[]) { /*Create and config motor arm */ rotating_joint_t motor_rotating_joints[NUM_ROTATINT_JOINT] = { {R_MOTOR_1, 0}, // Motor ID 0, value 0 {R_MOTOR_2, 0}, // Motor ID 1, value 0 {R_MOTOR_3, 0}, // Motor ID 2, value 0 {R_MOTOR_4, 0}, // Motor ID 3, value 0 }; sliding_joint_t motor_sliding_joints[NUM_SLIDING_JOINT] = { {S_MOTOR_1, 0}, // Motor ID 0, value 0 {S_MOTOR_2, 0}, // Motor ID 1, value 0 {S_MOTOR_3, 0}, // Motor ID 2, value 0 }; /* Crate and config left_arm */ robot_arm_manager_t* left_arm = robot_arm_manager_create(); if (left_arm == NULL) return -1; robot_arm_manager_config_rotation_joints(left_arm, motor_rotating_joints, 4); robot_arm_manager_config_sliding_joints(left_arm, motor_sliding_joints, 3); robot_arm_manager_compute_path(left_arm); robot_arm_manager_execute(left_arm); robot_arm_manager_goto_origin(left_arm); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int palindromo(char * string, int ini, int fim); int main() { char strPalindromo[200]; printf("Digite a expressao"); gets(strPalindromo); int fim = strlen(strPalindromo); int retorno = palindromo(&strPalindromo, 0, fim -1); if(retorno >0){ printf("Palindromo"); } else { printf("Nao e um palindromo"); } } int palindromo(char * string, int ini, int fim){ if(ini == fim){ return 1; } if(ini > fim ){ return 1; } if(string[ini] == ' '){ return palindromo(string, ini+1,fim); } if(string[fim] == ' '){ return palindromo(string, ini,fim -1); } if(string[ini] == string[fim]) return palindromo(string, ini+1, fim-1); else { return -1; } }
C
#include <stdio.h> int menu() { int flag = 0; int type = 0; printf("**************************************主菜单*****************************************\n"); printf("(1)系统管理菜单\n"); printf("(2)出入库管理菜单\n"); do { printf("请输入1或2选择菜单:"); scanf("%d", &flag); if (flag != 1 && flag != 2) { printf("输入格式错误,请重新输入\n"); } } while (flag != 1 && flag != 2); if (flag == 1) { printf("系统管理菜单\n"); printf("(1)增加物品信息\n"); printf("(2)删除物品信息\n"); printf("(3)查询物品信息\n"); printf("(4)显示物品信息\n"); printf("(5)更改密码\n"); printf("(6)返回上层\n"); printf("输入1-6的数字选择功能:"); } else { printf("出入库管理菜单\n"); printf("(1)物品出库\n"); printf("(2)物品入库\n"); printf("(3)库存物品信息\n"); printf("(4)显示紧缺物品\n"); printf("(5)返回上层\n"); } type = flag * 10; do { printf("请输入编号数字选择菜单:"); scanf("%d", &flag); if (flag < 1 || flag > 6) { printf("输入格式错误,请重新输入\n"); } } while (flag < 1 || flag > 6); return (type + flag); }
C
#include<stdio.h> using namespace std; int main() { int a = 1025; int* p = &a; printf("p = %d\n", p); printf("p+1 = %d\n", p + 1); printf("value at p = %d\n", *p); char* p0; p0 = (char*)p; printf("p0 = %d\n", p0); printf("p0+1 = %d\n", p0 + 1); printf("value at p0 = %d\n", *p0); printf("value at p0+1 = %d\n", *(p0 + 1)); }
C
/* * lcd.c */ #include "../LCD/lcd.h" #include "../../MCAL/Dio/Dio.h" #include "../../MCAL/Dio/Dio_Types.h" #include "../../MCAL/Dio/Dio_config.h" void lcd_command(uint8 cmd){ Dio_write(RS,Low); Dio_write(RW,Low); //DIO_Write(lcd_en,low); GET_BIT(cmd,7)?Dio_write(D7,High):Dio_write(D7,Low); GET_BIT(cmd,6)?Dio_write(D6,High):Dio_write(D6,Low); GET_BIT(cmd,5)?Dio_write(D5,High):Dio_write(D5,Low); GET_BIT(cmd,4)?Dio_write(D4,High):Dio_write(D4,Low); Dio_write(E,High); _delay_us(10); Dio_write(E,Low); _delay_us(200); GET_BIT(cmd,3)?Dio_write(D7,High):Dio_write(D7,Low); GET_BIT(cmd,2)?Dio_write(D6,High):Dio_write(D6,Low); GET_BIT(cmd,1)?Dio_write(D5,High):Dio_write(D5,Low); GET_BIT(cmd,0)?Dio_write(D4,High):Dio_write(D4,Low); Dio_write(E,High); _delay_us(10); Dio_write(E,Low); _delay_us(200); } void lcd_init(){ //DDRA = 0xff; // set port direction as output Dio_write(RW,Low); _delay_ms(20); lcd_command(0x33); lcd_command(0x32); lcd_command(0x28); lcd_command(0x0f); lcd_command(0x06); lcd_command(0x01); _delay_ms(20); } void lcd_char(uint8 data){ Dio_write(RS,High); Dio_write(RW,Low); //DIO_Write(lcd_en,low); GET_BIT(data,7)?Dio_write(D7,High):Dio_write(D7,Low); GET_BIT(data,6)?Dio_write(D6,High):Dio_write(D6,Low); GET_BIT(data,5)?Dio_write(D5,High):Dio_write(D5,Low); GET_BIT(data,4)?Dio_write(D4,High):Dio_write(D4,Low); Dio_write(E,High); _delay_us(10); Dio_write(E,Low); _delay_us(200); GET_BIT(data,3)?Dio_write(D7,High):Dio_write(D7,Low); GET_BIT(data,2)?Dio_write(D6,High):Dio_write(D6,Low); GET_BIT(data,1)?Dio_write(D5,High):Dio_write(D5,Low); GET_BIT(data,0)?Dio_write(D4,High):Dio_write(D4,Low); Dio_write(E,High); _delay_us(1); Dio_write(E,Low); _delay_us(200); } void lcd_str(uint8 *str){ int i =0; while(str[i]!=0){ lcd_char(str[i]); i++; } } void lcd_clear(){ lcd_command(0x01); //clear the display _delay_ms(2); lcd_command(0x80); //cursor at (0,0) } void lcd_str_xy(uint8 x, uint8 y,uint8 *str){ if (y==0 && x<16){ lcd_command((x & 0x0f)|0x80);//cursor at the xy cordinates }else if(y==1 && x<16){ lcd_command((x & 0x0f)|0xc0);//cursor at the xy cordinates } lcd_str(str); }
C
/* practice10.c */ #include<stdio.h> #include<stdlib.h> int main() { int i = 88; int *ptr = &i; printf("i=%d\n", i); printf("*ptr=%d\n\n", *ptr); *ptr = *ptr + 12; printf("i=%d\n", i); printf("*ptr=%d\n\n", *ptr); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* int main() { int fact=1,num; printf("enter the number\n"); scanf("%d",&num); for(int i=1;i<=num;i++) fact *= i; printf("factorial of %d is %d\n",num,fact); return 0; } */ // using recursion int fact(int); int main() { int num,ans; printf("enter the number\n"); scanf("%d",&num); ans=fact(num); printf("factorial of %d is %d\n",num,ans); return 0; } int fact(int x) { int f; if(x==0) { return 1; } else { f=x*fact(x-1); return f; } }
C
#ident "@(#)convert.c 1.7 96/08/16 SMI" /* From AT&T Toolchest */ /* * CONVERT.C * * * LTOU (STR1, STR2) * Copy STR1 to STR2, changing lower case to upper case. * * UTOL (STR1, STR2) * Copy STR1 to STR2, changing upper case to lower case. */ #include "csi.h" #ifdef KSHELL #include "shtype.h" #else #include <ctype.h> #endif /* KSHELL */ /* * LTOU (STR1, STR2) * char *STR1; * char *STR2; * * Copy STR1 to STR2, converting uppercase alphabetics to * lowercase. STR2 should be big enough to hold STR1. * * STR1 and STR2 may point to the same place. * */ void ltou(str1,str2) register char *str1,*str2; { wchar_t *wcs, *wcs_save; if ((wcs_save = wcs = mbstowcs_alloc(str1)) == NULL) return; for(; *wcs; wcs++) { if (sh_iswlower(*wcs)) str2 += sh_wctomb(str2, sh_towupper(*wcs)); else str2 += sh_wctomb(str2, *wcs); } *str2 = 0; xfree((void *)wcs_save); } /* * UTOL (STR1, STR2) * char *STR1; * char *STR2; * * Copy STR1 to STR2, converting lowercase alphabetics to * uppercase. STR2 should be big enough to hold STR1. * * STR1 and STR2 may point to the same place. * */ void utol(str1,str2) register char *str1,*str2; { wchar_t *wcs, *wcs_save; if ((wcs_save = wcs = mbstowcs_alloc(str1)) == NULL) return; for(; *wcs; wcs++) { if (sh_iswupper(*wcs)) str2 += sh_wctomb(str2, sh_towlower(*wcs)); else str2 += sh_wctomb(str2, *wcs); } *str2 = 0; xfree((void *)wcs_save); }
C
/* Copyright (c) 1990 UNIX System Laboratories, Inc. */ /* Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T */ /* All Rights Reserved */ /* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF */ /* UNIX System Laboratories, Inc. */ /* The copyright notice above does not evidence any */ /* actual or intended publication of such source code. */ /* Portions Copyright (c) 1988, Sun Microsystems, Inc. */ /* All Rights Reserved. */ #ident "@(#)id:id.c 1.9" #include <stdio.h> #include <pwd.h> #include <grp.h> #include <sys/param.h> main(argc, argv) int argc; char **argv; { uid_t uid, euid; gid_t gid, egid; static char stdbuf[BUFSIZ]; int c, aflag=0; while ((c = getopt(argc, argv, "a")) != EOF) { switch(c) { case 'a': aflag++; break; default: fprintf(stderr,"usage: id [-a]\n"); exit(1); } } setbuf (stdout, stdbuf); uid = getuid(); gid = getgid(); euid = geteuid(); egid = getegid(); puid ("uid", uid); pgid (" gid", gid); if (uid != euid) puid (" euid", euid); if (gid != egid) pgid (" egid", egid); if (aflag) pgroups (); putchar ('\n'); exit(0); } puid (s, id) char *s; uid_t id; { struct passwd *pw; printf ("%s=%ld", s, id); setpwent(); pw = getpwuid(id); if (pw) printf ("(%s)", pw->pw_name); } pgid (s, id) char *s; gid_t id; { struct group *gr; printf ("%s=%ld", s, id); setgrent(); gr = getgrgid(id); if (gr) printf ("(%s)", gr->gr_name); } pgroups () { gid_t groupids[NGROUPS_UMAX]; gid_t *idp; struct group *gr; int i; i = getgroups(NGROUPS_UMAX, groupids); if (i > 0) { printf (" groups="); for (idp = groupids; i--; idp++) { printf ("%ld", *idp); setgrent(); gr = getgrgid(*idp); if (gr) printf ("(%s)", gr->gr_name); if (i) putchar (','); } } }
C
/*********************************************************************/ /* PhotoLab.c: homework assignment #3, for EECS 22, Fall 2017 */ /* */ /* Author: Mina Moghadam */ /* Date: 11/8/2017 */ /* */ /* Comments: */ /* */ /* Please use this template to submit your hw3. */ /*********************************************************************/ #include "Constants.h" #include "DIPs.h" #include "Advanced.h" #include "FileIO.h" #include "Image.h" #include "Test.h" /*** function declarations ***/ /* print a menu */ void PrintMenu(); int main() { #ifdef DEBUG AutoTest(); #else int rc; int option; /* user input option */ char fname[SLEN]; /* input file name */ IMAGE *image = NULL; rc = 1; PrintMenu(); scanf("%d", &option); /* Hue() parameter */ int degree; /* Posterize() parameter */ unsigned char rbits, gbits, bbits; /* Noise() parameter */ int n; /* MotionBlur() parameter */ int blur_amount; /*Enlarge() parameter*/ int enlarge_percentage; /*Square() parameter*/ int x_offset, y_offset, square_size; /*BrightnessAndContrast() parameter*/ int brightness , contrast; while (option != EXIT) { /*if image existing, clear the image*/ if (option == 1) { if(image != NULL) { DeleteImage(image); } printf("Please input the file name to load: "); scanf("%s", fname); image = LoadImage(fname); } /* menu item 2 - 11 requires image is loaded first */ else if (option >= 2 && option <= 11) { if (image == NULL) { printf("No image is read.\n"); } /* now image is loaded */ else { switch (option) { case 2: printf("Please input the file name to save: "); scanf("%s",fname); SaveImage(fname,image); break; case 3: image = BlackNWhite(image); printf("\"Black & White\" operation is done!\n"); break; case 4: image = Sharpen(image); printf("\"Sharpen\" operation is done!\n"); break; case 5: printf("Please input the degree of changing hue: "); scanf("%d", &degree); image = Hue(image, degree); printf("\"Hue\" operatin is done!\n"); break; case 6: printf("Please input noise percentage: "); scanf("%d", &n); image = Noise(image, n); printf("\"Noise\" operation is done!\n"); break; case 7: printf("Enter the number of posterization bits for R chennel (1 to 8):"); scanf("%hhu", &rbits); printf("Enter the number of posterization bits for G chennel (1 to 8):"); scanf("%hhu", &gbits); printf("Enter the number of posterization bits for B chennel (1 to 8):"); scanf("%hhu", &bbits); Posterize(image , rbits, gbits, bbits); printf("\"Posterize\" operation is done!\n"); break; case 8: printf("Please input motion blur amount: "); scanf("%d", &blur_amount); MotionBlur(image, blur_amount); printf("\"Motion Blur\" operation is done!\n"); break; case 9: printf("Please input the enlarging percentage (integer between 100 - 200):\n"); scanf("%d", &enlarge_percentage); Enlarge(image, enlarge_percentage); printf("\"Enlarge the image\" operation is done!\n"); break; case 10: printf("Please enter the X offset value:\n"); scanf("%d", &x_offset); printf("Please enter the Y offset value:\n"); scanf("%d", &y_offset); printf("Please input the cropped square size:\n"); scanf("%d", &square_size); Square(image, x_offset, y_offset, square_size); printf("\"Square\" operation is done!\n"); break; case 11: printf("Please input the brightness level (integer between -255 - 255):\n"); scanf("%d", &brightness); printf("Please input the contrast level (integer between -255 - 255):\n"); scanf("%d", &contrast); BrightnessAndContrast(image, brightness, contrast); printf("\"Brightness and Contrast Adjustment\" operation is done!\n"); break; default: break;} } } else if (option == 12) { AutoTest(); rc = SUCCESS; /* set returned code SUCCESS, since image is loaded */ } else { printf("Invalid selection!\n"); } /* Process finished, waiting for another input */ PrintMenu(); printf("Please make your choice: "); scanf("%d", &option); } if(image){ assert(image); DeleteImage(image); image = NULL; } printf("You exit the program.\n"); #endif return 0; } /*******************************************/ /* Function implementations should go here */ /*******************************************/ /* Menu */ void PrintMenu() { printf("\n-------------------------\n"); printf("1: Load a PPM image\n"); printf("2: Save the image in PPM and JPEG format\n"); printf("3: Change the color image to black and white\n"); printf("4: Sharpen the image\n"); printf("5: Change the hue of image\n"); printf("6: Add Noise to an image\n"); printf("7: Posterize an image\n"); printf("8: Motion Blur\n"); printf("9: Enlarge the picture by percentage\n"); printf("10: Crop a square potion of the image\n"); printf("11: Adjust the Brightness and Contrast of an image\n"); printf("12: Test all functions\n"); printf("13: Exit\n"); printf("\n-------------------------\n"); printf("Please make your choice: "); } /* vim: set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab : */
C
#include<sys/ahci/ahci.h> #include<sys/ahci/ahcicommands.h> #include<sys/memory/mm_struct.h> #include<string.h> #include<sys/memory/free_phys_pages.h> HBA_PORT hba_port = {0}; HBA_MEM hba_mem = {0}; static int check_type(HBA_PORT port); int print_hba_mem(HBA_MEM *hba_mem); void port_rebase(HBA_PORT *port, int portno, int num_pi); int setup_ahci(){ struct kernel_mm_struct *mm = get_kernel_mm(); printf("mm->start_ahci_mem: %p\n", mm->start_ahci_mem); HBA_MEM *hba_mem = (HBA_MEM *)mm->start_ahci_mem; printf("hba_mem: %p\n", hba_mem); // print_hba_mem(hba_mem); DWORD mem_pi = hba_mem->pi; int num_pi =0; DWORD mem_cap_np = (hba_mem->cap)&HBA_MEM_CAP_NP; printf("mem_Cap_np: %p",mem_cap_np); /* get port details and stop engine */ for(int i=0;i<=mem_cap_np;i++){ if(mem_pi&0x1){ printf("port%d",i); DWORD cmd_st = (hba_mem->ports[i].cmd)&HBA_PORT_CMD_ST; DWORD cmd_fre = (hba_mem->ports[i].cmd)&HBA_PORT_CMD_FRE; // DWORD cmd_fr = (hba_mem->ports[i].cmd)&HBA_PORT_CMD_FR; // DWORD cmd_cr = (hba_mem->ports[i].cmd)&HBA_PORT_CMD_CR; // printf("cmd.st: %p",cmd_st);//0th cmd bit // printf("cmd.fre: %p",cmd_fre);//4th cmd bit // printf("cmd.fr: %p",cmd_fr);//14th cmd bit // printf("cmd.cr: %p\n",cmd_cr);//15th cmd bit int dt = check_type(hba_mem->ports[i]); if (dt == AHCI_DEV_SATA){ printf("SATA drive found at port %d\n", i); } else if (dt == AHCI_DEV_SATAPI){ printf("SATAPI drive found at port %d\n", i); } else if (dt == AHCI_DEV_SEMB){ printf("SEMB drive found at port %d\n", i); } else if (dt == AHCI_DEV_PM){ printf("PM drive found at port %d\n", i); } else{ printf("No drive found at port %d\n", i); } if(cmd_st!=0||cmd_fre!=0){ if(cmd_st!=0){ hba_mem->ports[i].cmd&=RESET_CMD_ST; } if(cmd_fre!=0){ (hba_mem->ports[i].cmd)&=RESET_CMD_FRE; } i--; continue; } } mem_pi>>=1; num_pi++; } printf("num_pi: %d\n",num_pi); DWORD mem_cap_ncs = (hba_mem->cap)&HBA_MEM_CAP_NCS; mem_cap_ncs>>=8; mem_cap_ncs++; printf("mem_cap_ncs: %p\n",mem_cap_ncs); if(((hba_mem->cap)&HBA_MEM_CAP_S64A)!=0){ // printf("64 bit supported\n"); } else // printf("64 bit address not supported\n"); mem_pi = hba_mem->pi; /* port rebase */ for(int i=0;i<=mem_cap_np;i++){ if(mem_pi&0x1){ port_rebase(&(hba_mem->ports[i]), i, num_pi); } mem_pi>>=1; } /*start engine */ mem_pi = hba_mem->pi; for(int i = 0;i<=mem_cap_np;i++){ if(mem_pi&0x1){ while(hba_mem->ports[i].cmd & HBA_PORT_CMD_CR); hba_mem->ports[i].cmd |= HBA_PORT_CMD_FRE; hba_mem->ports[i].cmd |= HBA_PORT_CMD_ST; printf("hba_mem->ports[i].serr: %p",hba_mem->ports[i].serr); } mem_pi>>=1; } return 0; } void port_rebase(HBA_PORT *port, int i, int num_pi){ //TODO: we are assuming that number of commandlist is 32 uint32_t FB_BASE = AHCI_BASE + (num_pi/4 + 1)*4096;//each clb is 1K // printf("FB_BASE = %p", FB_BASE); uint64_t CLB_BASE = FB_BASE + (num_pi/16 + 1)*4096; //each fis structure is 256B // printf("CLB_BASE = %p", CLB_BASE); port->clb = AHCI_BASE + (i<<10); port->clbu = 0; uint64_t clb = port->clb; // printf("clb: %p",clb); //if(clb&PAGE_ALIGNED){ uint64_t clb_vir = v_alloc_page_get_phys(&clb, PAGE_TRANS_READ_WRITE | PAGE_TRANS_USER_SUPERVISOR); // printf("clb virtual address: %p",clb_vir ); memset((void*)clb_vir, 0, 4096); // printf("memsetclb"); //} port->fb = FB_BASE + (i<<8); port->fbu = 0; uint64_t fb = port->fb; // printf("fb:%p",fb); if(fb&PAGE_ALIGNED){ uint64_t fb_vir = v_alloc_page_get_phys(&fb, PAGE_TRANS_READ_WRITE | PAGE_TRANS_USER_SUPERVISOR); memset((void*)fb_vir, 0, 4096); // printf("memsetfb"); } HBA_CMD_HEADER *cmdheader = (HBA_CMD_HEADER*)clb_vir; for (int j=0; j<32; j++){ cmdheader[j].prdtl = 8; cmdheader[j].ctba = CLB_BASE + (i<<13) + (j<<8); cmdheader[j].ctbau = 0; uint64_t ctba = cmdheader[j].ctba; // printf("ctba: %p", ctba); if(ctba&PAGE_ALIGNED){ uint64_t ctba_vir = v_alloc_page_get_phys(&ctba, PAGE_TRANS_READ_WRITE | PAGE_TRANS_USER_SUPERVISOR); memset((void*)ctba_vir, 0, 4096); //printf("after memset ctba"); } } } static int check_type(HBA_PORT port) { DWORD ssts = port.ssts; BYTE ipm = (ssts >> 8) & 0x0F; BYTE det = ssts & 0x0F; if (det != 0x3) // Check drive status return AHCI_DEV_NULL; if (ipm != 0x1) return AHCI_DEV_NULL; switch (port.sig){ case SATA_SIG_ATAPI: return AHCI_DEV_SATAPI; case SATA_SIG_SEMB: return AHCI_DEV_SEMB; case SATA_SIG_PM: return AHCI_DEV_PM; default: return AHCI_DEV_SATA; } } int print_hba_mem(HBA_MEM *hba_mem){ printf("hba_mem->cap: %x\n", hba_mem->cap); printf("hba_mem->ghc: %p\n", hba_mem->ghc); printf("hba_mem->is: %p\n", hba_mem->is); printf("hba_mem->pi: %p\n", hba_mem->pi); printf("hba_mem->vs: %p\n", hba_mem->vs); return 0; } int ahcicommands(){ struct kernel_mm_struct *mm = get_kernel_mm(); HBA_MEM *hba_mem = (HBA_MEM *)mm->start_ahci_mem; printf("hba_mem: %p\n", hba_mem); // print_hba_mem(hba_mem); DWORD mem_pi = hba_mem->pi; //int num_pi =0; DWORD mem_cap_np = (hba_mem->cap)&HBA_MEM_CAP_NP; printf("mem_Cap_np: %p",mem_cap_np); /* get port details */ int sata_drive = -1; for(int i=0;i<=mem_cap_np;i++){ if(mem_pi&0x1){ printf("port%d",i); int dt = check_type(hba_mem->ports[i]); if (dt == AHCI_DEV_SATA){ printf("SATA drive found at port %d\n", i); sata_drive = i; } else if (dt == AHCI_DEV_SATAPI){ printf("SATAPI drive found at port %d\n", i); } else if (dt == AHCI_DEV_SEMB){ printf("SEMB drive found at port %d\n", i); } else if (dt == AHCI_DEV_PM){ printf("PM drive found at port %d\n", i); } else{ printf("No drive found at port %d\n", i); } } } printf("sata_drive: %d",sata_drive); DWORD startl = 0; DWORD starth = 0; char *write_buffer = "Hi I am a test string to write"; char read_buffer[512] ; int write_ahci_ret =write_ahci(&hba_mem->ports[sata_drive], startl, starth, 1, (WORD *)write_buffer); printf("write_ahci_ret: %d", write_ahci_ret); printf("write_buffer: %s", write_buffer); int read_ahci_ret =read_ahci(&hba_mem->ports[sata_drive], startl, starth, 1, (WORD *)read_buffer); printf("read_ahci_ret: %d", read_ahci_ret); printf("read_buffer: %s", read_buffer); return 0; }
C
/* Author: smohi002 * Partner(s) Name: * Lab Section:25 * Assignment: Lab #4 Exercise #3 * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif enum States {start, Init, waitRise1, switch1, waitFall1, waitRise2, switch2, waitFall2} state; unsigned char tmpA; void Tick() { switch(state) { case start: state = Init; // PORTB = 0x01; break; case Init: state = waitRise1; // PORTB = 0x01; break; case waitRise1: if (!tmpA) state = waitRise1; else if (tmpA == 0x01) state = switch1; break; case switch1: // PORTB = 0x02; state = waitFall1; break; case waitFall1: if (tmpA == 0x01) state = waitFall1; else if (!tmpA) state = waitRise2; break; case waitRise2: if (!tmpA) state = waitRise2; else if (tmpA == 0x01) state = switch2; break; case switch2: // PORTB = 0x01; state = waitFall2; break; case waitFall2: if (tmpA == 0x01) state = waitFall2; else state = waitRise1; break; default: PORTB = 0x01; state = start; break; }; switch(state) { case start: PORTB = 0x01; break; case Init: PORTB = 0x01; break; case waitRise1: break; case switch1: PORTB = 0x02; break; case waitFall1: break; case waitRise2: break; case switch2: PORTB = 0x01; break; case waitFall2: break; default: break; }; } int main(void) { /* Insert DDR and PORT initializations */ DDRA = 0x00; PORTA = 0xFF; //PORTA = input DDRB = 0xFF; PORTB = 0x00; //PORTB = output state = start; while (1) { tmpA = PINA; Tick(); } return 1; }
C
/* * Here is the layout of this file: * * - Format description * - Global data * - Error-handling routines * - Parsing routines * - Main function */ /* * Format description * ------------------ * * There are several basic commands. When they take parameters, those parameters * will be in the form of hexadecimal digits, one after another, either in bytes * or words. * * Each command is made up of a single character. Here are the commands that are * currently supported: * * C rrggbb: Change color * P xxxxyyyy: Set pixel * L xxxxyyyyxxxxyyyy: Draw line * R xxxxyyyywwwwhhhh: Draw rectangle * F xxxxyyyywwwwhhhh: Fill rectangle * * U: Update display * Q: Quit application * * All hexadecimal digits must be lower-case. */ #include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/X.h> #include <unistd.h> /* * This define enables messages in the program code that can be used to trace * execution. It does not change the execution of the program beyond these messages. */ //#define DEBUG // Global data static const char HexadecimalDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; // Error-handling routines void errorBadByteValue(void) { fprintf(stderr, "A bad byte value was found.\n"); } void errorBadWordValue(void) { fprintf(stderr, "A bad word value was found.\n"); } void errorBadOperation(void) { fprintf(stderr, "A bad operation code was found.\n"); } // Parsing routines int locationIn(char c, const char digits[], int numberofdigits) { // This function returns the position of C in the digit array. int i = 0; while (i < numberofdigits) { if (c == digits[i]) { return i; } i++; } return -1; } int parseHexadecimal(FILE* input, int numberofdigits) { // This routine creates a number out of the hexadecimal // digits on the input stream. It reads the number of digits // and creates the total from those digits. -1 is returned // if any character from the input stream is invalid. int total = 0; int multiplier = 0x1 << (numberofdigits * 4 - 4); int immediate = 0; int character = 0; while ((multiplier > 0) && ! feof(input)) { // We use the immediate variable to handle exceptional // cases of non-hexadecimal characters. character = fgetc(input); if (character != ' ' && character != '\n') { immediate = locationIn(character, HexadecimalDigits, 16); // -1 is the sentinel value for a non-hex character. if (immediate == -1) { return -1; } else { // Add the value to the total. total += multiplier * immediate; } #ifdef DEBUG printf(" Hex converter: total = %x, multiplier = %x, immediate = %x\n", total, multiplier, immediate); #endif // Downshift the multiplier to be one hex-digit (half-byte) // less so that it is accurate for the next position. multiplier >>= 4; } } #ifdef DEBUG printf("Converted hex value of %x\n", total); #endif return total; } int parseByte(FILE* input) { // A shortcut for a two-digit hexadecimal parse. return parseHexadecimal(input, 2); } int parseWord(FILE* input) { // A shortcut for a four-digit hexadecimal parse. return parseHexadecimal(input, 4); } void parseChangeColor(FILE* input, Display* pDisplay, GC TheGC) { // Here, we read three bytes for the R, G, and B values, and then // total them up into one big int value. int red = parseByte(input); int green = parseByte(input); int blue = parseByte(input); #ifdef DEBUG printf("Received change-color operator\n"); #endif // While we could have done something like // if ((red | green | blue) & (1 << 31) != 0), // I think that this is far more readable. if ((red == -1) || (green == -1) || (blue == -1)) { errorBadByteValue(); } else { // Set the color appropriately. XSetForeground(pDisplay, TheGC, (red << 16) + (green << 8) + blue); } } void parsePixel(FILE* input, Display* pDisplay, Drawable Win, GC TheGC) { // Here, we read two words for the X and Y values and then fill // a pixel. int x = parseWord(input); int y = parseWord(input); #ifdef DEBUG printf("Received pixel operator\n"); #endif if ((x == -1) || (y == -1)) { errorBadWordValue(); } else { // Render the pixel. XDrawPoint(pDisplay, Win, TheGC, x, y); } } void parseLine(FILE* input, Display* pDisplay, Drawable Win, GC TheGC) { // We need four values here. They are, in order, X1, Y1, X2, and Y2. int x1 = parseWord(input); int y1 = parseWord(input); int x2 = parseWord(input); int y2 = parseWord(input); #ifdef DEBUG printf("Received line operator\n"); #endif if ((x1 == -1) || (y1 == -1) || (x2 == -1) || (y2 == -1)) { errorBadWordValue(); } else { // Draw the line. XDrawLine(pDisplay, Win, TheGC, x1, y1, x2, y2); } } void parseRectangle(FILE* input, Display* pDisplay, Drawable Win, GC TheGC) { // Here, we also need four values. They are X, Y, width, and height. int x = parseWord(input); int y = parseWord(input); int w = parseWord(input); int h = parseWord(input); #ifdef DEBUG printf("Received rectangle operator\n"); #endif if ((x == -1) || (y == -1) || (w == -1) || (h == -1)) { errorBadWordValue(); } else { // Draw the rectangle. XDrawRectangle(pDisplay, Win, TheGC, x, y, w, h); } } void parseFillRectangle(FILE* input, Display* pDisplay, Drawable Win, GC TheGC) { // And again, we need four values. They are the same ones that we need // to draw a rectangle (parseRectangle()). int x = parseWord(input); int y = parseWord(input); int w = parseWord(input); int h = parseWord(input); #ifdef DEBUG printf("Received fill rectangle operator\n"); #endif if ((x == -1) || (y == -1) || (w == -1) || (h == -1)) { errorBadWordValue(); } else { // Fill the rectangle. XFillRectangle(pDisplay, Win, TheGC, x, y, w, h); } } int parseOperation(FILE* input, Display* pDisplay, Pixmap Background, Drawable Win, GC TheGC) { // Here, we read a character and figure out which operation // it represents. The table is listed above. // If the program should exit, then we return a nonzero number. switch (fgetc(input)) { case 'C': parseChangeColor(input, pDisplay, TheGC); break; case 'P': parsePixel(input, pDisplay, Background, TheGC); break; case 'L': parseLine(input, pDisplay, Background, TheGC); break; case 'R': parseRectangle(input, pDisplay, Background, TheGC); break; case 'F': parseFillRectangle(input, pDisplay, Background, TheGC); break; case 'U': #ifdef DEBUG printf("Received update operator\n"); #endif XSetWindowBackgroundPixmap(pDisplay, Win, Background); XCopyArea(pDisplay, Background, Win, TheGC, 0, 0, 1280, 800, 0, 0); XFlushGC(pDisplay, TheGC); XFlush(pDisplay); break; case 'Q': return -1; case '\n': case ' ': // Do nothing. We allow newlines in our input. break; default: errorBadOperation(); break; } return 0; } // Main function int main(int argc, char** argv) { // // This routine listens for characters on the standard input // and processes them as they come along, with no buffering to // speak of. // Display* pDisplay = NULL; Drawable Win; Pixmap Background; GC TheGC; int quit = 0; int window_id; // Step 1. Initialize the X stuff so that we can commence // g drawing operations. pDisplay = XOpenDisplay(getenv("DISPLAY")); if (argc > 1) window_id = atoi (argv[1]); else window_id = XRootWindow (pDisplay, 0); printf ("Using window id %d\n", window_id); Win = window_id; Background = XCreatePixmap(pDisplay, Win, 1280, 800, 24); TheGC = XDefaultGC(pDisplay, 0); XSetWindowBackground(pDisplay, Win, Background); // Step 2. Begin the processing loop. while (! feof(stdin) && ! quit) { quit = parseOperation(stdin, pDisplay, Background, Win, TheGC); } // Step 3. Clean up by closing the display; then, return non-error status. XFreePixmap(pDisplay, Background); XCloseDisplay(pDisplay); return 0; }
C
#ifndef _RTC_ // #define _RTC_ static uint8_t _I2C_Time_Out; // - static char _I2C_buf[6]; // / static uint8_t _I2C_Error; // //============= - ============== unsigned char bin2bcd(unsigned char n) { return (n/10<<4)+(n % 10); } //============ - ============== unsigned char bcd2bin(unsigned char n) { return (n>>4)*10+(n & 0x0F); } //======================== I2C ========================= // I2C ( /) // : //Adr - ( / (0-/1-)) void _I2C_Start(uint8_t Adr) { TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWEA); // I2C, "", I2C _I2C_Time_Out=0; while(!(TWCR & (1<<TWINT))) // { if (++_I2C_Time_Out>10) {_I2C_Error=1; break;} // 1 _delay_us(100); } TWDR=Adr; // / TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWEA); // _I2C_Time_Out=0; while(!(TWCR & (1<<TWINT))) // { if (++_I2C_Time_Out>10) {_I2C_Error=1; break;} // 1 _delay_us(100); } } //======================== I2C ========================== void _I2C_Stop(void) { TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWSTO); // ( "") } //========================== I2C =========================== // : //*buf - //Length - void _I2C_Write(char *buf, uint8_t Length) { uint8_t temp; // for (temp=0; temp<Length; temp++) { TWDR=*buf; // buf++; TWCR=(1<<TWINT)|(1<<TWEN); // _I2C_Time_Out=0; while(!(TWCR & (1<<TWINT))) // { if (++_I2C_Time_Out>10) {_I2C_Error=1; break;} // 1 _delay_us(100); } } _I2C_Stop(); // _delay_us(10); } //========================== I2C ============================= // : //*buf - //Length - void _I2C_Read(char *buf, uint8_t Length) { uint8_t temp; // for (temp=0; temp<Length; temp++) { if(temp==Length-1) TWCR=(1<<TWINT)|(1<<TWEN); // else TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWEA); _I2C_Time_Out=0; while(!(TWCR & (1<<TWINT))) // { if (++_I2C_Time_Out>10) {_I2C_Error=1; break;} // 1 _delay_us(100); } *buf=TWDR; buf++; if(temp==Length-1) _I2C_Stop(); // } _delay_us(10); } /* //=========== ============ // : //LastByte - // : // char _RTC_Read(char LastByte) { if(LastByte) TWCR=(1<<TWINT)|(1<<TWEA)|(1<<TWEN); // else TWCR=(1<<TWINT)|(1<<TWEN); uint8_t temp=0; while(!(TWCR & (1<<TWINT))) // { if (++temp>10) {_I2C_Error=1; break;} // 1 _delay_us(100); } return TWDR; // } */ //================= =================== char RTC_Init(void) { TWSR=0; // TWBR=77; // TWAR=0x01; // _I2C_Error=0; // _I2C_Start(0xD0); _I2C_buf[0]=0x07; _I2C_buf[1]=0x91; _I2C_Write(_I2C_buf,2); if (_I2C_Error) return 1; // else return 0; } //============================== =============================== char RTC_Get_Time(unsigned char* hour, unsigned char* min, unsigned char* sec) { _I2C_Error=0; // _I2C_Start(0xD0); // _I2C_buf[0]=0x00; _I2C_Write(_I2C_buf,1); _I2C_Start(0xD1); _I2C_Read(_I2C_buf,3); // , , *sec=bcd2bin(_I2C_buf[0]); // *min=bcd2bin(_I2C_buf[1]); // *hour=bcd2bin(_I2C_buf[2]); // if (_I2C_Error) return 1; // else return 0; } //================================= ================================== char RTC_Set_Time(unsigned char hour, unsigned char min, unsigned char sec) { _I2C_Error=0; // _I2C_Start(0xD0); // _I2C_buf[0]=0x00; _I2C_buf[1]=bin2bcd(sec); _I2C_buf[2]=bin2bcd(min); _I2C_buf[3]=bin2bcd(hour); _I2C_Write(_I2C_buf,4); if (_I2C_Error) return 1; // else return 0; } //============================== =============================== char RTC_Get_Date(unsigned char* day, unsigned char* date, unsigned char* month, unsigned char* year) { _I2C_Error=0; // _I2C_Start(0xD0); // _I2C_buf[0]=0x03; _I2C_Write(_I2C_buf,1); _I2C_Start(0xD1); _I2C_Read(_I2C_buf,4); // , , , *day=bcd2bin(_I2C_buf[0])-1; // *date=bcd2bin(_I2C_buf[1]); // *month=bcd2bin(_I2C_buf[2]); // *year=bcd2bin(_I2C_buf[3]); // if (_I2C_Error) return 1; // else return 0; } //================================ ================================== char RTC_Set_Date(unsigned char day, unsigned char date, unsigned char month, unsigned char year) { _I2C_Error=0; // _I2C_Start(0xD0); // _I2C_buf[0]=0x03; _I2C_buf[1]=bin2bcd(day)+1; _I2C_buf[2]=bin2bcd(date); _I2C_buf[3]=bin2bcd(month); _I2C_buf[4]=bin2bcd(year); _I2C_Write(_I2C_buf,5); if (_I2C_Error) return 1; // else return 0; } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ftpf_unsigned_int_expander.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gfielder <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/07 11:58:56 by gfielder #+# #+# */ /* Updated: 2019/03/27 12:56:12 by gfielder ### ########.fr */ /* */ /* ************************************************************************** */ #include "ftpf_backend.h" #include <stdlib.h> /* ** ----------------------------------------------------------------------------- ** ftpf_unsigned_int_expander ** ----------------------------------------------------------------------------- ** specifier: %u ** description: writes an unsigned integer ** options: 0,-,field_width,.,hh,h,l,ll ** notes: none ** ----------------------------------------------------------------------------- ** general reminders ** ----------------------------------------------------------------------------- ** An expander function writes with ft_mswriten(md->ms, "...", 1) ** and returns the number of characters written. ** It writes one character at a time only if md->len + written < md->max_len ** md->ex is the expandler that holds all the option flags. ** ----------------------------------------------------------------------------- */ static void ftpf_handle_padding_uint(t_ftpf_master_data *md, char **str) { size_t str_len; str_len = ft_strlen(*str); if (md->ex->precision > 0) { ft_strinsert_nchr(str, '0', 0, md->ex->precision - str_len); str_len = ft_strlen(*str); } if (md->ex->field_width > 0) { if (!(md->ex->lfjusty) && md->ex->zpad && (md->ex->precision <= 0)) ft_strinsert_nchr(str, '0', 0, md->ex->field_width - str_len); else if (!(md->ex->lfjusty)) ft_strinsert_nchr(str, ' ', 0, md->ex->field_width - str_len); else ft_strinsert_nchr(str, ' ', str_len, md->ex->field_width - str_len); } } int ftpf_unsigned_int_expander(t_ftpf_master_data *md) { char *str; t_ftuint8 value; int i; value = 0ull; if (ftpf_getarg(md, &value) < 0) return (0); str = ft_luitoa(value); if (md->ex->precision == 0 && value == 0) ft_bzero(str, ft_strlen(str)); ftpf_handle_padding_uint(md, &str); i = 0; while (str[i] && (md->max_len < 0 || md->len + i < md->max_len)) ft_mswriten(md->ms, str + i++, 1); free(str); return (i); }
C
#include "quest.h" #include <string.h> /* Definição da estrutura das perguntas (quest). */ struct quest{ long id; /* Id da quest. */ Date creationDate; /* Data de criação da quest. */ int score; /* Pontuação da quest. */ long ownerUserId; /* Id do user que elaborou a quest. */ char* title; /* Título da pergunta. */ char* tags; /* Tag da pergunta. */ int answer_c; /* Nº de answer. */ int comment_c; /* Nº de comentários que a quest obteve. */ int favorite_c; /* Nº de votos favoritos. */ GSList* answerList; /* Lista das answer de uma quest. */ }; /* Função que inicia a estrutura quest. */ Quest init_quest(long id, Date cd, int s,long ouid, char* ti, char* ta, int ac, int cc){ Quest q = malloc(sizeof(struct quest)); q -> id = id; q -> creationDate = cd; q -> score = s; q -> ownerUserId = ouid; q -> title = mystrdup(ti); q -> tags = mystrdup(ta); q -> answer_c = ac; q -> comment_c = cc; q -> answerList = NULL; return q; } /* Gets (Obter valor das variaveis da estrutura) */ long get_id_quest(Quest q){ return q->id; } Date get_date_quest(Quest q){ Date d = q->creationDate; return createDate(get_day(d),get_month(d),get_year(d)); } int get_score_quest(Quest q){ return q->score; } long get_owner_id_quest(Quest q){ return q->ownerUserId; } char* get_title_quest(Quest q){ return mystrdup(q->title); } char* get_tags_quest(Quest q){ return mystrdup(q->tags); } int get_answer_c_quest(Quest q){ return q->answer_c; } int get_comment_c_quest(Quest q){ return q->comment_c; } int get_favorite_c_quest(Quest q){ return q->favorite_c; } GSList* get_answer_list_quest(Quest q){ if(q) return q->answerList; return NULL; } void set_answer_list_quest(Quest q,GSList* l){ if(q) q->answerList = l; } void set_tags_quest(Quest q,char* t){ if(q) q->tags = mystrdup(t); free(t); } static int id_compare_quest(long a,long b){ if(a>b) return -1; else return 1; return 0; } int compare_quest(gconstpointer t1, gconstpointer t2){ Date d1 = get_date_quest((Quest)GPOINTER_TO_SIZE(t1)); Date d2 = get_date_quest((Quest)GPOINTER_TO_SIZE(t2)); long id1 = get_id_quest((Quest)GPOINTER_TO_SIZE(t1)); long id2 = get_id_quest((Quest)GPOINTER_TO_SIZE(t2)); int c = 0; c = (-1)*date_compare(d1,d2); if(!c) c = id_compare_quest(id1,id2); return c; } //Funcao de comparação de score para ordenar uma lista ligada. gint answer_c_compare_quest(gconstpointer a,gconstpointer b){ int f = get_answer_c_quest((Quest)a); int s = get_answer_c_quest((Quest)b); if(f<s) return 1; else if(f>s) return -1; else return compare_quest(a,b); } void comp_tags_quest(gpointer key,gpointer value,gpointer data){ query4 ld = (query4)GPOINTER_TO_SIZE(data); char* t = get_tag_4(ld); GSList* l = get_list_4(ld); if (strstr(get_tags_quest(value),t)){ set_list_4(ld,g_slist_prepend(l,value)); } } void comp_words_quest(gpointer key, gpointer value, gpointer data){ query8 aux = (query8) GPOINTER_TO_SIZE(data); char* w = get_word_8(aux); char* t = get_title_quest((Quest)value); if(strstr(t,w)){ set_list_8(aux,g_slist_prepend(get_list_8(aux),value)); } free(t); } /*adiciona o id da quest na hash*/ void iter_quest9(gpointer data, gpointer user_data){ if(data != NULL){ GHashTable* h = (GHashTable*)GPOINTER_TO_SIZE(user_data); Quest q = (Quest)GPOINTER_TO_SIZE(data); g_hash_table_add(h,GSIZE_TO_POINTER(get_id_quest(q))); } } //Imprimir o conteudo da pergunta. void print_quest(Quest q){ if(q != NULL){ print_date(q->creationDate); printf("Quest:\n\n\t Id: %ld\n\tScore: %d\n\tOwnerUserID: %ld\n\tTitle: %s\n\tI Tags: %s\n\t Answer_c: %d\n\tComment_c: %d\n\tFavorite_c: %d\n\t", q->id,q->score, q->ownerUserId,q->title,q->tags,q->answer_c,q->comment_c,q->favorite_c); printf("\n\n"); } } /* Função resposável por adicionar as answers às quests. */ void add_answer_quest(Quest q, Answer a){ GSList* l = q->answerList; q->answerList = g_slist_prepend(l,a); } void free_quest(Quest q){ if(q){ free_date(q->creationDate); free(q -> title); free(q -> tags); g_slist_free(q->answerList); free(q); } } void free_g_quest(gpointer g){ Quest q = (Quest)GPOINTER_TO_SIZE(g); free_quest(q); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<math.h> #define max 200 #define size 5 #include"std_data.c" #include"dissim.c" static float cluster_setx[size][max],cluster_sety[size][max]; int find_mean(float mean_set[size][size]) { static float meanx,meany,count; for(int i=0;i<2;i++){ for(int j=0;j<data_set_count;j++){ if(cluster_setx[i][j]!=0&&cluster_sety[i][j]!=0){ meanx+=cluster_setx[i][j]; meany+=cluster_sety[i][j]; count++; } } mean_set[i][0]=meanx/count; mean_set[i][1]=meany/count; } return 0;//(mean_set); } int cluster(int k,float mean_set[size][size]) { static float distance[max],mean_set2[size][size]; while(1){ //printf("in cluster\n"); for(int i=0;i<k;i++){ for(int j=0;j<data_set_count;j++){ cluster_setx[i][j]=0; cluster_sety[i][j]=0; } } for(int i=0;i<data_set_count;i++){ for(int j=0;j<k;j++){ for(int l=0;l<k;l++){ distance[j]+=pow((mean_set[j][l]-data_set[i][l]),2); } distance[j]=sqrt(distance[j]); } if(distance[0]<distance[1]){ cluster_setx[0][i]=data_set[i][0]; cluster_sety[0][i]=data_set[i][1]; } else{ cluster_setx[1][i]=data_set[i][0]; cluster_sety[1][i]=data_set[i][1]; } } mean_set2[0][0]=mean_set[0][0]; mean_set2[0][1]=mean_set[0][1]; mean_set2[1][0]=mean_set[1][0]; mean_set2[1][1]=mean_set[1][1]; find_mean(mean_set); if(mean_set2[0][0]==mean_set[0][0]&&mean_set2[0][1]==mean_set[0][1]&&mean_set2[1][0]==mean_set[1][0]&&mean_set2[1][1]==mean_set[1][1]){ printf("final mean values are\n"); printf("\n\n(%f,%f)\n",mean_set[0][0],mean_set[0][1]); printf("\n(%f,%f)\n\n",mean_set[1][0],mean_set[1][1]); break; } } return 0;//(cluster_set); } int main() { float mean_set[size][size]; int random_index,k=2; ds(); printf("k=%d\ninitial randomly chooses mean values are\n",k); srand(time(NULL)); for(int i=0;i<k;i++) { random_index=(int)rand() % (data_set_count+1-0)+0;//random no between no. of dataset and 0 mean_set[i][0]=data_set[random_index][0]; mean_set[i][1]=data_set[random_index][1]; printf("%f\t%f\n",mean_set[i][0],mean_set[i][1]); } cluster(k,mean_set);//k=no of feature/dimension printf("\nCluster sets are:\n\n"); for(int i=0;i<k;i++){ for(int j=0;j<data_set_count;j++){ if(cluster_setx[i][j]!=0||cluster_sety[i][j]!=0){ printf("(%f ",cluster_setx[i][j]); printf(",%f)\t",cluster_sety[i][j]); } } printf("\n\n"); } return 0; }
C
// // Created by Kuba Sokolowski on 12/07/2016. // #ifndef CHESSBOARD_MOVE_H #define CHESSBOARD_MOVE_H #include "Position.h" struct Move { Move(SpecialMoveType specialMoveType) : specialMoveType(specialMoveType) {}; Move(Position start, Position end, PieceType pieceType) : startPosition(start), endPosition(end), pieceType(pieceType) {} Position startPosition; Position endPosition; PieceType pieceType; SpecialMoveType specialMoveType; }; #endif //CHESSBOARD_MOVE_H
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <time.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/msg.h> #include <sys/ipc.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #define RED "\033[0;31m" #define GREEN "\033[32m" #define DF "\033[0m" //struct of queue struct msg_buffer{ long type; int payload; }msg,msgR; extern int errno; int main(int argc,char **argv){ srand(time(NULL)); //creazione della coda //remove("/tmp/tree"); creat("/tmp/tree",0777); key_t k = ftok("/tmp/tree",1); int queueId=msgget(k,0777|IPC_CREAT); if(queueId==-1){ fprintf(stderr, "errno = %d\n", errno); perror("Error printed by perror"); fprintf(stderr,"Strerror: %s\n", strerror(errno)); } printf("%s[SND][queue key]: %d%s\n",GREEN,k,DF); printf("%s[SND][queue ID]: %d%s\n",GREEN,queueId,DF); if(fork()==0){ msg.payload=rand()%100; msg.type = 1; int esito = msgsnd(queueId , &msg, sizeof(msg.payload),0); if (esito>=0){ printf("%s[SND][msg.txt]:%d%s\n",GREEN,msg.payload,DF); }else{ fprintf(stderr, "errno = %d\n", errno); perror("Error printed by perror"); fprintf(stderr,"Strerror: %s\n", strerror(errno)); } exit(0); }else{ while(wait(NULL)>0); msgrcv(queueId,&msg,sizeof(msg.payload),1,0); printf("%s[RCV][msg.txt]:%d%s\n",GREEN,msg.payload,DF); msgctl(queueId, IPC_RMID, NULL); } return 0; }
C
/***************************************************************** // // NAME: Ehsan Kourkchi // // HOMEWORK: Project 1 // // CLASS: ICS 212 // // INSTRUCTOR: Ravi Narayan // // DATE: December 1, 2013 // // FILE: hw09.c // // DESCRIPTION: This file contains the tcp header handling // functions, required for HW09 // //****************************************************************/ // To compile the program: // $ make all // $ ./tcp_hw09 test.bin //****************************************************************/ # include <stdio.h> # include <string.h> # include <stdlib.h> // functions prototype int printheader(); int readfile(char []); int writefile(char []); int response(); // a Global tcp structure struct tcp { int validity; unsigned char source[2]; unsigned char destination[2]; unsigned char sequence[4]; unsigned char acknowledge[4]; unsigned char offset; unsigned char reserved[2]; unsigned char flags; unsigned char window[2]; unsigned char checksum[2]; unsigned char urgent[2]; } header; /***************************************************************** // // Function name: Main // // DESCRIPTION: a function that provide a user interface that asks // the user interactively to add data to the data base // It provides some user friendly menu facilities // // Parameters: Needs one argument, which is the name of input binary file // which contains the TCP header // // Return values: int: != 0 exit with error // = 0 complete the program without error //****************************************************************/ int main(int argc, char *argv[]) { char outfile[20]; strcpy(outfile, "output."); header.validity = 0; // it is set to 1 when a tcp header file is imported // check for the number of input arguments if(argc != 2) { printf("\n Please just enter the input file name as the in-line argument. \n\n"); return 1; } //reading in the input binary file if(readfile(argv[1])) { printf("\n Invalide file name: \"%s\" \n\n", argv[1]); return 2; } printf("\n ********************************"); printf("\n TCP request header [%s]", argv[1]); printheader(); // Prepare the response header based on the stored input header response(); // making the name the output file to store the response strcat(outfile, argv[1]); // writing the output file if(writefile(outfile)) { printf("\n File \"%s\" cannot be created. \n\n", outfile); return 3; } // Reading in the output again if(readfile(outfile)) { printf("\n The output file \"%s\" is not available. \n\n", outfile); return 4; } printf("\n ********************************"); printf("\n TCP response header [%s]", outfile); // Printing out the output file printheader(); return 0; } /** The end of main program */ /*****************************************************************/ /*****************************************************************/ /*****************************************************************/ /***************************************************************** // // Function name: readfile // // DESCRIPTION: a function that read in a binary file which // contains the header of a TCP message // // Parameters: char [] filename: the name of binary input file // // Return values: int: = 1 not able to open the file, exit // = 0 read in the file, and exit with success //****************************************************************/ int readfile(char filename[]) { FILE *file; int i; unsigned char input[20]; file = fopen(filename, "rb"); if (file == NULL) return 1; fread(input, sizeof(input), 1, file); header.source[0] = input[0]; header.source[1] = input[1]; header.destination[0] = input[2]; header.destination[1] = input[3]; for(i=0; i<4; i++) header.sequence[i] = input[4+i]; for(i=0; i<4; i++) header.acknowledge[i] = input[8+i]; header.offset = input[12] & 0xf0; // & 1111 0000 header.reserved[0] = input[12] & 0x0f; // & 0000 1111 header.reserved[1] = input[13] & 0xc0; // & 1100 0000 header.flags = input[13] & 0x3f; // & 0011 1111 header.window[0] = input[14]; header.window[1] = input[15]; header.checksum[0] = input[16]; header.checksum[1] = input[17]; header.urgent[0] = input[18]; header.urgent[1] = input[19]; header.validity = 1; fclose(file); return 0; } /*****************************************************************/ /*****************************************************************/ /*****************************************************************/ /***************************************************************** // // Function name: printheader // // DESCRIPTION: a function that prints the inported tcp header // // Parameters: no input ... It uses the global variable (struct tcp) // // Return values: int: = 1 exit withour printing (no valid tcp header imported) // = 0 printing the header with success //****************************************************************/ int printheader() { unsigned long number; if (header.validity == 0) return 1; printf("\n ***************************\n"); number = header.source[0]*256 + header.source[1]; printf(" Source Port: %d\n", number); number = header.destination[0]*256 + header.destination[1]; printf(" Destination Port: %d\n", number); number = header.sequence[0]*256*256*256 + header.sequence[1]*256*256 + header.sequence[2]*256 + header.sequence[3]; printf(" Sequence Number: %u\n", number); number = header.acknowledge[0]*256*256*256 + header.acknowledge[1]*256*256 + header.acknowledge[2]*256 + header.acknowledge[3]; printf(" Acknowledge Number: %u\n", number); number = header.offset / 16; printf(" Data Offset: %d\n", number); number = header.reserved[0] / 16 + header.reserved[1] / 64; printf(" Reserved: %d\n", number); printf(" Flags: "); if (header.flags & 0x20) printf("URG "); if (header.flags & 0x10) printf("ACK "); if (header.flags & 0x08) printf("PSH "); if (header.flags & 0x04) printf("RST "); if (header.flags & 0x02) printf("SYN "); if (header.flags & 0x01) printf("FIN "); printf("\n"); number = header.window[0]*256 + header.window[1]; printf(" Window: %ld\n", number); printf(" Checksum: %x\n", header.checksum[0]*256 + header.checksum[0]); number = header.urgent[0]*256 + header.urgent[1]; printf(" Urgent Pointer: %ld\n", number); printf(" ***************************\n\n"); return 0; } /*****************************************************************/ /*****************************************************************/ /*****************************************************************/ /***************************************************************** // // Function name: writefile // // DESCRIPTION: a function that writes the header of a TCP message // in a file // // Parameters: char [] filename: the name of binary output file // // Return values: int: = 1 not able to create the file for writing, exit // = 0 writing out the file, and exit with success //****************************************************************/ int writefile(char filename[]) { FILE *file; int i; unsigned char output[20]; if (header.validity == 0) return 1; // no valid header is available file = fopen(filename, "wb"); if (file == NULL) return 1; // unable to open the file for writing output[0] = header.source[0]; output[1] = header.source[1]; output[2] = header.destination[0]; output[3] = header.destination[1]; for(i=0; i<4; i++) output[4+i] = header.sequence[i]; for(i=0; i<4; i++) output[8+i] = header.acknowledge[i]; output[12] = header.offset | header.reserved[0]; output[13] = header.flags | header.reserved[1]; output[14] = header.window[0]; output[15] = header.window[1]; output[16] = header.checksum[0]; output[17] = header.checksum[1]; output[18] = header.urgent[0]; output[19] = header.urgent[1]; fwrite(output, sizeof(output), 1, file); fclose(file); return 0; } /*****************************************************************/ /*****************************************************************/ /*****************************************************************/ /***************************************************************** // // Function name: response // // DESCRIPTION: a function that creates the response based on the stored request // + The response file will switch the source and destination ports // + The sequence number must be incremented by 1 for the response // + The acknowledgment number of the response must be sequence number of the request // + If the SYN flag is set in the request, both the SYN and ACK flags must be set in the response // // Parameters: no input parameter // // Return values: int: = 1 exit withour printing (no valid tcp header imported) // = 0 printing the header with success //****************************************************************/ int response() { if (header.validity == 0) return 1; // no valid header is available int i; unsigned char tmp; for(i=0; i<2; i++) { tmp = header.source[i]; header.source[i] = header.destination[i]; header.destination[i] = tmp; } for(i=0; i<4; i++) header.acknowledge[i] = header.sequence[i]; header.sequence[3]++; if(header.sequence[3] == 0) {header.sequence[2]++; if(header.sequence[2] == 0) {header.sequence[1]++; if(header.sequence[1] == 0) header.sequence[0]++;}} if(header.flags & 0x02) header.flags = header.flags | 0x12; return 0; } /*****************************************************************/ /*****************************************************************/ /*****************************************************************/
C
/* * File: PWM.h * Author: Asmaa Hashim * * Created on February 26, 2020, 11:43 AM */ #ifndef PWM_H #define PWM_H #include"PWM_HW.h" #include"interrupt.h" /* * this enum contains all prescaller modes */ typedef enum{ PRE_1, PRE_4, PRE_16 }T2_CLK_DIV; /* * this enum contains interrupt modes */ typedef enum{ disable, enable, }INT_state; /* * this struct is used to hold all the data that should be passed to PWM_init function */ typedef struct{ T2_CLK_DIV pre_val; unint8 TOP; /** PR2R value --->> the value that timer2 data register will be count till it and then return to 0**/ }CCP_config; /** *@brief : this function is used to initialize PWM *@param : 1- object , pointer to the struct CCP_config , 2- INT_mode , enum INT_state *@ret : void **/ void PWM1_init(CCP_config *object , INT_state INT_mode); /** *@brief : this function is used to set the value of CCP1 compare register *@param : duty , unsigned short , set the value of CCP1 compare register *@ret : void **/ void set_duty1(unint16 duty); /** *@brief : this function is used to start PWM *@param : void *@ret : void **/ void PWM_start(void); /** *@brief : this function is used to stop PWM *@param : void *@ret : void **/ void PWM_stop(); #endif /* PWM_H */
C
#define _CRT_SECURE_NO_DEPRECATE #include<stdio.h> #include<stdlib.h> #include<string.h> #include<conio.h> #include <fcntl.h> #define MAXINODE 50 #define READ 1 #define WRITE 2 #define MAXFILESIZE 1024 #define REGULAR 1 #define SPECIAL 2 #define START 0 #define CURRENT 1 #define END 2 typedef struct superblock { int TotalInode; int FreeInode; }SUPERBLOCK, *PSUPERBLOCK; typedef struct inode { char FileName[50]; int InodeNumber; int FileSize; int FileActualSize; int FileType; char *Buffer; int LinkCount; int ReferenceCount; int permission; struct inode* next; }INODE, *PINODE, **PPINODE; typedef struct filetable { int readOffset; int writeOffset; int count; int mode; PINODE ptrInode; }FILETABLE, *PFILETABLE; typedef struct ufdt { PFILETABLE ptrFileTable; }UFDT; UFDT UFDTArr[50]; SUPERBLOCK SUPERBLOCKobj; PINODE Head = NULL; void man(char* name) { if (name == NULL) { return; } if (strcmp(name, "create") == 0) { printf("Description: Used to create new regular file\n"); printf("Usage: create File_Name Permission \n"); } else if (strcmp(name, "read") == 0) { printf("Description: Used to read data from regular file\n"); printf("Usage: read File_Name No_Of_Bytes_To_Read \n"); } else if (strcmp(name, "write") == 0) { printf("Description: Used to write into regular file\n"); printf("Usage: write File_Name Data_To_write size_of_data \n"); } else if (strcmp(name, "ls") == 0) { printf("Description: List files\n"); printf("Usage: ls\n"); } else if (strcmp(name, "stat") == 0) { printf("Description: Used to display Information about file\n"); printf("Usage: stat File_Name\n"); } else if (strcmp(name, "fstat") == 0) { printf("Description: Used to display Information about file\n"); printf("Usage: fstat File_descriptor \n"); } else if (strcmp(name, "truncate") == 0) { printf("Description: Used to remove data from file\n"); printf("Usage: truncate File_Name \n"); } else if (strcmp(name, "open") == 0) { printf("Description: Used to open existing file\n"); printf("Usage: open File_name mode \n"); } else if (strcmp(name, "close") == 0) { printf("Description: Used to close opened file\n"); printf("Usage: close file_Name \n"); } else if (strcmp(name, "closeAll") == 0) { printf("Description: Used to close all open file\n"); printf("Usage: closeAll \n"); } else if (strcmp(name, "lseek") == 0) { printf("Description: Used to change file offset\n"); printf("Usage: lseek File_Name ChangeInOffset StartPoint\n"); } else if (strcmp(name, "rm") == 0) { printf("Description: Used to delete the file\n"); printf("Usage: rm File_Name\n"); } else { printf("Error: No Manual entry available.\n"); } } void DisplayHelp() { printf("ls: To List out all files\n"); printf("clear: To clear console\n"); printf("open : To open the file\n"); printf("close : To close the file\n"); printf("closeall : To close all the open file\n"); printf("read : To read the content from file\n"); printf("write : To write contents in file\n"); printf("exit : To exit from program\n"); printf("stat : To Display information of file using name\n"); printf("fstat : To Display information of file using file descriptor\n"); printf("truncate : To remove all data from file\n"); printf("rm : To delete the file \n"); } int GetFDFromName(char *name) { int i = 0; while (i < 50) { if (UFDTArr[i].ptrFileTable != NULL) if (strcmp((UFDTArr[i].ptrFileTable->ptrInode->FileName), name) == 0) break; i++; } if (i == 50) return -1; else return i; } PINODE chkFileExist(char *name) { PINODE Temp = Head; if (name == NULL) { return NULL; } while (Temp != NULL) { if (strcmp(name, Temp->FileName) == 0) break; Temp = Temp->next; } return Temp; } void CreateDILB() { int i = 1; PINODE newn = NULL; PINODE Temp = Head; for (; i <= MAXINODE; i++) { newn = (PINODE)malloc(sizeof(INODE)); newn->InodeNumber = i; newn->FileType = 0; newn->FileSize = 0; newn->ReferenceCount = 0; newn->FileSize = 0; newn->FileActualSize = 0; newn->LinkCount = 0; newn->Buffer = NULL; newn->next = NULL; if (Temp == NULL) { Head = newn; Temp = Head; } else { Temp->next = newn; Temp = Temp->next; } } printf("DILB intialization completed successfully.\n"); } void InitialiseSuperBlock() { int i = 0; while (i < MAXINODE) { UFDTArr[i].ptrFileTable = NULL; i++; } SUPERBLOCKobj.TotalInode = MAXINODE; SUPERBLOCKobj.FreeInode = MAXINODE; printf("Superblock intialization completed successfully.\n"); } int CreateFile(char *name, int permission) { int i = 0; PINODE Temp = Head; if (name == NULL || permission < 1 || permission > 3) { return -1; } if (SUPERBLOCKobj.FreeInode == 0) { return -2; } if (chkFileExist(name) != NULL) { return -3; } while (Temp != NULL) { if (Temp->FileType == 0) { break; } Temp = Temp->next; } while (i < MAXINODE) { if (UFDTArr[i].ptrFileTable == NULL) { break; } i++; } UFDTArr[i].ptrFileTable = (PFILETABLE)malloc(sizeof(FILETABLE)); if (UFDTArr[i].ptrFileTable == NULL) { return -4; } SUPERBLOCKobj.FreeInode--; UFDTArr[i].ptrFileTable->readOffset = 0; UFDTArr[i].ptrFileTable->writeOffset = 0; UFDTArr[i].ptrFileTable->mode = permission; UFDTArr[i].ptrFileTable->count = 1; UFDTArr[i].ptrFileTable->ptrInode = Temp; strcpy(UFDTArr[i].ptrFileTable->ptrInode->FileName, name); UFDTArr[i].ptrFileTable->ptrInode->FileType = REGULAR; UFDTArr[i].ptrFileTable->ptrInode->FileSize = MAXFILESIZE; UFDTArr[i].ptrFileTable->ptrInode->ReferenceCount = 1; UFDTArr[i].ptrFileTable->ptrInode->LinkCount = 1; UFDTArr[i].ptrFileTable->ptrInode->permission = permission; UFDTArr[i].ptrFileTable->ptrInode->Buffer = (char*)malloc(sizeof(1024)); return i; } void DeallocateDS() { int i = 1; PINODE Temp = NULL; for (; i <= MAXINODE; i++) { Temp = Head; Head = Head->next; if (Temp->Buffer != NULL) { free(Temp->Buffer); } free(Temp); } for (i = 0; i < MAXINODE; i++) { free(UFDTArr[i].ptrFileTable); } printf("Terminating from the VFS Shell\n"); } void ls_file() { PINODE Temp = Head; while (Temp != NULL) { if (Temp->FileType != 0) { printf("%s\t", Temp->FileName); } Temp = Temp->next; } } int fstat_file(int fd) { int i = 0; //Logic remaining return i; } int stat_file(char *name) { int i = 0; int fd = 0; if (name == NULL) { return -1; } fd = GetFDFromName(name); if (fd == -1) { return -2; } else { printf("\n-----------Statistical information about file---------\n"); printf("File Name: %s\n", UFDTArr[fd].ptrFileTable->ptrInode->FileName); printf("Inode Number: %d\n",UFDTArr[fd].ptrFileTable->ptrInode->InodeNumber); printf("File Size: %d\n", UFDTArr[i].ptrFileTable->ptrInode->FileSize); printf("Actual File Size: %d\n", UFDTArr[i].ptrFileTable->ptrInode->FileActualSize); printf("Link Count: %d\n", UFDTArr[i].ptrFileTable->ptrInode->LinkCount); printf("Reference count: %d\n", UFDTArr[i].ptrFileTable->ptrInode->ReferenceCount); if (UFDTArr[fd].ptrFileTable->ptrInode->permission == 3) { printf("File Permission : Read & Write\n"); } else if (UFDTArr[fd].ptrFileTable->ptrInode->permission == 2) { printf("File Permission : Write Only\n"); } else if (UFDTArr[fd].ptrFileTable->ptrInode->permission == 1) { printf("File Permission : Read Only\n"); } } return 0; } int writeFile(int fd, char *arr, int size) { int iRet = 0; int writeSize = 0; if (UFDTArr[fd].ptrFileTable->mode != WRITE && UFDTArr[fd].ptrFileTable->mode != (READ + WRITE)) { return -1; } if (UFDTArr[fd].ptrFileTable->ptrInode->permission != WRITE && UFDTArr[fd].ptrFileTable->ptrInode->permission != (READ + WRITE)) { return -1; } if (UFDTArr[fd].ptrFileTable->writeOffset == MAXFILESIZE) { return -2; } if (UFDTArr[fd].ptrFileTable->ptrInode->FileType != REGULAR) { return -3; } writeSize = UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize - UFDTArr[fd].ptrFileTable->writeOffset; if (writeSize < size) { strncpy(( UFDTArr[fd].ptrFileTable->ptrInode->Buffer + UFDTArr[fd].ptrFileTable->writeOffset ), arr, size); UFDTArr[fd].ptrFileTable->writeOffset = UFDTArr[fd].ptrFileTable->writeOffset + size; UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize = UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize + size; } else { strncpy(UFDTArr[fd].ptrFileTable->ptrInode->Buffer, arr, writeSize); UFDTArr[fd].ptrFileTable->writeOffset = UFDTArr[fd].ptrFileTable->writeOffset + writeSize; UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize = UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize + writeSize; } return size; } int readFile(int fd, char *arr, int size) { int iRet = 0; int readSize = 0; if (UFDTArr[fd].ptrFileTable->mode != READ && UFDTArr[fd].ptrFileTable->mode != (READ + WRITE)) { return -1; } if (UFDTArr[fd].ptrFileTable->ptrInode->permission != READ && UFDTArr[fd].ptrFileTable->ptrInode->permission != (READ + WRITE)) { return -1; } if (UFDTArr[fd].ptrFileTable->readOffset == MAXFILESIZE) { return -2; } if (UFDTArr[fd].ptrFileTable->ptrInode->FileType != REGULAR) { return -3; } readSize = UFDTArr[fd].ptrFileTable->ptrInode->FileActualSize - UFDTArr[fd].ptrFileTable->readOffset; if (readSize < size) { strncpy(arr, UFDTArr[fd].ptrFileTable->ptrInode->Buffer + UFDTArr[fd].ptrFileTable->readOffset, size); UFDTArr[fd].ptrFileTable->readOffset = UFDTArr[fd].ptrFileTable->readOffset + size; } else { strncpy(arr, UFDTArr[fd].ptrFileTable->ptrInode->Buffer + UFDTArr[fd].ptrFileTable->readOffset, readSize); UFDTArr[fd].ptrFileTable->readOffset = UFDTArr[fd].ptrFileTable->readOffset + readSize; } return size; } int main() { char *ptr = NULL; char str[80]; //width of terminal is 80 char command[4][80]; //maximum command length is 4 int count = 0, ret = 0, fd = 0; char arr[1024]; InitialiseSuperBlock(); CreateDILB(); while (1) { fflush(stdin); strcpy(str, " "); printf("\nCustomized dynamic file system > "); fgets(str, 80, stdin); count = sscanf(str, "%s %s %s %s", command[0], command[1], command[2], command[3]); if (count == 1) { if (strcmp(command[0], "ls") == 0) { ls_file(); continue; } else if (strcmp(command[0], "closeall") == 0) { } else if (strcmp(command[0], "clear") == 0) { system("clear"); continue; } else if (strcmp(command[0], "help") == 0) { DisplayHelp(); continue; } else if (strcmp(command[0], "exit") == 0) { DeallocateDS(); break; } else { printf("Error: Command Not Found!\n"); continue; } } else if (count == 2) { if (strcmp(command[0], "man") == 0) { man(command[1]); continue; } else if (strcmp(command[0], "close") == 0) { } else if (strcmp(command[0], "truncate") == 0) { } else if (strcmp(command[0], "stat") == 0) { ret = stat_file(command[1]); if (ret == -1) { printf("Error: Incomplete parameters.\n"); } else if (ret == -2) { printf("Error: Their is no such fie\n"); } continue; } else if (strcmp(command[0], "fstat") == 0) { ret = fstat_file(atoi(command[1])); if (ret == -1) { printf("Error: Incomplete parameters.\n"); } else if (ret == -2) { printf("Error: Their is no such fie\n"); } continue; } else if (strcmp(command[0], "write") == 0) { fd = GetFDFromName(command[1]); if (fd == -1) { printf("Incorrect parameter\n"); continue; } printf("Enter the data to write in the file\n"); gets(arr); //printf("size is %d", strlen(arr)); ret = writeFile(fd, arr, strlen(arr)); if (ret == -1) { printf("Permission Denied.\n"); } else if (ret == -2) { printf("There is no sufficient Memory to write\n"); } else if (ret == -3) { printf("It is not a regular File\n"); } else { printf("Data has been written successfully\n"); } } else { printf("Error: Command Not Found!\n"); continue; } } else if (count == 3) { if (strcmp(command[0], "create") == 0) { ret = CreateFile(command[1], atoi(command[2])); if (ret >= 0) printf("File is succcessfully created with file descriptor: %d\n", ret); if (ret == -1) printf("Error : Incorrect parameters\n"); if (ret == -2) printf("Error : Their is no Inodes\n"); if (ret == -3) printf("Error : File already exist\n"); if (ret == -4) printf("Error : Memory allocation failure\n"); continue; } else if (strcmp(command[0], "open") == 0) { } else if (strcmp(command[0], "read") == 0) { fd = GetFDFromName(command[1]); if (fd == -1) { printf("Error: Incorrect parameter\n"); continue; } ptr = (char*)malloc(sizeof(atoi(command[2])) + 1); if (ptr == NULL) { printf("Error : Memory allocation failure\n"); continue; } ret = readFile(fd, ptr, atoi(command[2])); if (ret == -1) { printf("Permission Denied.\n"); } else if (ret == -2) { printf("Reached at the end of the file\n"); } else if (ret == -3) { printf("It is not a regular File\n"); } else if (ret == 0) { printf("File is empty\n"); } else if(ret > 0) { write(2, ptr, ret); } continue; } else { printf("Error: Command Not Found!\n"); continue; } } else if (count == 4) { if (strcmp(command[0], "lseek") == 0) { } } else { printf("Error : Command Not Found!\n"); } } _getch(); return 0; }
C
#include <stdio.h> int main() { char ch; puts("Would you like me to send your password to the bad guys?"); for (;;) { printf("Enter Yes or No (Y or N)?"); ch = getchar(); if (ch == 'N' || ch == 'n') { puts("Well then, your password is safe!"); break; } else if (ch == 'Y' || ch == 'y') { puts("Okay, sending password..."); break; } else { puts("You must enter Y or N! \n"); } fpurge(stdin); /* no brake here, keep looping */ } return (0); }
C
/*! @file float.c @brief 浮動小数点の扱いで使う諸々のutility */ #include <stdio.h> #include "float.h" int32_t f2i (float a) { union { float as_float; int32_t as_int; } ret; ret.as_float = a; return ret.as_int; } float i2f (uint32_t a) { union { float as_float; uint32_t as_int; } ret; ret.as_int = a; return ret.as_float; } void print_binary (const uint32_t a) { for (int t = 31; t >= 0;t--) { putchar (a & (1 << t) ? '1' : '0'); } putchar ('\n'); } void fprint_binary (FILE* stream,const uint32_t a) { for (int t = 31; t >= 0;t--) { putc (a & (1 << t) ? '1' : '0',stream); } } void print_binary_n (const uint64_t a,int b) { for (int t = b - 1; t >= 0;t--) { putchar ((a >> t) & 1 ? '1' : '0'); } putchar ('\n'); }
C
#include <sys/resource.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <unistd.h> #include <stdio.h> #include <time.h> #define U "Bubblesort" // 1 #define I "Insercao" // 2 #define S "Selecao" // 3 #define Q "Quicksort" // 4 #define H "Heapsort" // 5 #define M "Mergesort" // 6 typedef long TipoChave; typedef int TipoIndice; typedef struct TipoItem { TipoChave Chave; char nome[100]; } TipoItem; void Bubblesort(TipoItem *A, TipoIndice n){ int i, j; TipoItem aux; for (j = 1; j <= n-1; j++){ for (i = 1; i <= n-1; i++){ if (A[i].Chave > A[i+1].Chave){ aux = A[i]; A[i] = A[i+1]; A[i+1] = aux; } } } } void Insercao(TipoItem *A, TipoIndice n){ TipoIndice i, j; TipoItem x; for (i = 2; i <= n; i++){ x = A[i]; j = i - 1; A[0] = x; /* sentinela */ while (x.Chave < A[j].Chave){ A[j+1] = A[j]; j--; } A[j+1] = x; } } void Selecao(TipoItem *A, TipoIndice n){ TipoIndice i, j, Min; TipoItem x; for (i = 1; i <= n - 1; i++){ Min = i; for (j = i + 1; j <= n; j++){ if (A[j].Chave < A[Min].Chave){ Min = j; } } x = A[Min]; A[Min] = A[i]; A[i] = x; } } void Particao(TipoIndice Esq, TipoIndice Dir, TipoIndice *i, TipoIndice *j, TipoItem *A){ TipoItem x, w; *i = Esq; *j = Dir; x = A[(*i + *j) / 2]; /* obtem o pivo x */ do{ while (x.Chave > A[*i].Chave) (*i)++; while (x.Chave < A[*j].Chave) (*j)--; if (*i <= *j){ w = A[*i]; A[*i] = A[*j]; A[*j] = w; (*i)++; (*j)--; } } while (*i <= *j); } void Ordena(TipoIndice Esq, TipoIndice Dir, TipoItem *A){ TipoIndice i, j; Particao(Esq, Dir, &i, &j, A); if (Esq < j) Ordena(Esq, j, A); if (i < Dir) Ordena(i, Dir, A); } void Quicksort(TipoItem *A, TipoIndice n){ Ordena(1, n, A); } void Refaz(TipoIndice Esq, TipoIndice Dir, TipoItem *A){ TipoIndice i = Esq; int j; TipoItem x; j = i * 2; x = A[i]; while (j <= Dir){ if (j < Dir){ if (A[j].Chave < A[j+1].Chave) j++; } if (x.Chave >= A[j].Chave) goto L999; A[i] = A[j]; i = j; j = i * 2; } L999: A[i] = x; } void Constroi(TipoItem *A, TipoIndice n){ TipoIndice Esq; Esq = n / 2 + 1; while (Esq > 1){ Esq--; Refaz(Esq, n, A); } } void Heapsort(TipoItem *A, TipoIndice n){ TipoIndice Esq, Dir; TipoItem x; Constroi(A, n); Esq = 1; Dir = n; while (Dir > 1){ x = A[1]; A[1] = A[Dir]; A[Dir] = x; Dir--; Refaz(Esq, Dir, A); } } void Merge(TipoItem *A, int i, int m, int j){ TipoItem *B = (TipoItem*)malloc ((j+i+1) * sizeof (TipoItem)); int x; int k = i; int l = m+1; for (x = i; x <= j; x++){ B[x] = A[x]; } x = i; while (k <= m && l <= j) { if (B[k].Chave <= B[l].Chave){ A[x++] = B[k++]; } else{ A[x++] = B[l++]; } } while (k <= m){ A[x++] = B[k++]; } while (l <= j){ A[x++] = B[l++]; } } void Mergesort(TipoItem *A, int i, int j){ int m; if (i < j){ m = (i + j - 1) / 2; Mergesort(A, i, m); Mergesort(A, m + 1, j); Merge(A, i, m, j); } } void Imprime(TipoItem *V, TipoIndice n){ for (int i = 1; i <= n; i++){ printf("%li ", V[i].Chave); printf("\n"); } } void Copia(TipoItem *Fonte, TipoItem *Destino, TipoIndice n){ for (int i = 1; i <= n; i++){ Destino[i] = Fonte[i]; } } void Testa(TipoItem *V, TipoIndice n){ for (int i = 2; i <= n; i++) { if (V[i].Chave < V[i-1].Chave) { printf("ERRO\n"); return; } } printf("OK\n"); } void troca(TipoItem *A, int i, int j){ TipoItem aux; aux = A[i]; A[i] = A[j]; A[j] = aux; } void embaralhar(TipoItem *A, int n){ srand(time(NULL)); for (int i = 1; i <= n; i++){ int r = 1 + rand() % n; troca(A, i, r); } } void embaralhar20(TipoItem *A, int n){ srand(time(NULL)); int m = (int) (n * 0.2)/2;; for (int i = 1; i <= m; i++){ int r = 1 + rand() % n; troca(A, i, r); } } void geraCrescente(TipoItem *A, int n){ for (int i = 1; i <= n; i++) { A[i].Chave = i; } } void geraDecrescente(TipoItem *A, int n){ int j = 1; for (int i = n; i >= 1; i--) { A[i].Chave = j; j++; } } void geraAleatorio(TipoItem *A, int n){ geraCrescente(A, n); embaralhar(A, n); } void geraQuaseOrdenado(TipoItem *A, int n){ geraCrescente(A, n); embaralhar20(A, n); } int main(int argc, char** argv) { int who = RUSAGE_SELF; struct rusage usage; long utotalmicroseg, utotalseg; char optc = 0; struct option OpcoesLongas[] = { {"-a", required_argument, NULL, 'a'}, {"-n", required_argument, NULL, 'n'}, {"-t", required_argument, NULL, 't'}, {"-v", required_argument, NULL, 'v'}, {"-r", required_argument, NULL, 'r'} }; if(argc < 11) { printf("Parametros faltando\n"); exit(0); } int met = 0, n = 0, t = 0, v = 0, r = 0; while((optc = getopt_long(argc, argv, "a:n:t:v:r:", OpcoesLongas, NULL)) != -1) { switch(optc) { case 'a': printf("Metodo: %s\n", optarg); if(strcmp(U, optarg) == 0) met = 1; if(strcmp(I, optarg) == 0) met = 2; if(strcmp(S, optarg) == 0) met = 3; if(strcmp(Q, optarg) == 0) met = 4; if(strcmp(H, optarg) == 0) met = 5; if(strcmp(M, optarg) == 0) met = 6; break; case 'n': printf("Quantidade: %s\n", optarg); n = atoi(optarg); break; case 't': printf("Tipo: %s\n", optarg); t = atoi(optarg); break; case 'v': printf("Imprimir original: %s\n", optarg); if(strcmp("S", optarg) == 0) v = 1; break; case 'r': printf("Imprimir ordenado: %s\n", optarg); if(strcmp("S", optarg) == 0) r = 1; break; default: printf("Parametros incorretos.\n"); exit(0); } } /* TESTES DOS ARGUMENTOS printf("A: %d\n", met); printf("N: %d\n", n); printf("T: %d\n", t); printf("V: %d\n", v); printf("R: %d\n", r); */ TipoItem *A = malloc((n+1) * sizeof(TipoItem)); TipoItem *B = malloc((n+1) * sizeof(TipoItem)); switch(t) { case 1: geraCrescente(A, n); break; case 2: geraDecrescente(A, n); break; case 3: geraAleatorio(A, n); break; case 4: geraQuaseOrdenado(A, n); break; default: printf("Argumento Invalido\n"); exit(0); } Copia(A,B,n); switch(met) { case 1: Bubblesort(A, n); break; case 2: Insercao(A, n); break; case 3: Selecao(A, n); break; case 4: Quicksort(A, n); break; case 5: Heapsort(A, n); break; case 6: Mergesort(A, 1, n); break; default: printf("Argumento Invalido\n"); exit(0); } if (v){ printf("Vetor Original\n"); Imprime(B, n); } if (r){ printf("Vetor Ordenado\n"); Imprime(A, n); } Testa(A,n); getrusage(who, &usage); utotalseg = usage.ru_utime.tv_sec; // segundos utotalmicroseg = usage.ru_utime.tv_usec; // microsegundos printf("----------------------------------------------------------------------\n"); printf ("Tempo de usuario: %ld segundos e %ld microssegundos.\n", utotalseg, utotalmicroseg); printf("----------------------------------------------------------------------\n"); free(A); free(B); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include <string.h> #include <unistd.h> int main(){ DIR *dp; FILE * wfp, *rfp; struct dirent *dent; char name_data, *file_data; int i = 0, c; if((dp = opendir("./sample")) == NULL){ perror("open"); exit(1); } chdir("sample"); if((wfp = fopen("sum.txt", "w")) == NULL){ perror("write"); exit(1); } while (dent = readdir(dp)) { name_data = dent->d_name[i++]; while('.' != name_data) name_data = dent->d_name[i++]; // .이 나올때 까지 반복 if('c'== dent->d_name[i]) { if((rfp = fopen(("%s", dent->d_name), "r")) == NULL){ perror(dent->d_name); exit(1); } while((c = fgetc(rfp)) != EOF){ fputc(c, wfp); } } i = 0; } closedir(dp); fclose(wfp); fclose(rfp); }
C
#ifdef USE_QUADRATIC_HASH #if defined(_MSC_VER) && defined(_DEBUG) #define AVP_DUMP_MEM_LEAK #endif // Necessary includes and defines for memory leak detection: #ifdef AVP_DUMP_MEM_LEAK #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "hash_quadratic.h" #define WARN_NO_MEM fprintf(stderr, "%s %d No memory\n", __FILE__, __LINE__); /* -------------------------- hash functions -------------------------------- */ static uint8_t dict_hash_function_seed[16]; /* The default hashing function uses SipHash implementation * in siphash.c. */ uint64_t siphash(const uint8_t* in, const size_t inlen, const uint8_t* k); uint64_t siphash_nocase(const uint8_t* in, const size_t inlen, const uint8_t* k); void hash_set_hash_function_seed(uint8_t* seed) { memcpy(dict_hash_function_seed, seed, sizeof dict_hash_function_seed); } uint64_t hash_gen_hash_function(const void* key, size_t len) { return siphash(key, len, dict_hash_function_seed); } /* ----------------------------- API implementation ------------------------- */ static int is_prime(int n) { if (n < 2) return 0; if (n == 2) return 1; if (n % 2 == 0) return 0; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) return 0; } return 1; } // next prime bigger than n, and in 4k+3 form // `two-square therorem of Fermat` static int next_4kp3_prime(int n) { while (++n % 4 != 3 || !is_prime(n)); return n; } /* Returns the index of a free slot that can be populated with * a hash entry for the given 'key'. * If the key already exists, -1 is returned * and the optional output parameter may be filled. */ static long _hash_find(hash_t* h, const void* key, uint64_t hash, entry_t** existing) { long long i = 0; long long pos, cur; #if USE_EXPONETIAL_EXPANDING pos = cur = hash & (h->size - 1); #else pos = cur = hash % h->size; #endif if (existing) *existing = NULL; sizeof(int); sizeof(long long); while (h->entries[pos] && h->entries[pos]->state == ENTRY_STATE_LEGITIMATE && !hash_compare_keys(h, key, h->entries[pos]->key)) { if (i == 46340) { int j = 0; } if (++i % 2) { pos = cur + (i + 1) * (i + 1) / 4; while (pos >= h->size) pos %= h->size; } else { pos = cur - i * i / 4; while (pos < 0) pos += h->size; } if (pos >= h->size) { int j = 0; } } if (h->entries[pos] && h->entries[pos]->state == ENTRY_STATE_LEGITIMATE) { if (existing) *existing = h->entries[pos]; return -1; } return pos; } hash_t* hash_create(hash_type_t* type) { hash_t* h = malloc(sizeof *h); if (h == NULL) { WARN_NO_MEM; return NULL; } h->type = type; #if USE_EXPONETIAL_EXPANDING h->size = 8; #else h->size = next_4kp3_prime(HASH_TABLE_MIN_SIZE); #endif h->used = 0; h->entries = calloc(1, sizeof(entry_t*) * h->size); if (h->entries == NULL) { WARN_NO_MEM; free(h); return NULL; } return h; } void hash_clear(hash_t* h) { for (unsigned int i = 0; i < h->size; i++) { if (h->entries[i]) { hash_free_taken_entry(h, h->entries[i]); h->entries[i] = NULL; } } h->used = 0; } void hash_free(hash_t* h) { hash_clear(h); free(h->entries); free(h); } float hash_load_factor(hash_t* h) { return h->used * 1.0f / h->size; } void hash_rehash(hash_t* h) { unsigned long size; if (hash_load_factor(h) <= HASH_TABLE_MIN_LOAD_FACTOR) { #if USE_EXPONETIAL_EXPANDING size = h->size / 2; #else size = (unsigned int)(h->size * HASH_TABLE_MIN_LOAD_FACTOR * 2); #endif if (size < HASH_TABLE_MIN_SIZE) size = HASH_TABLE_MIN_SIZE; if (size == h->size) return; } else if (hash_load_factor(h) >= HASH_TABLE_MAX_LOAD_FACTOR) { #if USE_EXPONETIAL_EXPANDING size = h->size * 2; #else size = next_4kp3_prime(h->size * 2); #endif } else { return; } hash_t tmph = *h; tmph.entries = calloc(1, sizeof(entry_t*) * size); if (tmph.entries == NULL) { WARN_NO_MEM; abort(); } tmph.size = size; tmph.used = 0; for (unsigned long i = 0; i < h->size; i++) { if (h->entries[i]) { if (h->entries[i]->state == ENTRY_STATE_LEGITIMATE) { #if USE_EXPONETIAL_EXPANDING uint64_t hash = hash_hash_key(&tmph, h->entries[i]->key) & (size - 1); #else uint64_t hash = hash_hash_key(&tmph, h->entries[i]->key) % size; #endif long idx = _hash_find(&tmph, h->entries[i]->key, hash, NULL); assert(idx != -1); tmph.entries[idx] = h->entries[i]; tmph.used++; } else { hash_free_taken_entry(h, h->entries[i]); } } } assert(tmph.used == h->used); free(h->entries); h->entries = tmph.entries; h->size = size; } /* Add an element to the target hash table */ int hash_insert(hash_t* h, void* key, void* val) { entry_t* he = hash_insert_raw(h, key, NULL); if (!he) return HASH_ERR; hash_set_val(h, he, val); return HASH_OK; } /* Low level add or find: * This function adds the entry but instead of setting a value returns the * entry_t structure to the user, that will make sure to fill the value * field as they wish. * * This function is also directly exposed to the user API to be called * mainly in order to store non-pointers inside the hash value, example: * * entry = hash_insert_raw(dict,mykey,NULL); * if (entry != NULL) hash_set_s64_val(entry,1000); * * Return values: * * If key already exists NULL is returned, and "*existing" is populated * with the existing entry if existing is not NULL. * * If key was added, the hash entry is returned to be manipulated by the caller. */ entry_t* hash_insert_raw(hash_t* h, void* key, entry_t** existing) { entry_t* he = NULL; #if USE_EXPONETIAL_EXPANDING uint64_t hash = hash_hash_key(h, key) & (h->size - 1); #else uint64_t hash = hash_hash_key(h, key) % h->size; #endif /* Get the index of the new element, or -1 if * the element already exists. */ long idx = _hash_find(h, key, hash, existing); if (idx == -1) return NULL; if (h->entries[idx]) { assert(h->entries[idx]->state == ENTRY_STATE_DELETED); he = h->entries[idx]; hash_free_key(h, he); hash_free_val(h, he); } else { he = malloc(sizeof * he); if (!he) { WARN_NO_MEM; return NULL; } } h->entries[idx] = he; hash_set_key(h, he, key); he->state = ENTRY_STATE_LEGITIMATE; h->used++; if (hash_load_factor(h) >= HASH_TABLE_MAX_LOAD_FACTOR) hash_rehash(h); return he; } /* Search and remove an element. This is a helper function for * hash_remove() and hash_take(), please check the top comment * of those functions. */ static entry_t* hash_generic_remove(hash_t* h, const void* key, int nofree) { long long i = 0; long long pos, cur; if (h->used == 0) return NULL; #if USE_EXPONETIAL_EXPANDING pos = cur = hash_hash_key(h, key) & (h->size - 1); #else pos = cur = hash_hash_key(h, key) % h->size; #endif while (h->entries[pos] && !hash_compare_keys(h, key, h->entries[pos]->key)) { if (++i % 2) { pos = cur + (i + 1) * (i + 1) / 4; if (pos >= h->size) pos %= h->size; } else { pos = cur - i * i / 4; while (pos < 0) pos += h->size; } } if (h->entries[pos] && h->entries[pos]->state == ENTRY_STATE_LEGITIMATE) { if (!nofree) { entry_t* he = h->entries[pos]; h->entries[pos] = malloc(sizeof(entry_t)); if (!h->entries[pos]) { WARN_NO_MEM; abort(); } hash_set_key(h, h->entries[pos], he->key); hash_set_val(h, h->entries[pos], he->v.val); hash_free_taken_entry(h, he); } h->entries[pos]->state = ENTRY_STATE_DELETED; h->used--; return h->entries[pos]; } return NULL; } /* Remove an element, returning HASH_OK on success or HASH_ERR if the * element was not found. */ int hash_remove(hash_t* h, const void* key) { return hash_generic_remove(h, key, 0) ? HASH_OK : HASH_ERR; } /* Remove an element from the table, but without actually releasing * the key, value and dictionary entry. The dictionary entry is returned * if the element was found (and removed from the table), and the user * should later call `hash_free_taken_entry()` with it in order to release it. * Otherwise if the key is not found, NULL is returned. * * This function is useful when we want to remove something from the hash * table but want to use its value before actually deleting the entry. * Without this function the pattern would require two lookups: * * entry = hash_find(...); * // Do something with entry * hash_remove(dictionary,entry); * * Thanks to this function it is possible to avoid this, and use * instead: * * entry = hash_take(dictionary,entry); * // Do something with entry * hash_free_taken_entry(entry); // <- This does not need to lookup again. */ entry_t* hash_take(hash_t* h, const void* key) { return hash_generic_remove(h, key, 1); } void hash_free_taken_entry(hash_t* h, entry_t* he) { if (he == NULL) return; hash_free_key(h, he); hash_free_val(h, he); free(he); } entry_t* hash_find(hash_t* h, const void* key) { long long i = 0; long long pos, cur; if (h->used == 0) return NULL; #if USE_EXPONETIAL_EXPANDING pos = cur = hash_hash_key(h, key) & (h->size-1); #else pos = cur = hash_hash_key(h, key) % h->size; #endif while (h->entries[pos] && !hash_compare_keys(h, key, h->entries[pos]->key)) { if (++i % 2) { pos = cur + (i + 1) * (i + 1) / 4; if (pos >= h->size) pos %= h->size; } else { pos = cur - i * i / 4; while (pos < 0) pos += h->size; } } if (h->entries[pos] && h->entries[pos]->state == ENTRY_STATE_DELETED) { return NULL; } return h->entries[pos]; } entry_t* hash_get_random_key(hash_t* h) { entry_t* he = NULL; if (h->used == 0) return NULL; do { he = h->entries[rand() % h->size]; } while (he == NULL || he->state != ENTRY_STATE_LEGITIMATE); return he; } void* hash_retrieve_value(hash_t* h, const void* key) { entry_t* he = hash_find(h, key); return he ? hash_get_val(he) : NULL; } #endif // USE_QUADRATIC_HASH
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_do_op.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oel-ayad <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/16 15:47:22 by oel-ayad #+# #+# */ /* Updated: 2018/08/18 18:38:29 by oel-ayad ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_op.h" int ft_usage(int nb1, int nb2) { return (nb1 + nb2); } int check_error(int argc, char **argv) { int result; int i; i = 0; result = 0; if (argc != 4) return (0); if ((ft_strcmp(argv[2], "/") == 0) && (ft_atoi(argv[3]) == 0)) { ft_putstr(ERR_DIV); return (0); } if ((ft_strcmp(argv[2], "%") == 0) && ft_atoi(argv[3]) == 0) { ft_putstr(ERR_MOD); return (0); } return (1); } int main(int argc, char **argv) { int i; i = 0; if (check_error(argc, argv) == 0) return (0); while (ft_strcmp(g_optab[i].op, "")) { if (ft_strcmp(g_optab[i].op, argv[2]) == 0) { ft_putnbr(g_optab[i].put_f(ft_atoi(argv[1]), ft_atoi(argv[3]))); ft_putchar('\n'); return (0); } i++; } ft_putnbr(0); ft_putchar('\n'); return (0); }
C
#include <stdio.h> int isBitSet(int input, int bitpos) { return ((input & (1 << bitpos)) ? 1 : 0); } int main() { int input, position; printf("Zahl eingeben: "); scanf("%d", &input); printf("Zu pruefende Stelle angeben (mit 0 beginnend): "); scanf("%d", &position); printf("%d an Stelle %d gefunden.\n", isBitSet(input, position), position); }
C
#ifndef RNG_H #define RNG_H #ifdef __cplusplus extern "C" { #endif /* Mersenne Twister pseudo-random number generator. Based on the * implementation of src/common/Random.c of Cuba 1.4, itself an adaptation of * the original C code of T. Nishimura and M. Matsumoto from * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html */ /* 32 or 53 random bits */ #ifndef MERSENNE_NBITS #define MERSENNE_NBITS 32 #endif /* Length of state vector */ #define MERSENNE_N 624 /* Period parameter */ #define MERSENNE_M 397 /* Standard interface. Uses static state vector. Not thread-safe. */ void rng_init(unsigned int seed); unsigned int rng_random(); double rng_uniform(); // return value lies in half-open interval [0,1) typedef struct { unsigned int state[MERSENNE_N]; int next; } rng_state; /* Thread-safe variants. User allocates a 'rng_state' variable, initializes it * with a call to 'rng_init_r()', then draws randoms from it with either * 'rng_random_r()' or 'rng_uniform_r()'. */ void rng_init_r(rng_state *rng, unsigned int seed); unsigned int rng_random_r(rng_state *rng); double rng_uniform_r(rng_state *rng); /* Sampling from non-uniform distributions. */ /* Standard normal distribution */ double rng_normal(); double rng_normal_r(rng_state *rng); /* Exponential distribution */ double rng_exponential(double lambda); double rng_exponential_r(rng_state *rng, double lambda); /* Poisson distribution (note that the return value is integral, even though * it is returned as a double; cast to int as desired) */ double rng_poisson(double mu); double rng_poisson_r(rng_state *rng, double mu); /* Sobol quasi-random sequence generator. Based on ACM TOMS algorithm 659, * adapted from src/common/Random.c of Cuba 1.4. * * Here's a usage example showing how to perform quasi-Monte Carlo integration * of the function f(x,y,z) over the unit cube: * * int i, npoints; * double x[3], sum; * Sobol seq; * rng_sobol_init(&seq, 3); * for(i = 0; i < npoints; i++) { * rng_sobol_get(&seq, x); * sum += f(x[0], x[1], x[2]); * } * sum /= npoints; */ /* Maximum dimension of Sobol sample space */ #ifndef SOBOL_MAXDIM #define SOBOL_MAXDIM 40 #endif typedef struct { int ndim; double norm; int v[SOBOL_MAXDIM][30], prev[SOBOL_MAXDIM]; int seq; } Sobol; void rng_sobol_init(Sobol *sobol, int ndim); void rng_sobol_get(Sobol *sobol, double *x); void rng_sobol_skip(Sobol *sobol, int n); #ifdef __cplusplus } #endif #endif // RNG_H
C
/* test0c.c - launch EXAMPLE.BAS from C */ #include <mikeos.h> /* used MikeOS API :- mikeos_get_file_size mikeos_load_file mikeos_run_basic */ /* filename and buffer must be on the static region */ static char FileName[] = "EXAMPLE.BAS"; static char Buf[8192]; /* test os_run_basic */ static void test_run_basic(void) { int size; static char str0[] = "mikeos_run_basic OK"; static char str1[] = "mikeos_run_basic NG"; /* get file size for os_run_basic */ size = mikeos_get_file_size(FileName); if (size < 0 || size > sizeof(Buf)) goto error; /* load BASIC file into buffer */ if (mikeos_load_file(Buf, FileName) != size) goto error; /* run it */ mikeos_run_basic(Buf, size); success: mikeos_print_string(str0); mikeos_print_newline(); return; error: mikeos_print_string(str1); mikeos_print_newline(); return; } int MikeMain(void *arg) { test_run_basic(); return 0; }
C
void bubbleSort(int arr[], int n) { // Your code here int temp; for(int i=0;i<n;i++){ for(int j=0;j<n-i-1;j++){ if(arr[j]>arr[j+1]){ temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <errno.h> #include <netdb.h> #include <arpa/inet.h> int main(int argc , char *argv[]) { int sockfd; struct addrinfo hints, *servinfo, *p; struct sockaddr_in *h; int rc, ctr; //if argc size is less than 2, then the hostname was not included as a command line input. if(argc <3){ printf("Error: Missing Hostname/IP Address or flag to decide IP->Hostname or Hostname->IP\n"); exit(1); } //if command line input is "-h", then hostname was given. if (strcmp(argv[1], "-h") == 0) { char *hostname = argv[2]; //hostname from command line input. char ip[100]; //set up to take in the IPv4 address later. memset(&hints, 0, sizeof hints); //setting space for hints. hints.ai_family = AF_INET; //setting the family type to IPv4 only. hints.ai_socktype = SOCK_STREAM; //setting socket type to streams. //if the return value is not zero, there is an error. if((rc = getaddrinfo(hostname, "http", &hints, &servinfo)) != 0) { perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. exit(-1); } ctr = 1; //find the first connection from the results for(p = servinfo; p != NULL; p = p->ai_next) { h = (struct sockaddr_in *) p->ai_addr; //set h to the pointer of the sockaddr struct. ai_addr is a pointer to a filled-in socket address struct. strcpy(ip, inet_ntoa(h->sin_addr)); //sin_addr holds the IPv4 address. this is copied to ip. printf("%s - IPv4 address #%d: %s\n" ,hostname , ctr, ip); ctr++; } } //otherwise, if command line input is "-i", then IPv4 address was given. else if(strcmp(argv[1], "-i") == 0){ struct addrinfo *res=0; //Setting addrinfo struct for getaddrinfo. int rc; //used for error-checking later on. char *ip = argv[2]; //command line input char hostname[1000]; //variable to store output printf("Command line input: %s\n", ip); //output to show user their input. rc = getaddrinfo(ip, 0, 0, &res); //getaddrinfo is used to supply parameters to getnameinfo. //error checking getaddrinfo. if(rc != 0) { perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. exit(-1); } rc = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 1000, 0, 0, 0); //error checking getnameinfo. if(rc != 0) { perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. exit(-1); } printf("Hostname found: %s\n", hostname); } }
C
#include <stdio.h> #include <malloc.h> #define STACKSIZE 4 typedef struct LIST { int data; struct LIST *next; } LIST; static int stack[STACKSIZE]; static int S_top; static LIST *head,*tail; void printstack(int *); void printlist(LIST *); void add(int x){ LIST *p1,*p2; p2 = (LIST *)(malloc(sizeof(LIST))); p2->next = NULL; p2->data = x; if(head == NULL) { head = p2; } else { p1 = head; while(p1->next != NULL) p1 = p1->next; p1->next = p2; } } int take(){ LIST *p; int x; if(head == NULL){ printf("Error: Underflow(take top)\n"); return -1; } p = head; x = p->data; head = p->next; free(p); return x; } void push(int x){ if(S_top == STACKSIZE){ printf("Error:Overflow\n"); return; } else { stack[S_top++] = x; } } int pop(void){ if(S_top == 0){ printf("Error:Underflow\n"); return -1; } return stack[--S_top]; } int main(void){ int data,i; printf("/*(case1)\n"); printf("sizeof(LIST)=%d\n",sizeof(LIST)); S_top = 0; push(500); push(200); push(300); data = pop(); if(data>0){ printf("stack=[%d]=%d\n",S_top,data); } push(400); printstack(stack); for(i=0;i<4;i++){ data = pop(); if(data>0){ printf("stack=[%d]=%d\n",S_top,data); } } printf("\n(case2)\n"); head = tail = NULL; add(200); add(400); add(300); add(100); printlist(head); printf("\n"); take(); take(); printlist(head); take(); printlist(head); printf("\n"); take(); printlist(head); printf("*/\n"); } void printstack(int *stack){ int i = 0; while(i<S_top){ printf("stack[%d] = %d ",i,stack[i]); i++; } printf("\n"); } void printlist(LIST *head){ LIST *p; p = head; if(p==NULL) { printf("printlist list end(head = %p)\n",p); } printf("print out from the head(head = %p)\n",head); while(p!=NULL){ printf("p=%p,(p->data=%d,p->next=%p)\n",p,p->data,p->next); if(p->next != NULL){ p=p->next; } else { break; } } }
C
#include "simple_buf_alloc.h" simple_buf_t * simple_buf_alloc(simple_buf_t **pp_buf_freelist, size_t suggested_size) { simple_buf_t *list_item = (*pp_buf_freelist); if (list_item) { (*pp_buf_freelist) = list_item->_next; } else { list_item = malloc(suggested_size); list_item->_base = (char *)(list_item + 1); list_item->_len = suggested_size - sizeof(simple_buf_t); list_item->_next = 0; } return list_item; } void simple_buf_free(simple_buf_t **pp_buf_freelist, char *buf) { if (buf) { simple_buf_t *list_item = (simple_buf_t *)(buf - sizeof(simple_buf_t)); if (list_item) { list_item->_next = (*pp_buf_freelist); (*pp_buf_freelist) = list_item; } } } void simple_buf_freelist_clear(simple_buf_t **pp_buf_freelist) { simple_buf_t *list_item = 0; while(list_item = (*pp_buf_freelist)) { (*pp_buf_freelist) = list_item->_next; free(list_item); } } /** -- EOF -- **/
C
#include <stdio.h> main() { hola(); printf("Hola, Mundo\n"); chau(); } #include <stdio.h> int hola() { printf("Hola\n"); } int chau() { printf("Chau\n"); }
C
bool isMonotonic(int* A, int ASize) { int i,cnt=0; for(i=0;i<ASize-1;i++) { if(A[i]<=A[i+1]) { cnt++; } } if(cnt==ASize-1) return true; cnt=0; for(i=0;i<ASize-1;i++) { if(A[i]>=A[i+1]) { cnt++; } } if(cnt==ASize-1) return true; return false; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* handle_unsigned_int.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: alcornea <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/10 23:49:14 by alcornea #+# #+# */ /* Updated: 2017/01/11 16:48:26 by alcornea ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void unsigned_long_long_length(va_list arg, int *value, char *get, t_arg mod) { unsigned long long num; char *str; num = va_arg(arg, unsigned long long); g_nb = 1; str = convert_llu_to_ascii(num, 10); str = handle_int_precision(str, mod); if (mod.precision == 0 && num == 0 && ft_strchr(get, '.')) str[0] = '\0'; str = handle_int_width(str, mod); ft_putstr(str); *value += my_strlen(str); } void unsigned_size_t_length(va_list arg, int *value, char *get, t_arg mod) { size_t num; char *str; num = va_arg(arg, size_t); g_nb = 1; str = convert_size_t_to_ascii(num, 10); str = handle_int_precision(str, mod); if (mod.precision == 0 && num == 0 && ft_strchr(get, '.')) str[0] = '\0'; str = handle_int_width(str, mod); ft_putstr(str); *value += my_strlen(str); } void uintmax_t_length(va_list arg, int *value, char *get, t_arg mod) { uintmax_t num; char *str; num = va_arg(arg, uintmax_t); g_nb = 1; str = convert_uintmax_t_to_ascii(num, 10); str = handle_int_precision(str, mod); if (mod.precision == 0 && num == 0 && ft_strchr(get, '.')) str[0] = '\0'; str = handle_int_width(str, mod); ft_putstr(str); *value += my_strlen(str); } void convert_unsigned_int(va_list arg, int *value, char *get, t_arg mod) { unsigned int num; char *str; num = va_arg(arg, unsigned int); g_nb = 1; str = convert_u_to_ascii(num, 10); str = handle_int_precision(str, mod); if (mod.precision == 0 && num == 0 && ft_strchr(get, '.')) str[0] = '\0'; str = handle_int_width(str, mod); ft_putstr(str); *value += my_strlen(str); } void handle_uns_int(va_list arg, int *value, char *get, t_arg mod) { if (mod.len_ll) unsigned_long_long_length(arg, value, get, mod); else if (mod.len_l) unsigned_l_len(arg, value, get, mod); else if (mod.len_hh) unsign_char_len(arg, value, get, mod); else if (mod.len_j) uintmax_t_length(arg, value, get, mod); else if (mod.len_z) unsigned_size_t_length(arg, value, get, mod); else convert_unsigned_int(arg, value, get, mod); }
C
#include "structs.h" int ft_find_unassigned_location(t_matrix *m, t_pos *p) { p->row = 0; while (p->row < m->rows) { p->col = 0; while (p->col < m->cols) { if (m->values[p->row][p->col] == 0) return (1); p->col++; } p->row++; } return (0); }
C
//Program to evaluate a postfix expression. #include<stdio.h> #include<math.h> int top=-1,top2=-1,stack2[50]; char stack[50],post[50],infix[50]; int ops(int x,int y,char op); void push(char ele); void push2(int ele); char pop(); int pop2(); int isp(char ch); int icp(char c); void postfix(); void main() { int i=0,len,value,num,x,y,t; char op,item; printf("Enter a infix expression:"); scanf("%s",infix); postfix(); while(post[i]!='\0') i++; post[i]='#'; post[++i]='\0'; len=i; i=0; while(post[i]!='\0') { item=post[i++]; while(item!='#') { if(isalnum(item)) { printf("Enter value of %c:",item); scanf("%d",&num); push2(num); } else { op=item; y=pop2(); x=pop2(); t=ops(x,y,op); push2(t); } item=post[i++]; } } value=pop2(); printf("Value is %d.\n",value); } //Function to do operation. int ops(int x,int y,char op) { int c; switch(op) { case '^':c=pow(x,y); break; case '*':c=x*y; break; case '/':c=x/y;; break; case '+':c=x+y; break; case '-':c=x-y; break; } return c; } //Function to convert infix to post fix. void postfix() { int i=0,j=0,k=0; char item,x; push('('); while(infix[k]!='\0') //length k++; infix[k]=')'; infix[k+1]='\0'; while(infix[i]!='\0') { while(top>-1) { item=infix[i++]; if(isalnum(item)) { post[j]=item; j++; } else if(item==')') { x=pop(); while(x!='(') { post[j]=x; j++; x=pop(); } } else if(isp(stack[top])>=icp(item)) { x=pop(); while(isp(x)>=icp(item)) { post[j]=x; j++; x=pop(); } push(x); push(item); } else if(isp(stack[top])<icp(item)) { push(item); } else printf("Invalid expression.\n"); } } post[j]='\0'; printf("The postfix expression is as follows:\n"); __fpurge(stdin); puts(post); } //Function to push character elements. void push(char ele) { if(top>50) printf("Stack overflow!!\n"); else { top++; stack[top]=ele; } } //Function to push integer elements. void push2(int ele) { if(top2>50) printf("Stack overflow!!\n"); else { top2++; stack2[top2]=ele; } } //Function to pop character elements char pop() { char ele; if(top<-1) printf("Stack underflow!!\n"); else { ele=stack[top]; top--; return ele; } } //Function to pop integer elements int pop2() { int ele; if(top2<-1) printf("Stack underflow!!\n"); else { ele=stack2[top2]; top2--; return ele; } } //ISP int isp(char ch) { switch(ch) { case '^':return 3; break; case '*':return 2; break; case '/':return 2; break; case '+':return 1; break; case '-':return 1; break; case ')':return 0; break; } } //ICP int icp(char c) { switch(c) { case '^':return 4; break; case '*':return 2; break; case '/':return 2; break; case '+':return 1; break; case '-':return 1; break; case '(':return 4; break; } }
C
#include<stdio.h> #include<stdlib.h> struct Array { int *A; int size; }object; void init(int size) { object.size = size; object.A = (int *)malloc(object.size * sizeof(int)); int i; for(i=0;i<object.size;i++) { printf("Enter the Element\n"); scanf("%d",&object.A[i]); } } void maximumElement() { int max,i; for(i=0;i<object.size;i++) { if(max<object.A[i]) { max = object.A[i]; } } printf("Maximum Element of Array:%d\n",max); } void minimumElement() { int min,i; for(i=0;i<object.size;i++) { if(min>object.A[i]) { min = object.A[i]; } } printf("Minimum Element of Array:%d\n",min); } int main() { int size; printf("Enter the Size of Array\n"); scanf("%d",&size); init(size); maximumElement(); minimumElement(); }
C
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char** argv) { if(argc < 2) { printf("%s <dir1> ... <dirN>\n", argv[0]); return 1; } for(int i = 1; i < argc; ++i) { pid_t chld = fork(); if(chld == 0) { printf("%d:\n", getpid()); execlp("ls", "ls", argv[i], NULL); } else if (chld == -1) printf("fork fallita\n"); int status; wait(&status); printf("\n"); } return 0; }
C
#include <stdio.h> #include "domainOferta.h" #include <errno.h> #include <string.h> #include <assert.h> void validate(Oferta *off, char erori[]) { char idErr[] = "Id invalid!\n", typeErr[] = "Tip invalid!\n", priceErr[] = "Pret invalid!\n", dateErr[] = "Data invalida!\n"; errno = 0; if (off->id < 0) { strcat(erori,idErr); errno = EINVAL; } if (strcmp(off->type, "munte") != 0 && strcmp(off->type, "mare") != 0 && strcmp(off->type, "citiy break") != 0) { strcat(erori, typeErr); errno = EINVAL; } if (off->price < 0) { strcat(erori, priceErr); errno = EINVAL; } if (off->date < 1 || off->date>31) { strcat(erori, dateErr); errno = EINVAL; } } void testValidate() { char erori[200] = ""; Oferta* oferta1 = create(-1, "munte", "Himalaya", -18, 123); validate(oferta1, erori); assert(strcmp(erori, "Id invalid!\nData invalida!\n")==0); Oferta* oferta2 = create(1, "munte", "Himalaya", 18, 134); strcpy(erori, ""); validate(oferta2, erori); assert(strlen(erori) == 0); Oferta* oferta3 = create(1, "dfds", "Himalaya", 18, -23); validate(oferta3, erori); assert(strcmp(erori, "Tip invalid!\nPret invalid!\n") == 0); destruct(oferta1); destruct(oferta2); destruct(oferta3); }
C
#include <stdlib.h> #include <stdio.h> #include "mem.h" #include "timer.h" #include "flexstack.h" #define LENGTH 10 #define RESIZE_LENGTH 15 int main() { int i; int data; flexstack_t stack; timer_t timer = timer_new(); timer_start(timer); stack = flexstack_new(LENGTH,sizeof(int)); for(i = 0;i < LENGTH; i++) { int *p; NEW(p); *p = i + 1; // array_put(array,i,p); flexstack_push(stack,p); } for(i = 0;i < LENGTH; i++) { data = *(int *)flexstack_pop(stack); printf("item %d:%d\n",i,data); } printf("program time:%f(s)\n",timer_elapsedTime(timer)); }
C
#include <stdbool.h> #include <string.h> #include "i2c.h" #include "gpio.h" #define BUFFER_SIZE 256 #define WRITE 0 #define TIMINGR_CLEAR_MASK 0xF0FFFFFFU typedef struct { uint16_t addr; uint8_t buf[32]; size_t n; } i2c_msg; static I2C_TypeDef *handle; static void init_sda_pin() { gpio_af_init(I2C_SDA_GPIO_PORT, I2C_SDA_PIN, GPIO_HIGH_SPEED, GPIO_OPENDRAIN, I2C_SDA_AF); } static void init_scl_pin() { gpio_af_init(I2C_SCL_GPIO_PORT, I2C_SCL_PIN, GPIO_HIGH_SPEED, GPIO_OPENDRAIN, I2C_SCL_AF); } static void i2c_enable() { SET_BIT(handle->CR1, I2C_CR1_PE); } static void i2c_set_timing(){ handle->TIMINGR = 0x10909CEC & TIMINGR_CLEAR_MASK; } static void i2c_start_clock(){ SET_BIT(RCC->APB1ENR1, RCC_APB1ENR1_I2C1EN); } int i2c_init(void) { init_sda_pin(); init_scl_pin(); handle = I2C1; i2c_start_clock(); i2c_set_timing(); i2c_enable(); return 0; } int i2c_is_ready(uint16_t addr) { return 1; } static void start_condition(){ SET_BIT(handle->CR2, I2C_CR2_START); } static void set_slave_addr(uint8_t addr) { MODIFY_REG(handle->CR2, I2C_CR2_SADD_Msk, addr << 1); } static void set_write() { CLEAR_BIT(handle->CR2, I2C_CR2_RD_WRN); } static void set_n_bytes(size_t n) { MODIFY_REG(handle->CR2, I2C_CR2_NBYTES_Msk, n << I2C_CR2_NBYTES_Pos); } static void wait_for_dr_empty(){ //I2C_FLAG_TXIS: Data register empty flag (1 means empty) while(READ_BIT(handle->ISR, I2C_ISR_TXIS) == RESET) ; } static void transmit_byte(uint8_t byte) { // Write data to DR handle->TXDR = byte; } static void wait_for_byte_transfer_finished() { //I2C_FLAG_TC: Transfer complete flag (1 means finished) while(READ_BIT(handle->ISR, I2C_ISR_TC) == RESET) ; } static void stop_condition(){ SET_BIT(handle->CR2, I2C_CR2_STOP); } int i2c_master_transmit(uint16_t addr, uint8_t *buf, size_t n) { // No DMA set_slave_addr(addr); set_write(); set_n_bytes(n); start_condition(); for (uint8_t i = 0; i < n; i++) { wait_for_dr_empty(); transmit_byte(buf[i]); } wait_for_dr_empty(); wait_for_byte_transfer_finished(); stop_condition(); return 0; }
C
/* * -------------------------------------- * Ŭ ȣ ( #2) * * -------------------------------------- */ #include <stdio.h> int gcd(int,int); int main(void) { int a,b; printf(" Էϼ. : "); scanf("%d %d",&a,&b); printf("ִ=%d\n",gcd(a,b)); return 0; } int gcd(int m,int n) { if (n==0) return m; else return gcd(n,m % n); }
C
/*题目:八进制转换为十进制*/ #include<stdio.h> #include<stdlib.h> int main() { int n=0,i=0; char s[20]; printf("请输入一个8进制数:\n"); gets(s); while(s[i]!='\0'){ n=n*8+s[i]-'0'; i++; } printf("刚输入的8进制数转化为十进制为\n%d\n",n); return 0; }
C
// hello.c // compile gcc hello.c // run ./a.out #include <stdio.h> int main(){ printf("********************* Hello World ***********************************\n"); printf("* from *\n"); printf("* GGGGGGGGG BBBBBB PPPPPP MM MM *\n"); printf("* GGGGGGGGG BBBBBB PPPPPP MM MM MM MM *\n"); printf("* GG BB BB PP PP MM MM MM MM *\n"); printf("* GG BB BB PP PP MM MM MM MM *\n"); printf("* GG GGGGGG BBBBBB PPPPPP MM MM MM MM *\n"); printf("* GG GGGGGG BBBBBB PPPPPP MM MM MM MM *\n"); printf("* GG GG BB BB PP MM MM MM MM *\n"); printf("* GG GG BB BB PP MM MM MM MM *\n"); printf("* GGGGGGGGG BBBBBB PP MM MM MM MM *\n"); printf("* GGGGGGGGG BBBBBB PP MM MM MM *\n"); printf("*********************************************************************\n"); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> const int MIN_BLOCK_SIZE = 128; const int MAX_BLOCK_SIZE = 512; const int MIN_BLOCKS = 1024; const int MAX_BLOCKS = 128*1024; const int MAX_NUM_FILES = 256; int is_power2(int n){ if(n == 0) return 0; while((n & 1) == 0){ n >>= 1; } return n == 1; } int main(int argc, char** argv){ if(argc != 4 && argc != 3){ fprintf(stderr,"Usage: ssfs_mkdsk num_blocks block_size name(optional)\n"); return 64; } int blocks = atoi(argv[1]); int block_size = atoi(argv[2]); char* name = argv[3]; //Do we need to support disk names with spaces? if(blocks < MIN_BLOCKS || blocks > MAX_BLOCKS || !is_power2(blocks)){ fprintf(stderr, "num_blocks must be a power of 2 between %d and %d\n",MIN_BLOCKS,MAX_BLOCKS); return 64; } if(block_size < MIN_BLOCK_SIZE || block_size > MAX_BLOCK_SIZE || !is_power2(block_size)){ fprintf(stderr, "block_size must be a power of 2 between %d and %d\n",MIN_BLOCK_SIZE, MAX_BLOCK_SIZE); return 64; } int total_size = blocks * block_size; if(!name) name = "DISK"; int disk_fd = open(name,O_WRONLY | O_CREAT); // TODO: intialize free block list, block and block size data and inodes... int sizes[] = {blocks, block_size}; write(disk_fd, sizes, sizeof(sizes)); int negone = -1; int zero = 0; int one = 1; int i; for(i = 0; i < 256; i++){ write(disk_fd, &negone, 4); } int b = 0; int numBlocksInUse = ceil((1032 + blocks/8.0) / block_size); char partial = 0; for(b = 0; b < blocks; b++){ if(b <= numBlocksInUse) partial |= (1 << (b % 8)); if((b % 8 == 7)){ write(disk_fd, &partial, 1); partial = 0; } } for(i = 0; i < total_size - 8 - 1024 - blocks/8; i++){ write(disk_fd,"\7",1); } return 0; }