repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
cvxgrp/coneos
coneOSdense/normalize.h
<filename>coneOSdense/normalize.h #ifndef NORMAL_H_GUARD #define NORMAL_H_GUARD #define MIN_SCALE 1e-2 #define MAX_SCALE 1e3 void normalize(Data * d, Work * w, Cone * k){ double * D = coneOS_calloc(d->m, sizeof(double)); double * E = coneOS_calloc(d->n, sizeof(double)); int i, j, count; double wrk; // loses consistency with coneOSsparse: w->scale = fmax( fmin( sqrt( d->n * d->m / d->Anz ) , MAX_SCALE) , 1); // calculate row norms for(i = 0; i < d->m; ++i){ D[i] = cblas_dnrm2(d->n,&(d->Ax[i]),d->m); } // mean of norms of rows across each cone count = k->l+k->f; for(i = 0; i < k->qsize; ++i) { wrk = 0; /* for (j = count; j < count + k->q[i]; ++j){ wrk = fmax(wrk, D[j]); } */ wrk = 0; for (j = count; j < count + k->q[i]; ++j){ wrk += D[j]; } wrk /= k->q[i]; for (j = count; j < count + k->q[i]; ++j){ D[j] = wrk; } count += k->q[i]; } for (i=0; i < k->ssize; ++i) { wrk = 0; /* for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ wrk = fmax(wrk, D[j]); } */ for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ wrk += D[j]*D[j]; } wrk = sqrt(wrk); wrk /= (k->s[i]); for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ D[j] = wrk; } count += (k->s[i])*(k->s[i]); } for (i=0; i<d->m; ++i){ if (D[i] < MIN_SCALE) D[i] = MIN_SCALE; else if (D[i] > MAX_SCALE) D[i] = MAX_SCALE; } // scale the rows with D for(i = 0; i < d->m; ++i){ cblas_dscal(d->n,1.0/D[i],&(d->Ax[i]),d->m); } // calculate and scale by col norms, E for (i = 0; i < d->n; ++i){ E[i] = cblas_dnrm2(d->m,&(d->Ax[i*d->m]),1); if (E[i] < MIN_SCALE) E[i] = MIN_SCALE; if (E[i] > MAX_SCALE) E[i] = MAX_SCALE; cblas_dscal(d->m,1.0/E[i],&(d->Ax[i*d->m]),1); } // scale b for (i = 0; i < d->m; ++i){ d->b[i] /= D[i]; } w->sc_b = 1/fmax(calcNorm(d->b,d->m),MIN_SCALE); scaleArray(d->b, w->sc_b, d->m); // scale c for (i = 0; i < d->n; ++i){ d->c[i] /= E[i]; } double meanNormRowA = 0.0; for(i = 0; i < d->m; ++i){ meanNormRowA += cblas_dnrm2(d->n,&(d->Ax[i]),d->m)/d->m; } w->sc_c = meanNormRowA/fmax(calcNorm(d->c,d->n),MIN_SCALE); scaleArray(d->c, w->sc_c, d->n); w->D = D; w->E = E; // heuristic scaling factor scaleArray(d->Ax,w->scale,d->Anz); scaleArray(d->b,w->scale,d->m); scaleArray(d->c,w->scale,d->n); /* coneOS_printf("norm D is %4f\n", calcNorm(D,d->m)); coneOS_printf("norm E is %4f\n", calcNorm(E,d->n)); coneOS_printf("norm A is %4f\n", calcNorm(d->Ax,d->Anz)); coneOS_printf("norm b is %4f\n", calcNorm(d->b,d->m)); coneOS_printf("norm c is %4f\n", calcNorm(d->c,d->n)); */ } /* inline double calcScaledNormDiff(double * a, double * b, Data * d, Work * w) { double nmDiff = 0.0, tmp; double * D = w->D; double * E = w->E; int i; for (i = 0; i < d->n; ++i){ tmp = (a[i] - b[i])/(E[i] * w->sc_b); nmDiff += tmp * tmp; } for (i = 0; i < d->m; ++i){ tmp = (a[i + d->n] - b[i + d->n])/(D[i] * w->sc_c); nmDiff += tmp * tmp; } tmp = a[w->l-1] - b[w->l-1]; nmDiff += tmp * tmp; return sqrt(nmDiff); } */ void unNormalize(Data *d, Work * w, Sol * sol){ int i; double * D = w->D; double * E = w->E; for (i = 0; i < d->n; ++i){ sol->x[i] /= (E[i] * w->sc_b); } for (i = 0; i < d->m; ++i){ sol->y[i] /= (D[i] * w->sc_c); } for (i = 0; i < d->m; ++i){ sol->s[i] *= D[i]/(w->sc_b * w->scale); } for (i = 0; i < d->n; ++i){ d->c[i] *= E[i]/(w->sc_c * w->scale); } for (i = 0; i < d->m; ++i){ d->b[i] *= D[i]/(w->sc_b * w->scale); } for (i = 0; i < d->n; ++i){ cblas_dscal(d->m,E[i],&(d->Ax[i*d->m]),1); } for(i = 0; i < d->m; ++i){ cblas_dscal(d->n,D[i],&(d->Ax[i]),d->m); } scaleArray(d->Ax,1.0/w->scale,d->Anz); } #endif
cvxgrp/coneos
coneOSsparse/linAlg.c
#include "linAlg.h" #include <math.h> /* * All basic linear operations are inlined (and further optimized) by the * compiler. If compiling without optimization, causes code bloat. */ inline void _accumByAtrans(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); inline void _accumByA(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); // x = b*a inline void setAsScaledArray(double *x, const double * a,const double b,int len) { int i; for( i=0;i<len;++i ) x[i] = b*a[i]; } // a*= b inline void scaleArray(double * a,const double b,int len){ int i; for( i=0;i<len;++i) a[i]*=b; } // x'*y inline double innerProd(const double * x, const double * y, int len){ int i; double ip = 0.0; for ( i=0;i<len;++i){ ip += x[i]*y[i]; } return ip; } // ||v||_2^2 inline double calcNormSq(const double * v,int len){ int i; double nmsq = 0.0; for ( i=0;i<len;++i){ nmsq += v[i]*v[i]; } return nmsq; } // ||v||_2 inline double calcNorm(const double * v,int len){ return sqrt(calcNormSq(v, len)); } inline double calcNormInf(const double *a, int l){ double tmp, max = 0.0; int i; for (i=0; i<l; ++i){ tmp = fabs(a[i]); if(tmp > max) max = tmp; } return max; } // saxpy a += sc*b inline void addScaledArray(double * a, const double * b, int n, const double sc){ int i; for (i=0;i<n;++i){ a[i] += sc*b[i]; } } inline double calcNormDiff(const double *a, const double *b, int l) { double nmDiff = 0.0, tmp; int i; for ( i=0; i<l; ++i){ tmp = (a[i] - b[i]); nmDiff += tmp * tmp; } return sqrt(nmDiff); } inline double calcNormInfDiff(const double *a, const double *b, int l) { double tmp, max = 0.0; int i; for ( i=0; i<l; ++i){ tmp = fabs(a[i] - b[i]); if(tmp > max) max = tmp; } return max; } inline void accumByAtrans(Data * d, const double *x, double *y) { _accumByAtrans(d->n, d->Ax, d->Ai, d->Ap, x, y); } inline void accumByA(Data * d, const double *x, double *y) { _accumByA(d->n, d->Ax, d->Ai, d->Ap, x, y); } inline void _accumByAtrans(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y) { /* y = A'*x A in column compressed format parallelizes over columns (rows of A') */ int p, j; int c1, c2; double yj; #pragma omp parallel for private(p,c1,c2,yj) for (j = 0 ; j < n ; j++) { yj = y[j]; c1 = Ap[j]; c2 = Ap[j+1]; for (p = c1 ; p < c2 ; p++) { yj += Ax[p] * x[ Ai[p] ] ; } y[j] = yj; } } inline void _accumByA(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y) { /*y = A*x A in column compressed format this parallelizes over columns and uses pragma atomic to prevent concurrent writes to y */ int p, j; int c1, c2; double xj; //#pragma omp parallel for private(p,c1,c2,xj) for (j = 0 ; j < n ; j++) { xj = x[j]; c1 = Ap[j]; c2 = Ap[j+1]; for (p = c1 ; p < c2 ; p++) { //#pragma omp atomic y [Ai[p]] += Ax [p] * xj ; } } }
cvxgrp/coneos
coneOSdense/cones.h
<reponame>cvxgrp/coneos #ifndef CONES_H_GUARD #define CONES_H_GUARD #include <string.h> typedef struct Cone_t { int f; /* number of linear equality constraints */ int l; /* length of LP cone */ int *q; /* array of second-order cone constraints */ int qsize; /* length of SOC array */ int *s; /* array of SD constraints */ int ssize; /* length of SD array */ } Cone; #include "coneOS.h" void projCone(double *x,Cone *k, Work * w); #endif
cvxgrp/coneos
coneOSsparse/coneOS.c
<reponame>cvxgrp/coneos /* coneos 1.0 */ #include "coneOS.h" #include "normalize.h" static int _lineLen_; // constants and data structures static const char* HEADER[] = { " Iter ", " pri res ", " dua res ", " rel gap ", " pri obj ", " dua obj ", " kappa ", " time (s)", }; static const int HEADER_LEN = 8; static inline void updateDualVars(Data * d, Work * w); static inline void projectCones(Data * d,Work * w,Cone * k, int iter); static inline void sety(Data * d, Work * w, Sol * sol); static inline void setx(Data * d, Work * w, Sol * sol); static inline void sets(Data * d, Work * w, Sol * sol); static inline void setSolution(Data * d, Work * w, Sol * sol, Info * info); static inline void getInfo(Data * d, Work * w, Sol * sol, Info * info, struct residuals * r); static inline void printSummary(Data * d,Work * w,int i, struct residuals *r); static inline void printHeader(Data * d, Work * w, Cone * k); static inline void printFooter(Data * d, Info * info, Work * w); static inline void freeWork(Work * w); static inline void projectLinSys(Data * d,Work * w, int iter); static inline Work * initWork(Data * d, Cone * k); static inline int converged(Data * d, Work * w, struct residuals * r, int iter); static inline int exactConverged(Data * d, Work * w, struct residuals * r, int iter); #define PRINT_INTERVAL 100 #define CONVERGED_INTERVAL 20 /* coneOS returns one of the following integers: */ /* (zero should never be returned) */ #define FAILURE -4 #define INDETERMINATE -3 #define INFEASIBLE -2 // primal infeasible, dual unbounded #define UNBOUNDED -1 // primal unbounded, dual infeasible #define SOLVED 1 int coneOS(Data * d, Cone * k, Sol * sol, Info * info) { if(d == NULL || k == NULL) { return FAILURE; } tic(); info->stint = 0; // not yet converged int i; struct residuals r = {-1, -1, -1, -1, -1, -1, -1}; Work * w = initWork(d,k); if(d->VERBOSE) { printHeader(d, w, k); } /* coneOS: */ for (i=0; i < d->MAX_ITERS; ++i){ memcpy(w->u_prev, w->u, w->l*sizeof(double)); projectLinSys(d,w,i); projectCones(d,w,k,i); updateDualVars(d,w); info->stint = converged(d,w,&r,i); if (info->stint != 0) break; if (i % PRINT_INTERVAL == 0){ if (d->VERBOSE) printSummary(d,w,i,&r); } } if(d->VERBOSE) printSummary(d,w,i,&r); setSolution(d,w,sol,info); if(d->NORMALIZE) unNormalize(d,w,sol); info->iter = i; getInfo(d,w,sol,info,&r); if(d->VERBOSE) printFooter(d, info, w); freeWork(w); return info->stint; } static inline int converged(Data * d, Work * w, struct residuals * r, int iter){ /* approximate convergence check: double tau = fabs(w->u[w->l-1]); // abs to prevent negative stopping tol double kap = fabs(w->v[w->l-1]); r->resPri = calcNormDiff(w->u, w->u_t, w->l); r->resDual = calcNormDiff(w->u, w->u_prev, w->l); r->tau = tau; r->kap = kap; if (fmin(tau,kap)/fmax(tau,kap) < 1e-6 && fmax(r->resPri, r->resDual) < d->EPS_ABS*(tau+kap)){ return 1; } */ if (iter % CONVERGED_INTERVAL == 0) { return exactConverged(d,w,r,iter); } return 0; } static inline int exactConverged(Data * d, Work * w, struct residuals * r, int iter){ double * pr = coneOS_calloc(d->m,sizeof(double)); double * dr = coneOS_calloc(d->n,sizeof(double)); double * Axs = coneOS_calloc(d->m,sizeof(double)); double * ATy = coneOS_calloc(d->n,sizeof(double)); double tau = fabs(w->u[w->l-1]); double kap = fabs(w->v[w->l-1]); double * x = w->u, * y = &(w->u[d->n]); double * D = w->D, * E = w->E; int i; /* // requires mult by A: double * s = &(w->v[d->n]); accumByA(d,x,Axs); // Axs = Ax addScaledArray(Axs,s,d->m,1.0); // Axs = Ax + s memcpy(pr, Axs, d->m * sizeof(double)); // pr = Ax + s addScaledArray(pr,d->b,d->m,-tau); // pr = Ax + s - b * tau */ // does not require mult by A: memcpy(pr,&(w->u[d->n]),d->m * sizeof(double)); addScaledArray(pr,&(w->u_prev[d->n]),d->m,d->ALPH-2); addScaledArray(pr,&(w->u_t[d->n]),d->m,1-d->ALPH); addScaledArray(pr,d->b, d->m, w->u_t[w->l-1] - tau) ; // pr = Ax + s - b * tau memcpy(Axs, pr, d->m * sizeof(double)); addScaledArray(Axs, d->b, d->m, tau); // Axs = Ax + s double cTx = innerProd(x,d->c,d->n); if (d->NORMALIZE) { kap /= (w->scale * w->sc_c * w->sc_b); for (i = 0; i < d->m; ++i) { pr[i] *= D[i]/(w->sc_b * w->scale); Axs[i] *= D[i]/(w->sc_b * w->scale); } cTx /= (w->scale * w->sc_c * w->sc_b); } r->tau = tau; r->kap = kap; double nmAxs = calcNorm(Axs,d->m); r->resPri = cTx < 0 ? w->nm_c * nmAxs / -cTx : NAN; //coneOS_printf("unbounded cert: %4e\n", w->nm_c * nmAxs / (1+w->nm_b) / -cTx); if (r->resPri < d->EPS_ABS) { return UNBOUNDED; } accumByAtrans(d,y,ATy); // ATy = A'y memcpy(dr, ATy, d->n * sizeof(double)); addScaledArray(dr,d->c,d->n,tau); // dr = A'y + c * tau double bTy = innerProd(y,d->b,d->m); if (d->NORMALIZE) { for (i = 0; i < d->n; ++i) { dr[i] *= E[i]/(w->sc_c * w->scale); ATy[i] *= E[i]/(w->sc_c * w->scale); } bTy /= (w->scale * w->sc_c * w->sc_b); } double nmATy = calcNorm(ATy,d->n); r->resDual = bTy < 0 ? w->nm_b * nmATy / -bTy : NAN; //coneOS_printf("infeas cert: %4e\n", w->nm_b * nmATy / (1+w->nm_c) / - bTy ); if (r->resDual < d->EPS_ABS) { return INFEASIBLE; } r->relGap = NAN; int status = 0; if (tau > kap) { double rpri = calcNorm(pr,d->m) / (1+w->nm_b) / tau; double rdua = calcNorm(dr,d->n) / (1+w->nm_c) / tau; double gap = fabs(cTx + bTy) / (tau + fabs(cTx) + fabs(bTy)); r->resPri = rpri; r->resDual = rdua; r->relGap = gap; r->cTx = cTx / tau; r->bTy = bTy / tau; // coneOS_printf("primal resid: %4e, dual resid %4e, pobj %4e, dobj %4e, gap %4e\n", rpri,rdua,cTx,-bTy,gap); // coneOS_printf("primal resid: %4e, dual resid %4e, gap %4e\n",rpri,rdua,gap); if (fmax(fmax(rpri,rdua),gap) < d->EPS_ABS) { status = SOLVED; } } else { r->cTx = NAN; r->bTy = NAN; } coneOS_free(dr); coneOS_free(pr); coneOS_free(Axs); coneOS_free(ATy); return status; } static inline void getInfo(Data * d, Work * w, Sol * sol, Info * info, struct residuals * r){ double * x = sol->x, * y = sol->y, * s = sol->s; double * dr = coneOS_calloc(d->n,sizeof(double)); double * pr = coneOS_calloc(d->m,sizeof(double)); accumByA(d,x,pr); // pr = Ax addScaledArray(pr,s,d->m,1.0); // pr = Ax + s accumByAtrans(d,y,dr); // dr = A'y double cTx = innerProd(x,d->c,d->n); double bTy = innerProd(y,d->b,d->m); info->pobj = cTx; info->dobj = -bTy; if (info->stint == SOLVED){ addScaledArray(pr,d->b,d->m,-1.0); // pr = Ax + s - b addScaledArray(dr,d->c,d->n,1.0); // dr = A'y + c info->relGap = fabs(cTx + bTy) / (1 + fabs(cTx) + fabs(bTy)); info->resPri = calcNorm(pr,d->m) / (1 + w->nm_b); info->resDual = calcNorm(dr,d->n) / (1+ w->nm_c); } else { if (info->stint == UNBOUNDED) { info->dobj = NAN; info->relGap = NAN; info->resPri = w->nm_c * calcNorm(pr,d->m) / -cTx ; info->resDual = NAN; scaleArray(x,-1/cTx,d->n); scaleArray(s,-1/cTx,d->m); info->pobj = -1; } else { info->pobj = NAN; info->relGap = NAN; info->resPri = NAN; info->resDual = w->nm_b * calcNorm(dr,d->n) / -bTy ; scaleArray(y,-1/bTy,d->m); info->dobj = -1; } } info->time = tocq(); coneOS_free(dr); coneOS_free(pr); } static inline Work * initWork(Data *d, Cone * k) { Work * w = coneOS_malloc(sizeof(Work)); w->nm_b = calcNorm(d->b, d->m); w->nm_c = calcNorm(d->c, d->n); //w->nm_b = calcNormInf(d->b, d->m); //w->nm_c = calcNormInf(d->c, d->n); //w->nm_Q = calcNormFroQ(d); if(d->NORMALIZE) { normalize(d,w,k); } else { w->D = NULL; w->E = NULL; w->sc_c = 1.0; w->sc_b = 1.0; w->scale = 1.0; } w->l = d->n+d->m+1; w->u = coneOS_calloc(w->l,sizeof(double)); w->u[w->l-1] = sqrt(w->l); w->v = coneOS_calloc(w->l,sizeof(double)); w->v[w->l-1] = sqrt(w->l); w->u_t = coneOS_calloc(w->l,sizeof(double)); w->u_prev = coneOS_calloc(w->l,sizeof(double)); w->h = coneOS_calloc((w->l-1),sizeof(double)); memcpy(w->h,d->c,d->n*sizeof(double)); memcpy(&(w->h[d->n]),d->b,d->m*sizeof(double)); w->g = coneOS_calloc((w->l-1),sizeof(double)); memcpy(w->g,w->h,(w->l-1)*sizeof(double)); /* initialize the private data: */ int status = privateInitWork(d, w); if (status < 0){ coneOS_printf("privateInitWork failure: %i\n",status); exit(-1); } //else coneOS_printf("privateInitWork success: %i\n",status); if (k->s){ /* eigenvector decomp workspace */ int i, nMax = 0; for (i=0; i < k->ssize; ++i){ if (k->s[i] > nMax) nMax = k->s[i]; } w->Xs = coneOS_calloc(nMax*nMax,sizeof(double)); w->Z = coneOS_calloc(nMax*nMax,sizeof(double)); w->e = coneOS_calloc(nMax,sizeof(double)); } else { w->Xs = NULL; w->Z = NULL; w->e = NULL; } solveLinSys(d,w,w->g, NULL, -1); scaleArray(&(w->g[d->n]),-1,d->m); w->gTh = innerProd(w->h, w->g, w->l-1); return w; } static inline void projectLinSys(Data * d,Work * w, int iter){ // ut = u + v memcpy(w->u_t,w->u,w->l*sizeof(double)); addScaledArray(w->u_t,w->v,w->l,1.0); scaleArray(w->u_t,d->RHO_X,d->n); addScaledArray(w->u_t,w->h,w->l-1,-w->u_t[w->l-1]); addScaledArray(w->u_t, w->h, w->l-1, -innerProd(w->u_t,w->g,w->l-1)/(w->gTh+1)); scaleArray(&(w->u_t[d->n]),-1,d->m); solveLinSys(d, w, w->u_t, w->u, iter); w->u_t[w->l-1] += innerProd(w->u_t,w->h,w->l-1); } static inline void freeWork(Work * w){ freePriv(w); if(w){ if(w->method) free(w->method); //called via malloc not mxMalloc if(w->Xs) coneOS_free(w->Xs); if(w->Z) coneOS_free(w->Z); if(w->e) coneOS_free(w->e); if(w->u) coneOS_free(w->u); if(w->v) coneOS_free(w->v); if(w->u_t) coneOS_free(w->u_t); if(w->u_prev) coneOS_free(w->u_prev); if(w->h) coneOS_free(w->h); if(w->g) coneOS_free(w->g); if(w->D) coneOS_free(w->D); if(w->E) coneOS_free(w->E); coneOS_free(w); } } void printSol(Data * d, Sol * sol, Info * info){ int i; coneOS_printf("%s\n",info->status); if (sol->x != NULL){ for ( i=0;i<d->n; ++i){ coneOS_printf("x[%i] = %4f\n",i, sol->x[i]); } } if (sol->y != NULL){ for ( i=0;i<d->m; ++i){ coneOS_printf("y[%i] = %4f\n",i, sol->y[i]); } } } static inline void updateDualVars(Data * d, Work * w){ int i; /* for(i = 0; i < d->n; ++i) { w->v[i] += w->u[i] - w->u_t[i]; } */ //for(i = 0; i < w->l; ++i) { if (fabs(d->ALPH - 1.0) < 1e-9) { // this is over-step parameter: //double sig = (1+sqrt(5))/2; double sig = 1.0; for(i = d->n; i < w->l; ++i) { w->v[i] += sig*(w->u[i] - w->u_t[i]); } } else { // this does not relax 'x' variable for(i = d->n; i < w->l; ++i) { w->v[i] += (w->u[i] - d->ALPH*w->u_t[i] - (1.0 - d->ALPH)*w->u_prev[i]); } } } static inline void projectCones(Data *d,Work * w,Cone * k, int iter){ int i; // this does not relax 'x' variable for(i = 0; i < d->n; ++i) { w->u[i] = w->u_t[i] - w->v[i]; } //for(i = 0; i < w->l; ++i){ for(i = d->n; i < w->l; ++i){ w->u[i] = d->ALPH*w->u_t[i] + (1-d->ALPH)*w->u_prev[i] - w->v[i]; } /* u = [x;y;tau] */ projCone(&(w->u[d->n]),k,w,iter); if (w->u[w->l-1]<0.0) w->u[w->l-1] = 0.0; } static inline int solved(Data * d, Sol * sol, Info * info, double tau){ strcpy(info->status,"Solved"); scaleArray(sol->x,1.0/tau,d->n); scaleArray(sol->y,1.0/tau,d->m); scaleArray(sol->s,1.0/tau,d->m); return SOLVED; } static inline int indeterminate(Data * d, Sol * sol, Info * info){ strcpy(info->status, "Indeterminate"); scaleArray(sol->x,NAN,d->n); scaleArray(sol->y,NAN,d->m); scaleArray(sol->s,NAN,d->m); return INDETERMINATE; } static inline int infeasible(Data * d, Sol * sol, Info * info){ strcpy(info->status,"Infeasible"); //scaleArray(sol->y,-1/ip_y,d->m); scaleArray(sol->x,NAN,d->n); scaleArray(sol->s,NAN,d->m); return INFEASIBLE; } static inline int unbounded(Data * d, Sol * sol, Info * info){ strcpy(info->status,"Unbounded"); //scaleArray(sol->x,-1/ip_x,d->n); scaleArray(sol->y,NAN,d->m); return UNBOUNDED; } static inline void setSolution(Data * d,Work * w,Sol * sol, Info * info){ setx(d,w,sol); sety(d,w,sol); sets(d,w,sol); if (info->stint == 0 || info->stint == SOLVED){ double tau = w->u[w->l-1]; double kap = fabs(w->v[w->l-1]); if (tau > d->UNDET_TOL && tau > kap){ info->stint = solved(d,sol,info,tau); } else{ if (calcNorm(w->u,w->l)<d->UNDET_TOL*sqrt(w->l)){ info->stint = indeterminate(d,sol,info); } else { double bTy = innerProd(d->b,sol->y,d->m); double cTx = innerProd(d->c,sol->x,d->n); if (bTy < cTx){ info->stint = infeasible(d,sol,info); } else{ info->stint = unbounded(d,sol,info); } } } } else if (info->stint == INFEASIBLE) { info->stint = infeasible(d,sol,info); } else { info->stint = unbounded(d,sol,info); } } static inline void sety(Data * d,Work * w, Sol * sol){ sol->y = coneOS_malloc(sizeof(double)*d->m); memcpy(sol->y, &(w->u[d->n]), d->m*sizeof(double)); } static inline void sets(Data * d,Work * w, Sol * sol){ sol->s = coneOS_malloc(sizeof(double)*d->m); memcpy(sol->s, &(w->v[d->n]), d->m*sizeof(double)); } static inline void setx(Data * d,Work * w, Sol * sol){ sol->x = coneOS_malloc(sizeof(double)*d->n); memcpy(sol->x, w->u, d->n*sizeof(double)); } static inline void printSummary(Data * d,Work * w,int i, struct residuals *r){ coneOS_printf("%*i|", (int)strlen(HEADER[0]), i); coneOS_printf(" %*.2e ", (int)strlen(HEADER[1])-1, r->resPri); coneOS_printf(" %*.2e ", (int)strlen(HEADER[2])-1, r->resDual); coneOS_printf(" %*.2e ", (int)strlen(HEADER[3])-1, r->relGap); if (r->cTx < 0) { coneOS_printf("%*.2e ", (int)strlen(HEADER[4])-1, r->cTx); } else { coneOS_printf(" %*.2e ", (int)strlen(HEADER[4])-1, r->cTx); } if (r->bTy >= 0) { coneOS_printf("%*.2e ", (int)strlen(HEADER[5])-1, -r->bTy); } else { coneOS_printf(" %*.2e ", (int)strlen(HEADER[5])-1, -r->bTy); } coneOS_printf(" %*.2e ", (int)strlen(HEADER[6])-1, r->kap); coneOS_printf(" %*.2e ", (int)strlen(HEADER[7])-1, tocq()/1e3); coneOS_printf("\n"); #ifdef MATLAB_MEX_FILE mexEvalString("drawnow;"); #endif } static inline void printHeader(Data * d, Work * w, Cone * k) { int i; _lineLen_ = -1; for(i = 0; i < HEADER_LEN; ++i) { _lineLen_ += strlen(HEADER[i]) + 1; } for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\nconeOS 1.0: %s\n", w->method); for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\nEPS = %.2e, ALPHA = %.2f, MAX_ITERS = %i, NORMALIZE = %i\n", d->EPS_ABS, d->ALPH, d->MAX_ITERS, d->NORMALIZE); coneOS_printf("variables n = %i, constraints m = %i, non-zeros in A = %i\n", d->n, d->m, d->Anz); int socVars = 0; for (int i=0;i<k->qsize;i++){ socVars += k->q[i]; } int sdVars = 0; for (int i=0;i<k->ssize;i++){ sdVars += k->s[i]*k->s[i]; } coneOS_printf("cones:\tzero/free vars: %i\n\tlinear vars: %i\n\tsoc vars: %i, soc blks: %i\n\tsd vars: %i, sd blks: %i\n\texp vars: %i\n\tdual exp vars: %i\n", k->f, k->l, socVars, k->qsize, sdVars,k->ssize, k->ep*3, k->ed*3); for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\n"); for(i = 0; i < HEADER_LEN - 1; ++i) { coneOS_printf("%s|", HEADER[i]); } coneOS_printf("%s\n", HEADER[HEADER_LEN-1]); for(i = 0; i < _lineLen_; ++i) { coneOS_printf("="); } coneOS_printf("\n"); } static inline void printFooter(Data * d, Info * info, Work * w) { int i; for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\nStatus: %s\n",info->status); if (info->iter == d->MAX_ITERS) { coneOS_printf("Hit MAX_ITERS, solution may be inaccurate\n"); } coneOS_printf("Time taken: %.4f seconds\n",info->time/1e3); for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\n"); if (info->stint == INFEASIBLE) { coneOS_printf("Certificate of primal infeasibility:\n"); coneOS_printf("|A'y|_2 * |b|_2 = %.4e\n", info->resDual); coneOS_printf("dist(y, K*) = 0\n"); coneOS_printf("b'y = %.4f\n", info->dobj); } else if (info->stint == UNBOUNDED) { coneOS_printf("Certificate of dual infeasibility:\n"); coneOS_printf("|Ax + s|_2 * |c|_2 = %.4e\n", info->resPri); coneOS_printf("dist(s, K) = 0\n"); coneOS_printf("c'x = %.4f\n", info->pobj); } else { coneOS_printf("Error metrics:\n"); coneOS_printf("|Ax + s - b|_2 / (1 + |b|_2) = %.4e\n",info->resPri); coneOS_printf("|A'y + c|_2 / (1 + |c|_2) = %.4e\n",info->resDual); coneOS_printf("|c'x + b'y| / (1 + |c'x| + |b'y|) = %.4e\n", info->relGap); coneOS_printf("dist(s, K) = 0, dist(y, K*) = 0, s'y = 0\n"); for(i = 0; i < _lineLen_; ++i) { coneOS_printf("-"); } coneOS_printf("\n"); coneOS_printf("c'x = %.4f, -b'y = %.4f\n",info->pobj, info->dobj); } for(i = 0; i < _lineLen_; ++i) { coneOS_printf("="); } coneOS_printf("\n"); }
cvxgrp/coneos
coneOSsparse/indirect/private.h
#ifndef PRIV_H_GUARD #define PRIV_H_GUARD #include "cs.h" #include "coneOS.h" #include <math.h> struct PRIVATE_DATA{ double *p; // cg iterate double *r; // cg residual double *x; double * Ap; double * tmp; double * Atx; int * Ati; int * Atp; }; #endif
cvxgrp/coneos
coneOSsparse/matlab/coneOS_mex.c
<reponame>cvxgrp/coneos #include "mex.h" #include "matrix.h" #include "coneOS.h" #include "linAlg.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* matlab usage: coneOS(data,cone,params); */ if (nrhs != 3){ mexErrMsgTxt("Three arguments are required in this order: data struct, cone struct, params struct"); } Data * d = mxMalloc(sizeof(Data)); Cone * k = mxMalloc(sizeof(Cone)); const mxArray *data = prhs[0]; const mxArray *A_mex = (mxArray *) mxGetField(data,0,"A"); if(A_mex == NULL) { coneOS_free(d); coneOS_free(k); mexErrMsgTxt("Data struct must contain a `A` entry."); } if (!mxIsSparse(A_mex)){ coneOS_free(d); coneOS_free(k); mexErrMsgTxt("Input matrix A must be in sparse format (pass in sparse(A))"); } const mxArray *b_mex = (mxArray *) mxGetField(data,0,"b"); if(b_mex == NULL) { coneOS_free(d); coneOS_free(k); mexErrMsgTxt("Data struct must contain a `b` entry."); } const mxArray *c_mex = (mxArray *) mxGetField(data,0,"c"); if(c_mex == NULL) { coneOS_free(d); coneOS_free(k); mexErrMsgTxt("Data struct must contain a `c` entry."); } const mxArray *cone = prhs[1]; const mxArray *params = prhs[2]; d->n = *(mxGetDimensions(c_mex)); d->m = *(mxGetDimensions(b_mex)); d->b = mxGetPr(b_mex); d->c = mxGetPr(c_mex); const mxArray *ALPH_mex = mxGetField(params,0,"ALPHA"); if (ALPH_mex == NULL) d->ALPH = 1.8; else d->ALPH = (double)*mxGetPr(ALPH_mex); const mxArray *RHO_X_mex = mxGetField(params,0,"RHO_X"); if (RHO_X_mex == NULL) d->RHO_X = 1e-3; else d->RHO_X = (double)*mxGetPr(RHO_X_mex); const mxArray *MAX_ITERS_mex = mxGetField(params,0,"MAX_ITERS"); if (MAX_ITERS_mex == NULL) d->MAX_ITERS = 2500; else d->MAX_ITERS = (int)*mxGetPr(MAX_ITERS_mex); const mxArray *EPS_ABS_mex = mxGetField(params,0,"EPS_ABS"); if (EPS_ABS_mex == NULL) d->EPS_ABS = 1e-3; else d->EPS_ABS = (double)*mxGetPr(EPS_ABS_mex); const mxArray *UNDET_TOL_mex = mxGetField(params,0,"UNDET_TOL"); if (UNDET_TOL_mex == NULL) d->UNDET_TOL = 1e-9; else d->UNDET_TOL = (double)*mxGetPr(UNDET_TOL_mex); const mxArray *VERBOSE_mex = mxGetField(params,0,"VERBOSE"); if (VERBOSE_mex == NULL) d->VERBOSE = 0; else d->VERBOSE = (int)*mxGetPr(VERBOSE_mex); const mxArray *NORMALIZE_mex = mxGetField(params,0,"NORMALIZE"); if (NORMALIZE_mex == NULL) d->NORMALIZE = 1; else d->NORMALIZE = (int)*mxGetPr(NORMALIZE_mex); k->f = (int)*mxGetPr(mxGetField(cone,0,"f")); k->l = (int)*mxGetPr(mxGetField(cone,0,"l")); mxArray * ep = mxGetField(cone,0,"ep"); if(ep) k->ep = (int)*mxGetPr(ep); else k->ep = 0; mxArray * ed = mxGetField(cone,0,"ed"); if(ed) k->ed = (int)*mxGetPr(ed); else k->ed = 0; double * q_mex = mxGetPr(mxGetField(cone,0,"q")); k->qsize = *(mxGetDimensions(mxGetField(cone,0,"q"))); int i; k->q = mxMalloc(sizeof(int)*k->qsize); for ( i=0; i < k->qsize; i++ ){ k->q[i] = (int)q_mex[i]; } double * s_mex = mxGetPr(mxGetField(cone,0,"s")); k->ssize = *(mxGetDimensions(mxGetField(cone,0,"s"))); k->s = mxMalloc(sizeof(int)*k->ssize); for ( i=0; i < k->ssize; i++ ){ k->s[i] = (int)s_mex[i]; } d->Anz = mxGetNzmax(A_mex); d->Ax = (double *)mxGetPr(A_mex); d->Ap = (int *)mxMalloc(sizeof(int)*d->Anz); d->Ai = (int *)mxMalloc(sizeof(int)*d->Anz); long * A_i = (long*)mxGetIr(A_mex); /* XXX fix this crap: */ for (i = 0; i < d->Anz; i++){ d->Ai[i] = (int)A_i[i]; } long * A_p = (long*)mxGetJc(A_mex); for (i = 0; i < (d->n)+1; i++) { d->Ap[i] = (int)A_p[i]; } Sol sol; Info info; int status = coneOS(d,k,&sol,&info); plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL); mxSetPr(plhs[0], sol.x); mxSetM(plhs[0], d->n); mxSetN(plhs[0], 1); plhs[1] = mxCreateDoubleMatrix(0, 0, mxREAL); mxSetPr(plhs[1], sol.y); mxSetM(plhs[1], d->m); mxSetN(plhs[1], 1); const char * infoFields[] = {"iter","status","pobj","dobj","resPri","resDual","relGap","time"}; const int numInfoFields = 8; mwSize one[1] = {1}; mxArray * xm; plhs[2] = mxCreateStructArray(1,one,numInfoFields,infoFields); mxSetField(plhs[2], 0, "status", mxCreateString(info.status)); xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "iter", xm); *mxGetPr(xm) = info.iter; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "pobj", xm); *mxGetPr(xm) = info.pobj; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "dobj", xm); *mxGetPr(xm) = info.dobj; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "resPri", xm); *mxGetPr(xm) = info.resPri; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "resDual", xm); *mxGetPr(xm) = info.resDual; xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "relGap", xm); *mxGetPr(xm) = info.relGap; //info.time is millisecs - return value in secs xm = mxCreateDoubleMatrix(1, 1, mxREAL); mxSetField(plhs[2], 0, "time", xm); *mxGetPr(xm) = info.time/1e3; if(k->q) coneOS_free(k->q); if(k->s) coneOS_free(k->s); if(d->Ap) coneOS_free(d->Ap); if(d->Ai) coneOS_free(d->Ai); if(d) coneOS_free(d); if(k) coneOS_free(k); return; }
cvxgrp/coneos
coneOSdense/linAlg.c
#include "coneOS.h" #include <cblas.h> #include <math.h> // x = b*a inline void setAsScaledArray(double *x, const double * a,const double b,int len) { int i; for( i=0;i<len;++i ) x[i] = b*a[i]; } // a*= b inline void scaleArray(double * a,const double b,int len){ //b_dscal(len,b,a,1); cblas_dscal(len,b,a,1); } // x'*y inline double innerProd(const double * x, const double * y, int len){ //return b_ddot(len, x,1,y,1); return cblas_ddot(len, x,1,y,1); } // ||v||_2 inline double calcNorm(const double * v,int len){ //return b_dnrm2(len, v, 1); return cblas_dnrm2(len, v, 1); } inline double calcNormInf(const double *a, int l){ double tmp, max = 0.0; int i; for ( i=0; i<l; ++i){ tmp = fabs(a[i]); if(tmp > max) max = tmp; } return max; } // ||v||_2^2 inline double calcNormSq(const double * v,int len){ double nrm = calcNorm(v,len); return nrm*nrm; } // daxpy a += sc*b inline void addScaledArray(double * a, const double * b, int n, const double sc){ //b_daxpy(n, sc, b, 1, a, 1); cblas_daxpy(n, sc, b, 1, a, 1); } inline double calcNormDiff(const double *a,const double *b, int l) { double nmDiff = 0.0, tmp; int i; for ( i=0; i<l; ++i ){ tmp = (a[i] - b[i]); nmDiff += tmp * tmp; } return sqrt(nmDiff); } inline double calcNormInfDiff(const double *a, const double *b, int l) { double tmp, max = 0.0; int i; for ( i=0; i<l; ++i){ tmp = fabs(a[i] - b[i]); if(tmp > max) max = tmp; } return max; } inline void accumByAtrans(Data * d, const double *x, double *y) { cblas_dgemv(CblasColMajor, CblasTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1); } inline void accumByA(Data * d, const double *x, double *y) { cblas_dgemv(CblasColMajor, CblasNoTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1); } /* inline void b_daxpy(const int n, const double alpha, const double *x, const int incx, double *y, const int incy) { daxpy(&n,&alpha,x,&incx,y,&incy); //cblas_daxpy(n,alpha,x,incx,y,incy); } inline void b_dsyr(char Uplo, const int N, const double alpha, const double *X, const int incX, double *A, const int lda) { //dsyr(&Uplo,&N,&alpha,X,&incX,A,&lda); cblas_dsyr(CblasColMajor, Uplo, N, alpha, X, incX, A, lda); } inline void b_dscal(const int N, const double alpha, double *X, const int incX) { //dscal(&N,&alpha,X,&incX); cblas_dscal(N,alpha,X,incX); } inline double b_ddot(const int n, const double *x, const int incx, const double *y, const int incy) { //return ddot(&n,x,&incx,y,&incy); return cblas_ddot(n,x,incx,y,incy); } inline double b_dnrm2(const int N, const double *X, const int incX) { return cblas_dnrm2(N,X,incX); //return dnrm2(&N,X,&incX); } inline void b_dgemm( char TransA, char TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc){ dgemm(&TransA, &TransB, &M, &N, &K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc); //cblas_dgemm(); } inline void b_dgemv(char Trans, const int m, const int n, const double alpha, const double *a, const int lda, const double *x, const int incx, const double beta, double *y, const int incy){ dgemv(&Trans,&m,&n,&alpha,a,&lda,x,&incx,&beta,y,&incy); } inline void b_dtrsv(char Uplo, char TransA, char Diag, const int N, const double *A, const int lda, double *X, const int incX) { dtrsv(&Uplo, &TransA, &Diag, &N, A, &lda, X, &incX); } inline void b_dsymv(char Uplo, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY){ dsymv(&Uplo, &N, &alpha, A, &lda, X, &incX, beta, Y, &incY); } */
cvxgrp/coneos
coneOSdense/direct/private.c
#include "private.h" int privateInitWork(Data * d, Work * w){ w->method = strdup("dense-direct"); int k,j, n=d->n, m=d->m; w->p = coneOS_malloc(sizeof(Priv)); double * A = d->Ax; /* sparse A input: w->p->A = coneOS_calloc(m*n, sizeof(double)); for (j = 0; j < n; ++j) { for (k = d->Ap[j]; k < d->Ap[j+1]; ++k) { w->p->A[d->Ai[k]+j*m] = d->Ax[k]; } } */ // form Gram matrix I + A'A w->p->L = coneOS_calloc(n*n, sizeof(double)); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,n, n, m, 1, A, d->m, A, m, 0, w->p->L, n); //b_dgemm('T', 'N', n, n, m, 1, A, d->m, A, m, 0, w->p->L, n); for (j = 0; j < n; j++) { //w->p->L[j*n + j] += 1; w->p->L[j*n + j] += d->RHO_X; } int status = LAPACKE_dpotrf(LAPACK_COL_MAJOR,'L',d->n,w->p->L,d->n); // copy L into top half for faster solve steps for (k = 0; k < n; ++k){ for (j = k+1; j < n; ++j){ w->p->L[k + j*n] = w->p->L[j + k*n]; } } return(status); //coneOS_printf("Factorization time is %4.8f ms\n", tocq()); } void freePriv(Work * w){ coneOS_free(w->p->L); coneOS_free(w->p); } void solveLinSys(Data *d, Work * w, double * b, const double * s){ // solves Mx = b, for x but stores result in b double * A = d->Ax; double * L = w->p->L; cblas_dgemv(CblasColMajor, CblasTrans, d->m, d->n, 1, A, d->m, &(b[d->n]), 1, 1, b, 1); //b_dgemv('T', d->m, d->n, 1, A, d->m, &(b[d->n]), 1, 1, b, 1); /* lapack dportrs is slower than cblas dtrsv: */ //LAPACKE_dpotrs(LAPACK_COL_MAJOR, 'L', d->n, 1, L, d->n, b, d->n); /* Solve using forward-substitution, L c = b */ cblas_dtrsv (CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit, d->n, L, d->n, b, 1); //b_dtrsv('L', 'N', 'N', d->n, L, d->n, b, 1); /* Perform back-substitution, U x = c */ cblas_dtrsv (CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, d->n, L, d->n, b, 1); //b_dtrsv('U', 'N', 'N', d->n, L, d->n, b, 1); cblas_dgemv(CblasColMajor, CblasNoTrans, d->m, d->n, 1, A, d->m, b, 1, -1, &(b[d->n]), 1); //b_dgemv('N', d->m, d->n, 1, A, d->m, b, 1, -1, &(b[d->n]), 1); }
cvxgrp/coneos
coneOSsparse/indirect/private.c
#include "private.h" #include "linAlg.h" #define CG_BEST_TOL 1e-9 #define CG_EXPONENT 1.5 #define CG_VERBOSE 1 #define PRINT_INTERVAL 100 static inline void calcAx(Data * d, Work * w, const double * x, double * y); static int cgCustom(Data *d, Work *w, const double *s, double * b, int max_its, double tol); static inline void CGaccumByA(Data * d, Work * w, const double *x, double *y); static inline void CGaccumByAtrans(Data *d, Work * w, const double *x, double *y); static inline void transpose (Data * d, Work * w); static int totCgIts = 0; int privateInitWork(Data * d, Work * w){ char str[80]; // int len = sprintf(str,"sparse-indirect, CG: iters %i, tol %.2e", d->CG_MAX_ITS, d->CG_TOL); int len = sprintf(str,"sparse-indirect, CG tol ~ 1/iter^(%2.2f)", (float) CG_EXPONENT); w->method = strndup(str, len); w->p = coneOS_malloc(sizeof(Priv)); w->p->p = coneOS_malloc((d->n)*sizeof(double)); w->p->r = coneOS_malloc((d->n)*sizeof(double)); w->p->Ap = coneOS_malloc((d->n)*sizeof(double)); w->p->tmp = coneOS_malloc((d->m)*sizeof(double)); w->p->Ati = coneOS_malloc((d->Ap[d->n])*sizeof(int)); w->p->Atp = coneOS_malloc((d->m+1)*sizeof(int)); w->p->Atx = coneOS_malloc((d->Ap[d->n])*sizeof(double)); transpose(d,w); return(0); } static inline void transpose (Data * d, Work * w) { int * Ci = w->p->Ati; int * Cp = w->p->Atp; double * Cx = w->p->Atx; int m = d->m; int n = d->n; int * Ap = d->Ap; int * Ai = d->Ai; double * Ax = d->Ax; int p, j, q, *z; z = coneOS_calloc(m,sizeof(int)); for (p = 0 ; p < Ap [n] ; p++) z [Ai [p]]++ ; /* row counts */ cs_cumsum (Cp, z, m) ; /* row pointers */ for (j = 0 ; j < n ; j++) { for (p = Ap [j] ; p < Ap [j+1] ; p++) { Ci [q = z [Ai [p]]++] = j ; /* place A(i,j) as entry C(j,i) */ if (Cx) Cx [q] = Ax [p] ; } } coneOS_free(z); } void freePriv(Work * w){ coneOS_free(w->p->p); coneOS_free(w->p->r); coneOS_free(w->p->Ap); coneOS_free(w->p->tmp); coneOS_free(w->p->Ati); coneOS_free(w->p->Atx); coneOS_free(w->p->Atp); coneOS_free(w->p); } void solveLinSys(Data *d, Work * w, double * b, const double * s, int iter){ double cgTol = iter < 0 ? CG_BEST_TOL : calcNorm(b,d->n) / pow(iter + 1, (float) CG_EXPONENT); // solves Mx = b, for x but stores result in b // s contains warm-start (if available) CGaccumByAtrans(d,w, &(b[d->n]), b); // solves (I+A'A)x = b, s warm start, solution stored in b int cgIts = cgCustom(d, w, s, b, d->n, cgTol); scaleArray(&(b[d->n]),-1,d->m); CGaccumByA(d, w, b, &(b[d->n])); if(iter >= 0) { totCgIts += cgIts; if (CG_VERBOSE && d->VERBOSE && (iter + 1) % PRINT_INTERVAL == 0) { coneOS_printf("\taverage CG iterations for last %i coneOS iters: %2.2f\n", PRINT_INTERVAL, (double) totCgIts / PRINT_INTERVAL); totCgIts = 0; } } } static int cgCustom(Data *d, Work *w, const double * s, double * b, int max_its, double tol){ /* solves (I+A'A)x = b */ /* warm start cg with s */ int i = 0, n = d->n; double *p = w->p->p; // cg direction double *Ap = w->p->Ap; // updated CG direction double *r = w->p->r; // cg residual double alpha, rsnew=0; if (s==NULL){ memcpy(r,b,n*sizeof(double)); memset(b,0.0,n*sizeof(double)); } else{ calcAx(d,w,s,r); addScaledArray(r,b,n,-1); scaleArray(r,-1,n); memcpy(b,s,n*sizeof(double)); } memcpy(p,r,n*sizeof(double)); double rsold=calcNorm(r,n); for (i=0; i < max_its; ++i){ calcAx(d,w,p,Ap); alpha=(rsold*rsold)/innerProd(p,Ap,n); addScaledArray(b,p,n,alpha); addScaledArray(r,Ap,n,-alpha); rsnew=calcNorm(r,n); if (rsnew < tol){ //coneOS_printf("tol: %.4e, resid: %.4e, iters: %i\n", tol, rsnew, i+1); return i+1; } scaleArray(p,(rsnew*rsnew)/(rsold*rsold),n); addScaledArray(p,r,n,1); rsold=rsnew; } return i; } static inline void calcAx(Data * d, Work * w, const double * x, double * y){ double * tmp = w->p->tmp; memset(tmp,0,d->m*sizeof(double)); CGaccumByA(d,w,x,tmp); memset(y,0,d->n*sizeof(double)); CGaccumByAtrans(d,w,tmp,y); addScaledArray(y,x,d->n,d->RHO_X); } static inline void CGaccumByA(Data * d, Work * w, const double *x, double *y) { _accumByAtrans(d->m,w->p->Atx,w->p->Ati,w->p->Atp,x,y); } static inline void CGaccumByAtrans(Data *d, Work * w, const double *x, double *y) { _accumByAtrans(d->n,d->Ax,d->Ai,d->Ap,x,y); }
cvxgrp/coneos
coneOSsparse/run_coneOS.h
#ifndef RUN_coneOS_H_GUARD #define RUN_coneOS_H_GUARD int main(int argc, char **argv); void free_data(Data * d, Cone * k); int read_in_data(FILE * fp,Data * d, Cone * k); int open_file(int argc, char ** argv, int idx, char * default_file, FILE ** fb); void freeData(Data *d, Cone *k); void freeSol(Sol *sol); #endif
cvxgrp/coneos
coneOSsparse/linAlg.h
<gh_stars>1-10 #ifndef LINALG_H_GUARD #define LINALG_H_GUARD #include "coneOS.h" #include <math.h> void _accumByAtrans(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); void _accumByA(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); void setAsScaledArray(double *x, const double * a,const double b,int len); void scaleArray(double * a,const double b,int len); double innerProd(const double * x, const double * y, int len); double calcNormSq(const double * v,int len); double calcNorm(const double * v,int len); double calcNormInf(const double *a, int l); void addScaledArray(double * a, const double * b, int n, const double sc); double calcNormDiff(const double *a, const double *b, int l); double calcNormInfDiff(const double *a, const double *b, int l); void accumByAtrans(Data * d, const double *x, double *y); void accumByA(Data * d, const double *x, double *y); void _accumByAtrans(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); void _accumByA(int n, double * Ax, int * Ai, int * Ap, const double *x, double *y); #endif
cvxgrp/coneos
coneOSdense/indirect/private.c
#include "private.h" int privateInitWork(Data * d, Work * w){ char str[80]; int len = sprintf(str, "dense-indirect, CG: iters %i, tol %.2e", d->CG_MAX_ITS, d->CG_TOL); w->method = strndup(str, len); int j; w->p = coneOS_malloc(sizeof(Priv)); w->p->x = coneOS_malloc(d->n*sizeof(double)); w->p->p = coneOS_malloc(d->n*sizeof(double)); w->p->Ap = coneOS_malloc(d->n*sizeof(double)); double * A = d->Ax; /* sparse A format w->p->A = coneOS_calloc(d->m*d->n, sizeof(double)); int k; for (j = 0; j < d->n; j++) { for (k = d->Ap[j]; k < d->Ap[j+1]; k++) { w->p->A[d->Ai[k]+j*d->m] = d->Ax[k]; } } */ // form Gram matrix I+A'A w->p->G = coneOS_malloc(d->n*d->n*sizeof(double)); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,d->n, d->n, d->m, 1, A, d->m, A,d->m, 0, w->p->G,d->n); //b_dgemm('T', 'N' ,d->n, d->n, d->m, 1, A, d->m, A,d->m, 0, w->p->G,d->n); for (j = 0; j < d->n; j++) { //w->p->G[j*d->n + j] += 1; w->p->G[j*d->n + j] += d->RHO_X; } return(0); } void freePriv(Work * w){ coneOS_free(w->p->p); coneOS_free(w->p->x); coneOS_free(w->p->Ap); coneOS_free(w->p->G); coneOS_free(w->p); } static void cgCustom(Data *d, Work *w, const double *s, int max_its, double tol); void solveLinSys(Data *d, Work * w, double * b, const double * s){ // solves Mx = b, for x but stores result in b // s contains warm-start (if available) w->p->r = b; double * r = w->p->r; double * A = d->Ax; double * x = w->p->x; cblas_dgemv(CblasColMajor, CblasTrans, d->m, d->n, 1, A, d->m, &(b[d->n]),1, 1, r, 1); //b_dgemv('T', d->m, d->n, 1, A, d->m, &(b[d->n]),1, 1, r, 1); cgCustom(d, w, s, d->CG_MAX_ITS, d->CG_TOL); cblas_dgemv(CblasColMajor, CblasNoTrans, d->m, d->n, 1, A, d->m, x,1, -1, &(b[d->n]), 1); //b_dgemv('N', d->m, d->n, 1, A, d->m, x,1, -1, &(b[d->n]), 1); memcpy(b, x, d->n*sizeof(double)); } static void cgCustom(Data *d, Work *w, const double * s, int max_its, double tol){ /* solves (I+A'A)x = b */ /* warm start cg with s */ int i = 0, n = d->n; double *x = w->p->x; double *p = w->p->p; // cg direction double *Ap = w->p->Ap; // updated CG direction double *r = w->p->r; // cg residual double *G = w->p->G; // Gram matrix double alpha, beta, rsnew=0; if (s==NULL){ memset(x,0,n*sizeof(double)); } else{ memcpy(x,s,n*sizeof(double)); cblas_dsymv(CblasColMajor, CblasUpper,n, -1, G, n, x,1, 1, r, 1); //b_dsymv('U', n, -1, G, n, x,1, 1, r, 1); } memcpy(p, r, n*sizeof(double)); //double rsold=cblas_dnrm2(n,r,1); double rsold=calcNorm(r,n); for (i=0; i< max_its; i++){ cblas_dsymv(CblasColMajor, CblasUpper,n, 1, G, n, p, 1, 0, Ap, 1); //b_dsymv('U', n, 1, G, n, p, 1, 0, Ap, 1); //beta = cblas_ddot(n, p, 1, Ap, 1); beta = innerProd(p,Ap,n); alpha=(rsold*rsold)/beta; addScaledArray(x,p,n,alpha); //cblas_daxpy(n,alpha,p,1,x,1); addScaledArray(r,Ap,n,-alpha); //cblas_daxpy(n,-alpha,Ap,1,r,1); //rsnew=cblas_dnrm2(n,r,1); rsnew=calcNorm(r,n); if (rsnew<tol){ break; } scaleArray(p,(rsnew*rsnew)/(rsold*rsold),n); //cblas_dscal(n,(rsnew*rsnew)/(rsold*rsold),p,1); addScaledArray(p,r,n,1); //cblas_daxpy(n,1,r,1,p,1); rsold=rsnew; } //printf("terminating cg residual = %4f, took %i itns\n",rsnew,i); }
cvxgrp/coneos
coneOSsparse/cs.h
#ifndef CS_H_GUARD #define CS_H_GUARD //#include <string.h> //#include <stdlib.h> typedef struct cs_sparse /* matrix in compressed-column or triplet form */ { int nzmax ; /* maximum number of entries */ int m ; /* number of rows */ int n ; /* number of columns */ int *p ; /* column pointers (size n+1) or col indices (size nzmax) */ int *i ; /* row indices, size nzmax */ double *x ; /* numerical values, size nzmax */ int nz ; /* # of entries in triplet matrix, -1 for compressed-col */ } cs ; cs *cs_compress (const cs *T); cs *cs_done (cs *C, void *w, void *x, int ok); cs *cs_spalloc (int m, int n, int nzmax, int values, int triplet); cs *cs_spfree (cs *A); double cs_cumsum (int *p, int *c, int n); int *cs_pinv (int const *p, int n); cs *cs_symperm (const cs *A, const int *pinv, int values); #endif
cvxgrp/coneos
coneOSsparse/util.h
#ifndef UTIL_H_GUARD #define UTIL_H_GUARD #include <stdlib.h> #include <stdio.h> #include "coneOS.h" void tic(void); double toc(void); double tocq(void); void printConeData(Cone * k); void printData(Data * d); void printAll(Data * d, Work * w); #endif
cvxgrp/coneos
coneOSdense/run_coneOS.c
<gh_stars>1-10 #include "coneOS.h" #include "run_coneOS.h" #ifndef DEMO_PATH #define DEMO_PATH "../data_dense" #endif #define NUM_TRIALS 1 #define RHOX 1e-3 int main(int argc, char **argv) { FILE * fp; if(open_file(argc, argv, 1, DEMO_PATH, &fp)==-1) return -1; Cone * k = coneOS_malloc(sizeof(Cone)); Data * d = coneOS_malloc(sizeof(Data)); read_in_data(fp,d,k); fclose(fp); Sol * sol = coneOS_malloc(sizeof(Sol)); Info * info = coneOS_malloc(sizeof(Info)); int i; for (i=0;i<NUM_TRIALS;i++) { coneOS(d,k,sol,info); } freeData(d,k); freeSol(sol); coneOS_free(info); return 0; } int read_in_data(FILE * fp,Data * d, Cone * k){ /* MATRIX IN DATA FILE MUST BE DENSE COLUMN MAJOR FORMAT */ d->RHO_X = RHOX; if(fscanf(fp, "%i", &(d->n)) != 1) return -1; if(fscanf(fp, "%i", &(d->m))!= 1) return -1; if(fscanf(fp, "%i", &(k->f))!= 1) return -1; if(fscanf(fp, "%i", &(k->l))!= 1) return -1; if(fscanf(fp, "%i", &(k->qsize))!= 1) return -1; if(fscanf(fp, "%i", &(k->ssize))!= 1) return -1; if(fscanf(fp, "%i", &(d->MAX_ITERS))!= 1) return -1; if(fscanf(fp, "%i", &(d->CG_MAX_ITS))!= 1) return -1; if(fscanf(fp, "%i", &(d->VERBOSE))!= 1) return -1; if(fscanf(fp, "%i", &(d->NORMALIZE))!= 1) return -1; if(fscanf(fp, "%lf", &(d->ALPH))!= 1) return -1; if(fscanf(fp, "%lf", &(d->UNDET_TOL))!= 1) return -1; if(fscanf(fp, "%lf", &(d->EPS_ABS))!= 1) return -1; if(fscanf(fp, "%lf", &(d->CG_TOL))!= 1) return -1; k->q = malloc(sizeof(int)*k->qsize); for(int i = 0; i < k->qsize; i++) { if(fscanf(fp, "%i", &k->q[i])!= 1) return -1; } k->s = malloc(sizeof(int)*k->ssize); for(int i = 0; i < k->ssize; i++) { if(fscanf(fp, "%i", &k->s[i])!= 1) return -1; } d->b = malloc(sizeof(double)*d->m); for(int i = 0; i < d->m; i++) { if(fscanf(fp, "%lf", &d->b[i])!= 1) return -1; } d->c = malloc(sizeof(double)*d->n); for(int i = 0; i < d->n; i++) { if(fscanf(fp, "%lf", &d->c[i])!= 1) return -1; } d->Anz = d->n*d->m; d->Ax = coneOS_malloc(sizeof(double)*d->Anz); for(int i = 0; i < d->Anz; i++) { if(fscanf(fp, "%lf", &d->Ax[i])!= 1) return -1; } d->Ai = NULL; d->Ap = NULL; // fscanf(fp, "%zu", &NNZ); // int *Kr = coneOS_malloc(sizeof(int)*NNZ); // for(int i = 0; i < NNZ; i++) // { // fscanf(fp, "%i", &Kr[i]); // } // int *Kp=coneOS_malloc(sizeof(int)*(w->l+1)); // for(int i = 0; i < w->l+1; i++) // { // fscanf(fp, "%i", &Kp[i]); // } // double *Kx=coneOS_malloc(sizeof(double)*NNZ); // for(int i = 0; i < NNZ; i++) // { // fscanf(fp, "%lf", &Kx[i]); // } return 0; } int open_file(int argc, char ** argv, int idx, char * default_file, FILE ** fb) { if (argc<idx+1){ printf("Not enough arguments supplied, using %s as default\n", default_file); } else{ *fb = fopen(argv[idx], "r"); if (*fb != NULL) return 0; else{ printf("Couldn't open file %s, using %s as default\n", argv[idx],default_file); fclose(*fb); } } *fb = fopen(default_file, "r"); if (*fb == NULL){ printf("Couldn't open %s\n",default_file); return -1; } return 0; } void freeData(Data * d, Cone * k){ if(d) { if(d->b) coneOS_free(d->b); if(d->c) coneOS_free(d->c); if(d->Ax) coneOS_free(d->Ax); if(d->Ai) coneOS_free(d->Ai); if(d->Ap) coneOS_free(d->Ap); coneOS_free(d); } if(k) { if(k->q) coneOS_free(k->q); if(k->s) coneOS_free(k->s); coneOS_free(k); } d = NULL; k = NULL; } void freeSol(Sol *sol){ if(sol) { if(sol->x) coneOS_free(sol->x); if(sol->y) coneOS_free(sol->y); if(sol->s) coneOS_free(sol->s); //if(sol->status) coneOS_free(sol->status); coneOS_free(sol); } sol = NULL; }
cvxgrp/coneos
coneOSsparse/normalize.h
#ifndef NORMAL_H_GUARD #define NORMAL_H_GUARD #define MIN_SCALE 1e-2 #define MAX_SCALE 1e3 void normalize(Data * d, Work * w, Cone * k){ double * D = coneOS_calloc(d->m, sizeof(double)); double * E = coneOS_calloc(d->n, sizeof(double)); int i, j, count; double wrk; // heuristic rescaling, seems to do well with a scaling of about 4 w->scale = 4; //fmax( fmin( sqrt( d->n * d->m / d->Anz ) , MAX_SCALE) , 1); // calculate row norms for(i = 0; i < d->n; ++i){ for(j = d->Ap[i]; j < d->Ap[i+1]; ++j) { wrk = d->Ax[j]; D[d->Ai[j]] += wrk*wrk; } } for (i=0; i < d->m; ++i){ D[i] = sqrt(D[i]); // just the norms } // mean of norms of rows across each cone count = k->l+k->f; for(i = 0; i < k->qsize; ++i) { wrk = 0; /* for (j = count; j < count + k->q[i]; ++j){ wrk = fmax(wrk,D[j]); } */ for (j = count; j < count + k->q[i]; ++j){ wrk += D[j]; } wrk /= k->q[i]; for (j = count; j < count + k->q[i]; ++j){ D[j] = wrk; } count += k->q[i]; } for (i=0; i < k->ssize; ++i) { wrk = 0; /* for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ wrk = fmax(wrk,D[j]); } */ for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ wrk += D[j]*D[j]; } wrk = sqrt(wrk); wrk /= k->s[i]; for (j = count; j < count + (k->s[i])*(k->s[i]); ++j){ D[j] = wrk; } count += (k->s[i])*(k->s[i]); } for(i = 0; i < k->ep + k->ed; ++i) { wrk = D[count]/3 + D[count + 1]/3 + D[count + 2]/3; D[count] = wrk; D[count + 1] = wrk; D[count + 2] = wrk; count += 3; } for (i=0; i<d->m; ++i){ if (D[i] < MIN_SCALE) D[i] = MIN_SCALE; else if (D[i] > MAX_SCALE) D[i] = MAX_SCALE; } // scale the rows with D for(i = 0; i < d->n; ++i){ for(j = d->Ap[i]; j < d->Ap[i+1]; ++j) { d->Ax[j] /= D[d->Ai[j]]; } } // calculate and scale by col norms, E for (i = 0; i < d->n; ++i){ E[i] = calcNorm(&(d->Ax[d->Ap[i]]),d->Ap[i+1] - d->Ap[i]); if (E[i] < MIN_SCALE) E[i] = MIN_SCALE; else if (E[i] > MAX_SCALE) E[i] = MAX_SCALE; scaleArray(&(d->Ax[d->Ap[i]]), 1.0/E[i], d->Ap[i+1] - d->Ap[i]); } // scale b for (i = 0; i < d->m; ++i){ d->b[i] /= D[i]; } w->sc_b = 1/fmax(calcNorm(d->b,d->m),MIN_SCALE); scaleArray(d->b, w->sc_b, d->m); // scale c for (i = 0; i < d->n; ++i){ d->c[i] /= E[i]; } double meanNormRowA = 0.0; double *nms = coneOS_calloc(d->m,sizeof(double)); for(i = 0; i < d->n; ++i){ for(j = d->Ap[i]; j < d->Ap[i+1]; ++j) { wrk = d->Ax[j]; nms[d->Ai[j]] += wrk*wrk; } } for (i=0; i < d->m; ++i){ meanNormRowA += sqrt(nms[i])/d->m; } w->sc_c = meanNormRowA/fmax(calcNorm(d->c,d->n),MIN_SCALE); scaleArray(d->c, w->sc_c, d->n); w->D = D; w->E = E; coneOS_free(nms); // heuristic scaling factor scaleArray(d->Ax,w->scale,d->Anz); scaleArray(d->b,w->scale,d->m); scaleArray(d->c,w->scale,d->n); /* coneOS_printf("norm D is %4f\n", calcNorm(D,d->m)); coneOS_printf("norm E is %4f\n", calcNorm(E,d->n)); coneOS_printf("norm A is %4f\n", calcNorm(d->Ax,d->Anz)); coneOS_printf("norm b is %4f\n", calcNorm(d->b,d->m)); coneOS_printf("norm c is %4f\n", calcNorm(d->c,d->n)); */ } void calcScaledResids(Data * d, Work * w, struct residuals * r) { double * D = w->D; double * E = w->E; double * u = w->u; double * u_t = w->u_t; double * u_prev = w->u_prev; double tmp; int i; r->resPri = 0; for (i = 0; i < d->n; ++i){ tmp = (u[i] - u_t[i])/(E[i] * w->sc_b); r->resPri += tmp * tmp; } for (i = 0; i < d->m; ++i){ tmp = (u[i + d->n] - u_t[i + d->n])/(D[i] * w->sc_c); r->resPri += tmp * tmp; } tmp = u[w->l-1] - u_t[w->l-1]; r->resPri += tmp * tmp; r->resPri = sqrt(r->resPri); r->resDual = 0; for (i = 0; i < d->n; ++i){ tmp = (u[i] - u_prev[i]) * E[i] / w->sc_b; r->resDual += tmp * tmp; } for (i = 0; i < d->m; ++i){ tmp = (u[i + d->n] - u_prev[i + d->n]) * D[i] / w->sc_c; r->resDual += tmp * tmp; } tmp = u[w->l-1] - u_t[w->l-1]; r->resDual += tmp * tmp; r->resDual = sqrt(r->resDual); } double calcScaledNormInf(const double *a, const double * s, int l){ double tmp, max = 0.0; int i; for ( i=0; i<l; ++i){ tmp = fabs(s[i] * a[i]); if(tmp > max) max = tmp; } return max; } void unNormalize(Data *d, Work * w, Sol * sol){ int i, j; double * D = w->D; double * E = w->E; for (i = 0; i < d->n; ++i){ sol->x[i] /= (E[i] * w->sc_b); } for (i = 0; i < d->m; ++i){ sol->y[i] /= (D[i] * w->sc_c); } for (i = 0; i < d->m; ++i){ sol->s[i] *= D[i]/(w->sc_b * w->scale); } for (i = 0; i < d->n; ++i){ d->c[i] *= E[i]/(w->sc_c * w->scale); } for (i = 0; i < d->m; ++i){ d->b[i] *= D[i]/(w->sc_b * w->scale); } for (i = 0; i < d->n; ++i){ scaleArray(&(d->Ax[d->Ap[i]]), E[i], d->Ap[i+1] - d->Ap[i]); } for(i = 0; i < d->n; ++i){ for(j = d->Ap[i]; j < d->Ap[i+1]; ++j) { d->Ax[j] *= D[d->Ai[j]]; } } scaleArray(d->Ax,1.0/w->scale,d->Anz); } #endif
cvxgrp/coneos
coneOSdense/linAlg.h
#ifndef LINALG_H_GUARD #define LINALG_H_GUARD #include "coneOS.h" #include <cblas.h> #include <math.h> void setAsScaledArray(double *x, const double * a,const double b,int len); void scaleArray(double * a,const double b,int len); double innerProd(const double * x, const double * y, int len); double calcNorm(const double * v,int len); double calcNormInf(const double *a, int l); double calcNormSq(const double * v,int len); void addScaledArray(double * a, const double * b, int n, const double sc); double calcNormDiff(const double *a,const double *b, int l); double calcNormInfDiff(const double *a, const double *b, int l); void accumByAtrans(Data * d, const double *x, double *y); void accumByA(Data * d, const double *x, double *y); #endif
cvxgrp/coneos
coneOSsparse/direct/private.h
#ifndef PRIV_H_GUARD #define PRIV_H_GUARD #include "cs.h" #include "amd.h" #include "ldl.h" #include "coneOS.h" struct PRIVATE_DATA { cs * L; /* KKT, and factorization matrix L resp. */ double * D; /* diagonal matrix of factorization */ int * P; /* permutation of KKT matrix for factorization */ double * bp; /* workspace memory for solves */ }; extern void amd_info (double Info [ ]); extern int amd_order (int n, const int Ap [ ], const int Ai [ ], int P [ ], double Control [ ], double Info [ ]); #endif
9re/QROAuth
QROAuthSample/Classes/QROAuthSampleAppDelegate.h
// // QROAuthSampleDelegate.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface QROAuthSampleDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
9re/QROAuth
Classes/QROAuthDelegate.h
// // QROAuthDelegate.h // QROAuth // // Created by <NAME> on 27/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef QROAuth_QROAuthDelegate_h #define QROAuth_QROAuthDelegate_h @protocol QROAuthDelegate <NSObject> @required - (void) onFetchedAccessToken:(NSString *) accessToken accessTokenSecret:(NSString *) accessTokenSecret; - (void) onFailure; @end #endif
9re/QROAuth
Classes/QROAuthProvider.h
// // QROAuthProvider.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "OAConsumer.h" @interface QROAuthProvider : NSObject @property (retain) NSString *requestTokenUrl; @property (retain) NSString *accessTokenUrl; @property (retain) NSString *authorizeUrl; @property (retain) NSString *oauthCallbackUrl; - (id)initWithRequestTokenUrl: (NSString *)requestTokenUrl accessTokenUrl: (NSString *)accessTokenUrl authorizeUrl: (NSString *)authorizeUrl oauthCallbackUrl: (NSString *)oauthCallbackUrl; - (void)retrieveRequestToken: (OAConsumer *)oaConsumer callback:(void (^)(NSString *callbakUrl, NSError *error))callback; - (void)retrieveAccessToken: (OAConsumer *)oaConsumer requestToken: (NSString *)requestToken verifier: (NSString *)verifier callback:(void (^)(NSDictionary *res, NSError *error))callback; @end
9re/QROAuth
QROAuthSample/Classes/Config.h
<reponame>9re/QROAuth<filename>QROAuthSample/Classes/Config.h // // Header.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef QROAuth_Header_h #define QROAuth_Header_h #define TWITTER_CONSUMER_KEY <PUT YOUR TWITTER_CONSUMER_KEY> #define TWITTER_CONSUMER_SECRET_KEY <PUT YOUR TWITTER_CONSUMER_SECRET_KEY> #endif
9re/QROAuth
Classes/QROAuthLoginViewController.h
<filename>Classes/QROAuthLoginViewController.h<gh_stars>0 // // QROAuthLoginViewController.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "OAConsumer.h" #import "QROAuthDelegate.h" #import "QROAuthProvider.h" @interface QROAuthLoginViewController : UIViewController<UIWebViewDelegate> @property (retain, nonatomic) IBOutlet UIWebView *webView; @property (retain, nonatomic) IBOutlet UIButton *cancelButton; @property (retain) QROAuthProvider *oauthProvider; @property (retain) OAConsumer *oaConsumer; @property (retain) id <QROAuthDelegate> delegate; - (id)initWithOAuthProvider: (QROAuthProvider *)oauthProvider oaConsumer: (OAConsumer *) oaConsumer; - (IBAction)onCancelClicked:(id)sender; @end
9re/QROAuth
Classes/NSDictionary+OARequestParameter.h
<reponame>9re/QROAuth // // NSDictionary+OAParameter.h // QROAuth // // Created by <NAME> on 27/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (OAParameter) - (NSArray*) castAsOAParameters; @end
9re/QROAuth
Classes/QRResourceUtil.h
// // QRResourceUtil.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface QRResourceUtil : NSObject + (NSBundle *)frameworkBundle; @end
9re/QROAuth
Classes/QROAuth.h
// // QROAuth.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef QROAuth_QROAuth_h #define QROAuth_QROAuth_h #import "QROAuthLoginViewController.h" #import "QROAuthDelegate.h" #endif
9re/QROAuth
QROAuthSample/Classes/QROAuthSampleViewController.h
// // QRSampleViewController.h // QROAuth // // Created by <NAME> on 25/01/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "QROAuth.h" @interface QRSampleViewController : UIViewController <QROAuthDelegate> @property (retain, nonatomic) IBOutlet UIButton *loginButton; - (IBAction)onLoginClicked:(id)sender; @end
vdm-dev/gpsinformer
src/TcpClient.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef TcpClient_INCLUDED #define TcpClient_INCLUDED template <class T> class TcpClientHandler; class TcpClient { public: TcpClient(asio::io_service& ioService, TcpClientHandler<TcpClient>* handler = 0); ~TcpClient(); void connect(const std::string& server, unsigned short port); void connect(const std::string& server, const std::string& protocol); void disconnect(); void send(const unsigned char* buffer, size_t length); void send(const std::string& data); void setEventHandler(TcpClientHandler<TcpClient>* handler); asio::ip::tcp::socket& socket(); private: enum Status { Disconnected, Resolve, Connecting, Connected, Disconnecting }; bool handleAnything(Status handleStatus, const system::error_code& error); void handleResolve(const system::error_code& error, asio::ip::tcp::resolver::iterator endpoint); void handleConnect(const system::error_code& error); void handleRead(size_t size, const system::error_code& error); void handleWrite(size_t size, const system::error_code& error); asio::ip::tcp::resolver _resolver; asio::ip::tcp::socket _socket; std::vector<char> _readBuffer; std::deque<std::string> _writeBuffer; TcpClientHandler<TcpClient>* _handler; Status _status; int _ioCount; }; inline void TcpClient::setEventHandler(TcpClientHandler<TcpClient>* handler) { _handler = handler; } inline asio::ip::tcp::socket& TcpClient::socket() { return _socket; } #endif // TcpClient_INCLUDED
vdm-dev/gpsinformer
src/Device.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef Device_INCLUDED #define Device_INCLUDED #include "TcpSession.h" class Device { public: Device(shared_ptr<TcpSession> session); ~Device(); static shared_ptr<TcpSession> authorizedSession(); void processClientData(const std::string& data); void processData(const std::string& data); private: bool commandLogon(const std::vector<std::string>& arguments); bool commandHeartbeat(const std::vector<std::string>& arguments); bool commandGpsData(const std::vector<std::string>& arguments); static shared_ptr<TcpSession> _authorizedSession; shared_ptr<TcpSession> _session; std::string _buffer; std::string _imei; }; #endif // Device_INCLUDED
vdm-dev/gpsinformer
src/HttpsClient.h
<reponame>vdm-dev/gpsinformer // // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef HttpsClient_INCLUDED #define HttpsClient_INCLUDED #include "HttpRequest.h" #include "SslClient.h" #include "TcpClientHandler.h" class HttpClientHandler; class HttpsClient : public TcpClientHandler<SslClient> { public: HttpsClient(asio::io_service& ioService, HttpClientHandler* handler = 0); ~HttpsClient(); void sendRequest(const HttpRequest& request); void pushQueue(); void stop(bool clear = true); void setEventHandler(HttpClientHandler* handler); private: void handleTcpClientConnect(SslClient* client); void handleTcpClientDisconnect(SslClient* client, TcpClientHandler::Reason reason); void handleTcpClientError(SslClient* client, const system::error_code& error); void handleTcpClientReceivedData(SslClient* client, const std::string& data); void handleTimerEvent(); asio::deadline_timer _timer; SslClient _client; std::deque<HttpRequest> _requestQueue; std::string _response; HttpClientHandler* _handler; }; inline void HttpsClient::setEventHandler(HttpClientHandler* handler) { _handler = handler; } #endif // HttpsClient_INCLUDED
vdm-dev/gpsinformer
src/TelegramBot.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef TelegramBot_INCLUDED #define TelegramBot_INCLUDED #include <tgbot/TgTypeParser.h> #include "HttpsClient.h" #include "HttpClientHandler.h" #include "HttpReqArg.h" class TelegramBotHandler; class TelegramBot : public HttpClientHandler { public: enum ParseMode { None, Markdown, Html }; TelegramBot(asio::io_service& ioService, TelegramBotHandler* handler = 0); virtual ~TelegramBot(); void start(); void stop(); void setEventHandler(TelegramBotHandler* handler); void setApiUrl(const std::string& apiUrl); void setToken(const std::string& token); void setReconnectDelay(int64_t delay); void getMe(); void sendMessage(int64_t chatId, const std::string& text, ParseMode parseMode = ParseMode::None, bool disableWebPagePreview = false, bool disableNotification = false, int32_t replyToMessageId = 0, const TgBot::GenericReply::Ptr& replyMarkup = TgBot::GenericReply::Ptr()); void sendLocation(int64_t chatId, double latitude, double longitude, bool disableNotification = false, int32_t replyToMessageId = 0, const TgBot::GenericReply::Ptr& replyMarkup = TgBot::GenericReply::Ptr()); void sendVenue(int64_t chatId, double latitude, double longitude, const std::string& title, const std::string& address, const std::string& foursquareId = std::string(), bool disableNotification = false, int32_t replyToMessageId = 0, const TgBot::GenericReply::Ptr& replyMarkup = TgBot::GenericReply::Ptr()); void sendContact(int64_t chatId, const std::string& phoneNumber, const std::string& firstName, const std::string& lastName = std::string(), bool disableNotification = false, int32_t replyToMessageId = 0, const TgBot::GenericReply::Ptr& replyMarkup = TgBot::GenericReply::Ptr()); private: enum Tags { TAG_NONE = 0, TAG_GET_UPDATES = 1, TAG_GET_ME = 2, TAG_SEND_MESSAGE = 3, TAG_SEND_LOCATION = 4, TAG_SEND_VENUE = 5, TAG_SEND_CONTACT = 6 }; void getUpdates(int32_t limit, int32_t timeout); void makeRequest(const std::string& method, const std::vector<HttpReqArg>& arguments, unsigned int tag = 0, bool longPoll = false); void handleUpdate(const TgBot::Update::Ptr& update); void handleHttpClientError(const system::error_code& error); void handleHttpClientIdle(); void handleHttpClientResponse(const HttpRequest& request, const std::string& response); void handleTimerEvent(const system::error_code& error); asio::deadline_timer _timer; HttpsClient _client; std::string _apiUrl; std::string _token; int32_t _lastUpdateId; int64_t _timerDelay; bool _enabled; TelegramBotHandler* _handler; }; inline void TelegramBot::setEventHandler(TelegramBotHandler* handler) { _handler = handler; } inline void TelegramBot::setApiUrl(const std::string& apiUrl) { _apiUrl = apiUrl; } inline void TelegramBot::setToken(const std::string& token) { _token = token; } inline void TelegramBot::setReconnectDelay(int64_t delay) { _timerDelay = delay; } #endif // TelegramBot_INCLUDED
vdm-dev/gpsinformer
src/Application.h
<reponame>vdm-dev/gpsinformer // // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef Application_INCLUDED #define Application_INCLUDED #include "TcpClient.h" #include "TcpClientHandler.h" #include "TcpServer.h" #include "TcpSession.h" #include "TcpSessionHandler.h" #include "TelegramBot.h" #include "TelegramBotHandler.h" #include "Device.h" #include "GpsMessage.h" #include "UserSettings.h" struct sqlite3; class User; class Application : public boost::noncopyable , public TcpClientHandler<TcpClient> , public TcpSessionHandler , public TelegramBotHandler { friend class Device; public: Application(); ~Application(); static Application* instance(); int main(int argc, char* argv[]); sqlite3* database(); private: bool parseCommandLine(int argc, char* argv[]); bool setApplicationPath(int argc, char* argv[]); bool loadConfiguration(); bool saveConfiguration(); void configureLog(); void handleDeviceCommand(const std::vector<std::string>& arguments); // ApplicationReceiver void startReceiver(); void handleTcpServerError(const system::error_code& error); void handleTcpSessionConnect(shared_ptr<TcpSession> session); void handleTcpSessionDisconnect(shared_ptr<TcpSession> session, TcpSessionHandler::Reason reason); void handleTcpSessionReceivedData(shared_ptr<TcpSession> session, const std::string& data); void handleReceiverTimer(const system::error_code& error); // ApplicationTransmitter void startTransmitter(); void handleTcpClientConnect(TcpClient* client); void handleTcpClientDisconnect(TcpClient* client, TcpClientHandler::Reason reason); void handleTcpClientError(TcpClient* client, const system::error_code& error); void handleTcpClientReceivedData(TcpClient* client, const std::string& data); void handleTransmitterTimer(const system::error_code& error); // ApplicationTelegram void startTelegram(); void sendGpsStatus(const GpsMessage& gpsMessage, int64_t userId); void handleInlineQuery(const TgBot::InlineQuery::Ptr& inlineQuery); void handleChosenInlineResult(const TgBot::ChosenInlineResult::Ptr& chosenInlineResult); void handleCallbackQuery(const TgBot::CallbackQuery::Ptr& callbackQuery); void handleMessage(const TgBot::Message::Ptr& message); void handleOwnMessage(const TgBot::Message::Ptr& message); void handleGetMe(const TgBot::User::Ptr& user); // ApplicationDatabase void openDatabase(); void closeDatabase(); void dbRestoreSettings(); bool dbSaveSettings(); bool dbAddGpsData(const GpsMessage& data); bool dbCreateUser(const User& user); bool dbGetGpsData(std::vector<GpsMessage>& data, unsigned int limit = 0, bool validOnly = false); bool dbSearchUser(User& user); bool dbUpdateUser(const User& user); // ApplicationCommands void fillCommandList(); void handleChatCommand(const std::vector<std::string>& command, const TgBot::Message::Ptr& originalMessage); void handleStartCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleHelpCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handlePasswordCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleGetCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleSetCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleLoadCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleSaveCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleWhereCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleStatusCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleArmCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); void handleDisarmCommand(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); // ApplicationEvents void handleTrackerEvent(const GpsMessage& data); static Application* _instance; filesystem::path _applicationPath; filesystem::path _configurationFile; property_tree::ptree _settings; asio::io_service _ioService; asio::deadline_timer _receiverTimer; asio::deadline_timer _transmitterTimer; TcpServer _receiver; TcpClient _transmitter; TelegramBot _telegram; GpsMessage _lastMessage; std::map<shared_ptr<TcpSession>, shared_ptr<Device>> _devices; std::vector<UserSettings> _userSettings; std::string _transmitterBuffer; sqlite3* _database; bool _transmitterAuthorized; }; inline sqlite3* Application::database() { return _database; } #endif // Application_INCLUDED
vdm-dev/gpsinformer
src/HttpParser.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef HttpParser_INCLUDED #define HttpParser_INCLUDED #include <string> #include <map> #include <vector> #include "Url.h" #include "HttpReqArg.h" class HttpParser { public: static HttpParser& getInstance(); static std::string generateRequest(const Url& url, const std::vector<HttpReqArg>& args, bool isKeepAlive = false); static std::string generateMultipartFormData(const std::vector<HttpReqArg>& args, const std::string& bondary); static std::string generateMultipartBoundary(const std::vector<HttpReqArg>& args); static std::string generateWwwFormUrlencoded(const std::vector<HttpReqArg>& args); std::string generateResponse(const std::string& data, const std::string& mimeType = "text/plain", short unsigned statusCode = 200, const std::string& statusStr = "OK", bool isKeepAlive = false); inline static std::string parseRequest(const std::string& data, std::map<std::string, std::string>& headers) { return parseHttp(true, data, headers); } inline static std::string parseRequest(const std::string& data) { return parseHttp(true, data); } inline static std::string parseResponse(const std::string& data, std::map<std::string, std::string>& headers) { return parseHttp(false, data, headers); } inline static std::string parseResponse(const std::string& data) { return parseHttp(false, data); } private: static std::string parseHttp(bool isRequest, const std::string& data, std::map<std::string, std::string>& headers); static std::string parseHttp(bool isRequest, const std::string& data); }; #endif // HttpParser_INCLUDED
vdm-dev/gpsinformer
src/tgbot/types/InlineQueryResultLocation.h
<reponame>vdm-dev/gpsinformer // // Created by <NAME> on 27/12/16 // #ifndef TGBOT_INLINEQUERYRESULTLOCATION_H #define TGBOT_INLINEQUERYRESULTLOCATION_H #include <string> #include <memory> #include "tgbot/types/InlineQueryResult.h" namespace TgBot { /** * Represents a location on a map. * @ingroup types */ class InlineQueryResultLocation : public InlineQueryResult { public: static const std::string TYPE; typedef std::shared_ptr<InlineQueryResultLocation> Ptr; InlineQueryResultLocation() : latitude(0.0) , longitude(0.0) , thumbWidth(0) , thumbHeight(0) { this->type = TYPE; } /** * Location latitude in degrees */ float latitude; /** * Location longitude in degrees */ float longitude; /** * Optional. Url of the thumbnail for the result */ std::string thumbUrl; /** * Optional. Thumbnail width. */ int32_t thumbWidth; /** * Optinal. Thumbnail height */ int32_t thumbHeight; }; } #endif //TGBOT_INLINEQUERYRESULTLOCATION_H
vdm-dev/gpsinformer
src/StdAfx.h
<filename>src/StdAfx.h // // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef StdAfx_INCLUDED #define StdAfx_INCLUDED #ifdef _WIN32 #include <sdkddkver.h> #endif #include <cstdio> #include <cstdint> #include <cwchar> #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <list> #include <vector> #include <map> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/date_time/c_local_time_adjustor.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/support/date_time.hpp> #include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/range.hpp> using namespace boost; #endif // StdAfx_INCLUDED
vdm-dev/gpsinformer
src/SslClient.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef SslClient_INCLUDED #define SslClient_INCLUDED #include <mbedtls/debug.h> #include <mbedtls/ssl.h> #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #include <mbedtls/error.h> #include <mbedtls/certs.h> #include "TcpClient.h" #include "TcpClientHandler.h" class SslClient : public TcpClientHandler<TcpClient> { public: SslClient(asio::io_service& ioService, TcpClientHandler<SslClient>* handler = 0); ~SslClient(); void connect(const std::string& server, unsigned short port); void connect(const std::string& server, const std::string& protocol); void disconnect(); void send(const std::string& data); bool isConnected() const; bool isConnecting() const; bool isDisconnecting() const; void setEventHandler(TcpClientHandler<SslClient>* handler); private: enum Status { Disconnected, Connecting, Handshake, Connected, Disconnecting, Error }; static void sslDebugCallback(void *context, int level, const char *file, int line, const char *string); static int sslReadCallback(void* context, unsigned char* buffer, size_t length); static int sslWriteCallback(void* context, const unsigned char* buffer, size_t length); bool sslInitialize(); void sslFree(); bool handleAnything(Status handleStatus, const system::error_code& error); void handleHandshake(); bool handleRead(); void handleWrite(); // TCP Client Handlers void handleTcpClientConnect(TcpClient* client); void handleTcpClientDisconnect(TcpClient* client, TcpClientHandler::Reason reason); void handleTcpClientError(TcpClient* client, const system::error_code& error); void handleTcpClientReceivedData(TcpClient* client, const std::string& data); TcpClient _tcpClient; asio::deadline_timer _timer; mbedtls_ssl_context _sslContext; mbedtls_ssl_config _sslConfiguration; mbedtls_x509_crt _sslCaRoot; mbedtls_ctr_drbg_context _sslCtrDrbg; mbedtls_entropy_context _sslEntropy; std::vector<char> _sslBuffer; std::deque<std::string> _writeBuffer; TcpClientHandler<SslClient>* _handler; Status _status; int _ioCount; bool _sslInitialized; bool _wasConnected; }; inline bool SslClient::isConnected() const { return _status == Connected; } inline bool SslClient::isConnecting() const { return _status == Connecting || _status == Handshake; } inline bool SslClient::isDisconnecting() const { return _status == Disconnecting || _status == Error; } inline void SslClient::setEventHandler(TcpClientHandler<SslClient>* handler) { _handler = handler; } #endif // SslClient_INCLUDED
vdm-dev/gpsinformer
src/Url.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef Url_INCLUDED #define Url_INCLUDED #include <string> class Url { public: Url(); Url(const std::string& url); void parse(const std::string& url); /** * Protocol part of an url. Example: https:// */ std::string protocol; /** * Host part of an url. Example: www.example.com */ std::string host; /** * Path part of an url including preceding '/' char. Example: /index.html */ std::string path; /** * Query part of an url without '?' char. Example: a=1&b=2&c=3 */ std::string query; /** * Fragment part of an url without '#' char. Example: section1 */ std::string fragment; }; #endif // Url_INCLUDED
vdm-dev/gpsinformer
src/HttpRequest.h
<reponame>vdm-dev/gpsinformer<gh_stars>1-10 // // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef HttpRequest_INCLUDED #define HttpRequest_INCLUDED #include "Url.h" class HttpRequest { public: HttpRequest(); HttpRequest(const Url& url, const std::string& data, bool longPoll = false, unsigned int tag = 0); virtual ~HttpRequest(); Url getUrl() const; std::string getData() const; unsigned int getTag() const; bool isLongPoll() const; void setUrl(const Url& url); void setData(const std::string& data); void setTag(unsigned int tag); void setLongPoll(bool longPoll = true); private: Url _url; std::string _data; unsigned int _tag; bool _longPoll; }; inline Url HttpRequest::getUrl() const { return _url; } inline std::string HttpRequest::getData() const { return _data; } inline unsigned int HttpRequest::getTag() const { return _tag; } inline bool HttpRequest::isLongPoll() const { return _longPoll; } inline void HttpRequest::setUrl(const Url& url) { _url = url; } inline void HttpRequest::setData(const std::string& data) { _data = data; } inline void HttpRequest::setTag(unsigned int tag) { _tag = tag; } inline void HttpRequest::setLongPoll(bool longPoll) { _longPoll = longPoll; } #endif // HttpRequest_INCLUDED
vdm-dev/gpsinformer
src/ChatCommand.h
// // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef ChatCommand_INCLUDED #define ChatCommand_INCLUDED #include "Application.h" class User; class ChatCommand { public: typedef void(Application::*ChatCommandHandler)(const std::vector<std::string>& command, User& user, const TgBot::Message::Ptr& originalMessage); enum Access { Default = 0, User = 1, Owner = 2 }; static std::string getAccessString(unsigned int level) { switch (level) { case ChatCommand::Owner: return "owner"; case ChatCommand::User: return "user"; default: return "unprivileged"; } } ChatCommand(const std::string& command, const std::string& description, unsigned int access, ChatCommandHandler handler) : command(command) , description(description) , access(access) , handler(handler) { } std::string command; std::string description; unsigned int access; ChatCommandHandler handler; }; #endif // ChatCommand_INCLUDED
vdm-dev/gpsinformer
src/TelegramBotHandler.h
<filename>src/TelegramBotHandler.h // // Copyright (c) 2017 <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef TelegramBotHandler_INCLUDED #define TelegramBotHandler_INCLUDED #include <tgbot/TgTypeParser.h> #include "HttpsClient.h" class TelegramBotHandler { public: virtual ~TelegramBotHandler() { } virtual void handleInlineQuery(const TgBot::InlineQuery::Ptr& inlineQuery) { } virtual void handleChosenInlineResult(const TgBot::ChosenInlineResult::Ptr& chosenInlineResult) { } virtual void handleCallbackQuery(const TgBot::CallbackQuery::Ptr& callbackQuery) { } virtual void handleMessage(const TgBot::Message::Ptr& message) { } virtual void handleOwnMessage(const TgBot::Message::Ptr& message) { } virtual void handleGetMe(const TgBot::User::Ptr& user) { } }; #endif // TelegramBotHandler_INCLUDED
wujiangwei/FFToastView
FFToastView.h
<gh_stars>1-10 // // FFToastView.h // // Created by Kevin on 14-3-17. // Copyright (c) 2014年 Wu. All rights reserved. // #import <UIKit/UIKit.h> @interface FFToastView : UIView { @private UILabel *_label; BOOL _stoped; BOOL _refreshed; } //get handle + (id)sharedInstance; //config toast font and show time(normal toast text and long toast text) //all the param can not be nil and bigger than zero //if nil or not bigger than zero,it will invalid + (void)configFont:(UIFont *)toastFont normalTime:(CGFloat)normalTime longTime:(CGFloat)longTime; //show in custom view - (void)showToast:(NSString *)message inView:(UIView *)superView; //centerOffY:距离屏幕中间的像素 - (void)showToast:(NSString *)message inView:(UIView *)superView centerOffY:(CGFloat)centerOffY; //show toast in window - (void)showToast:(NSString *)message; - (void)showToast:(NSString *)message centerOffY:(CGFloat)centerOffY; @end
michael-groble/motioncapture
MotionCapture/MCMotionPeripheral.h
// Copyright (c) 2014 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #import <Foundation/Foundation.h> #import "MCMeasurement.h" @interface MCMotionPeripheral : NSObject { @protected NSString* _uuid; NSString* _type; NSTimeInterval _updateInterval; BOOL _accelerometerEnabled; BOOL _gyroEnabled; BOOL _magnetometerEnabled; BOOL _deviceMotionEnabled; } @property (nonatomic, strong, readonly) NSString* uuid; @property (nonatomic, strong, readonly) NSString* type; @property (nonatomic, strong) NSString* name; @property (nonatomic, assign) MCBodySide bodySide; @property (nonatomic, assign) MCBodyPart bodyPart; @property (nonatomic, strong, readonly) NSString* locationString; @property(assign, nonatomic) NSTimeInterval updateInterval; @property(assign, nonatomic) BOOL autoconnect; @property(readonly, nonatomic, getter=isAccelerometerAvailable) BOOL accelerometerAvailable; @property(readonly, nonatomic, getter=isGyroAvailable) BOOL gyroAvailable; @property(readonly, nonatomic, getter=isMagnetometerAvailable) BOOL magnetometerAvailable; @property(readonly, nonatomic, getter=isAccelerometerActive) BOOL accelerometerActive; @property(readonly, nonatomic, getter=isGyroActive) BOOL gyroActive; @property(readonly, nonatomic, getter=isMagnetometerActive) BOOL magnetometerActive; @property(readonly, nonatomic, getter=isDeviceMotionActive) BOOL deviceMotionActive; @property(readonly, nonatomic, getter=isDeviceMotionAvailable) BOOL deviceMotionAvailable; @property(assign, nonatomic, getter=isAccelerometerEnabled) BOOL accelerometerEnabled; @property(assign, nonatomic, getter=isGyroEnabled) BOOL gyroEnabled; @property(assign, nonatomic, getter=isMagnetometerActive) BOOL magnetometerEnabled; @property(assign, nonatomic, getter=isDeviceMotionActive) BOOL deviceMotionEnabled; - (NSTimeInterval)secondsFromUnixEpochForDeviceTime:(NSTimeInterval)deviceTime; @end
michael-groble/motioncapture
MotionCapture/MCMeasurement.h
// Copyright (c) 2014 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import <CoreMotion/CoreMotion.h> typedef enum { MCMeasurementAttitueType, MCMeasurementRotationRateType, MCMeasurementGravityType, MCMeasurementUserAccelerationType, MCMeasurementMagneticFieldType, MCMeasurementAccelerometerType, MCMeasurementGyroscopeType, MCMeasurementMagnetometerType, } MCMeasurementType; typedef enum { MCBodySideUnknown, MCBodySideLeft, MCBodySideRight } MCBodySide; typedef enum { MCBodyPartUnknown, MCBodyPartHead, MCBodyPartArm, MCBodyPartWrist, MCBodyPartHip, MCBodyPartAnkle } MCBodyPart; @class MCMotionPeripheral; @class MCGyroData; @class MCAccelerometerData; @class MCMagnetometerData; @interface MCMeasurement : NSManagedObject @property (nonatomic, strong) NSNumber * type; @property (nonatomic, strong) NSNumber * timestamp; @property (nonatomic, strong) NSNumber * x; @property (nonatomic, strong) NSNumber * y; @property (nonatomic, strong) NSNumber * z; @property (nonatomic, strong) NSNumber * w; @property (nonatomic, strong) NSNumber * accuracy; @property (nonatomic, strong) NSNumber* bodySide; @property (nonatomic, strong) NSNumber* bodyPart; @property (nonatomic, strong) NSNumber* isLocal; - (MCMeasurement*)setAttitudeFromMotion:(CMDeviceMotion*)motion device:(MCMotionPeripheral*)device; - (MCMeasurement*)setRotationRateFromMotion:(CMDeviceMotion*)motion device:(MCMotionPeripheral*)device; - (MCMeasurement*)setGravityFromMotion:(CMDeviceMotion*)motion device:(MCMotionPeripheral*)device; - (MCMeasurement*)setUserAccelerationFromMotion:(CMDeviceMotion*)motion device:(MCMotionPeripheral*)device; - (MCMeasurement*)setMagneticFieldFromMotion:(CMDeviceMotion*)motion device:(MCMotionPeripheral*)device; - (MCMeasurement*)setRotationRate:(MCGyroData*)data device:(MCMotionPeripheral*)device; - (MCMeasurement*)setAcceleration:(MCAccelerometerData*)data device:(MCMotionPeripheral*)device; - (MCMeasurement*)setMagneticField:(MCMagnetometerData*)data device:(MCMotionPeripheral*)device; @end
ftl999/libkatherine
src/udp.c
<reponame>ftl999/libkatherine // // Created by petr on 29.5.18. // Edited by Felix for Windows on 28.09.18 // #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #include <sys/socket.h> #else #include "unistd.h" #include <WinSock2.h> #include <WS2tcpip.h> #include <sys/types.h> WSADATA wsaData; int UDP_connection_counter = 0; _Bool WSDataInitialized = 0; static inline void INITWSDATA_MACRO() { #ifdef WIN32 UDP_connection_counter++; if (!WSDataInitialized) { if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0) WSDataInitialized = true; } #endif } static inline void WSDATACLEANUP_MACRO() { #ifdef WIN32 UDP_connection_counter--; if (UDP_connection_counter <= 0) { WSACleanup(); WSDataInitialized = false; UDP_connection_counter = 0; } #endif } #endif #include <string.h> #include <katherine/udp.h> /** * Initialize new UDP session. * @param u UDP session to initialize * @param local_port Local port number * @param remote_addr Remote IP address * @param remote_port Remote port number * @param timeout_ms Communication timeout in milliseconds (zero if disabled) * @return Error code. */ int katherine_udp_init(katherine_udp_t *u, uint16_t local_port, const char *remote_addr, uint16_t remote_port, uint32_t timeout_ms) { INITWSDATA_MACRO(); // Create socket. if ((u->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { goto err_socket; } // Setup and bind the socket address. u->addr_local.sin_family = AF_INET; u->addr_local.sin_port = htons(local_port); u->addr_local.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(u->sock, (SOCKET_ADDR_T *) &u->addr_local, sizeof(u->addr_local)) == -1) { goto err_bind; } //Added: int size = sizeof(u->addr_local); getsockname(u->sock, (SOCKET_ADDR_T *)&u->addr_local, (int *)&size); // Set remote socket address. u->addr_remote.sin_family = AF_INET; u->addr_remote.sin_port = htons(remote_port); if (inet_pton(AF_INET, remote_addr, &u->addr_remote.sin_addr) <= 0) { goto err_remote; } CREATEMUTEX(u->mutex); if (!IS_MUTEX_VALID(u->mutex)) { goto err_mutex; } if (timeout_ms > 0) { // Set socket timeout. if (SETTIMEOUT(u->sock, timeout_ms) < 0) { goto err_timeout; } } return 0; err_mutex: err_remote: err_timeout: err_bind: CLOSESOCK(u->sock); WSDATACLEANUP_MACRO(); err_socket: u->sock = -1; return 1; } /** * Finalize UDP session. * @param u UDP session to finalize */ void katherine_udp_fini(katherine_udp_t *u) { CLOSESOCK(u->sock); WSDATACLEANUP_MACRO(); // Ignoring return code below. // DESTROYMUTEX(u->mutex); } /** * Send a message (unreliable). * @param u UDP session * @param data Message start * @param count Message length in bytes * @return Error code. */ int katherine_udp_send_exact(katherine_udp_t* u, const void* data, size_t count) { ssize_t sent; size_t total = 0; do { sent = sendto(u->sock, ((const char*)data) + total, count - total, 0, (SOCKET_ADDR_T *) &u->addr_remote, sizeof(u->addr_remote)); if (sent == -1) { return 1; } total += sent; } while (total < count); return 0; } /** * Receive a message (unreliable). * @param u UDP session * @param data Inbound buffer start * @param count Inbound buffer size in bytes * @return Error code. */ int katherine_udp_recv_exact(katherine_udp_t* u, void* data, size_t count) { ssize_t received; size_t total = 0; socklen_t addr_len = sizeof(u->addr_remote); while (total < count) { received = recvfrom(u->sock, ((char*)data) + total, count - total, 0, (SOCKET_ADDR_T *) &u->addr_remote, &addr_len); if (received == -1) { return 1; } total += received; } return 0; } /** * Receive a portion of a message (unreliable). * @param u UDP session * @param data Inbound buffer start * @param count Inbound buffer size in bytes * @return Error code. */ int katherine_udp_recv(katherine_udp_t* u, void* data, size_t* count) { socklen_t addr_len = sizeof(u->addr_remote); ssize_t received = recvfrom(u->sock, data, *count, 0, (SOCKET_ADDR_T *) &u->addr_remote, &addr_len); if (received == SOCKET_ERROR) { OUTPUT_SOCKET_ERROR(); return 1; } *count = (size_t) received; return 0; } /** * Lock mutual exclusion synchronization primitive. * @param u UDP session * @return Error code. */ int katherine_udp_mutex_lock(katherine_udp_t *u) { return ACQUIRE_MUTEX(u->mutex); } /** * Unlock mutual exclusion synchronization primitive. * @param u UDP session * @return Error code. */ int katherine_udp_mutex_unlock(katherine_udp_t *u) { return RELEASE_MUTEX(u->mutex); }
ftl999/libkatherine
src/bmc.c
// // Created by petr on 9.6.18. // #include <katherine/bmc.h> #include <string.h> /** * Initialize new BMC matrix. * @param bmc Matrix to initialize. * @return Error code. */ int katherine_bmc_init(katherine_bmc_t *bmc) { // Nothing done. return 0; } /** * Finalize BMC matrix. * @param bmc Matrix to finalize. */ void katherine_bmc_fini(katherine_bmc_t *bmc) { // Nothing done. } /** * Load matrix from a file. * @param bmc Target matrix. * @param data File path. * @return Error code. */ int katherine_bmc_load(katherine_bmc_t *bmc, const char *data) { // Reset the pixel values. memset(&bmc->pconf, 0, 65536); int x, y; int *buffer = (int*) bmc->pconf; // Parse data from BMC format. for (int i = 0; i < 65536; ++i) { x = i % 256; y = 255 - i / 256; buffer[(64 * x) + (y >> 2)] |= data[i] << (8 * (3 - (y % 4))); } return 0; }
ftl999/libkatherine
include/katherine/bmc.h
// // Created by petr on 9.6.18. // #ifndef THESIS_BMC_H #define THESIS_BMC_H /** * @file * @brief Functions related to the BMC matrix configuration format. */ #ifdef __cplusplus extern "C" { #endif typedef struct katherine_bmc { char pconf[65536]; } katherine_bmc_t; int katherine_bmc_init(katherine_bmc_t *); void katherine_bmc_fini(katherine_bmc_t *); int katherine_bmc_load(katherine_bmc_t *, const char *); #ifdef __cplusplus } #endif #endif //THESIS_BMC_H
ftl999/libkatherine
include/katherine/MultiplattformNetwork.h
<filename>include/katherine/MultiplattformNetwork.h<gh_stars>0 #pragma once #ifndef WIN32 #include <arpa/inet.h> #include <sys/time.h> #define SOCKETTYPE int #define SOCKET_ADDR_T struct sockaddr_in #define CLOSESOCK(sock) close(sock) #define INITWSDATA() #define SOCKET_ERROR -1 #define INVALID_SOCKET -1 static inline int TIMEOUT_MAKRO(int sock, uint32_t timeout_ms) { struct timeval val; val.tv_sec = timeout_ms / 1000.f; val.tv_usec = 1000 * (timeout_ms % 1000); return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &val, sizeof(struct timeval)); } #define SETTIMEOUT(sock, timeout_ms) TIMEOUT_MAKRO(sock, timeout_ms) #define OUTPUT_SOCKET_ERROR() #else #include "Winsock2.h" #define SOCKETTYPE SOCKET #define SOCKET_ADDR_T SOCKADDR_IN #define CLOSESOCK(sock) if(sock > 0) closesocket(sock) static inline int TIMEOUT_MAKRO(SOCKET sock, uint32_t timeout_ms) { char* timeout = (char*)&timeout_ms; return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, timeout, sizeof(uint32_t)); } #define SETTIMEOUT(sock, timeout_ms) TIMEOUT_MAKRO(sock, timeout_ms) static inline void OUTPUT_SOCKET_ERROR(int code) { char* out; switch (code) { case WSANOTINITIALISED: out = "Not Initialized"; break; case WSAENETDOWN: out = "Subsystem fail"; break; case WSAEFAULT: out = "Buffer invalid memory"; break; case WSAEINVAL: out = "Server setup incorrect"; break; case WSAEISCONN: out = "Socket is connected, but should not"; break; case WSAENETRESET: out = "UDP expired"; break; case WSAENOTSOCK: out = "Wrong descriptor"; break; case WSAEOPNOTSUPP: out = "Socket not supported"; break; case WSAESHUTDOWN: out = "Socket already shuted down"; break; case WSAEWOULDBLOCK: out = "Socket can't block"; break; case WSAEMSGSIZE: out = "Message too large"; break; case WSAETIMEDOUT: out = "Socket timed out"; break; case WSAECONNRESET: out = "Connection was reseted"; break; default: out = "Unknown error code"; } out; } #define OUTPUT_SOCKET_ERROR() OUTPUT_SOCKET_ERROR(WSAGetLastError()) //Overwritten in udp.c #define INITWSDATA() #endif
ftl999/libkatherine
include/katherine/KatherineConfigParser.h
#pragma once #include <katherine/katherine.h> namespace YAML { class Node; } class KatherineConfigParser { public: KatherineConfigParser(const char* configFile); ~KatherineConfigParser(); int getFrameCount(); katherine_config_t* getConfig(); size_t getBufferMD_Size(); size_t getBufferPixel_Size(); protected: void configure_yaml(katherine_config_t& config, const YAML::Node& yml); private: int frame_count; YAML::Node* yml; katherine_config_t config; size_t buffer_md_items_size; size_t buffer_pixel_items_size; };
ftl999/libkatherine
include/katherine/MultiplattformTypes.h
#pragma once #ifndef WIN32 #include <pthread.h> #define MUTEXTYPE pthread_mutex_t #define CREATEMUTEX(mux) pthread_mutex_init(&mux, NULL) #define DESTROYMUTEX(mux) pthread_mutex_destroy(&mux) #define IS_MUTEX_VALID(mux) 1 #define ACQUIRE_MUTEX(mux) pthread_mutex_lock(&mux); #define RELEASE_MUTEX(mux) pthread_mutex_unlock(&mux) #define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) #else #include <Windows.h> #define MUTEXTYPE HANDLE #define IS_MUTEX_VALID(mux) ((mux != NULL) && (mux != INVALID_HANDLE_VALUE)) #define CREATEMUTEX(mux) mux = CreateMutex(NULL, FALSE, NULL) #define DESTROYMUTEX(mux) if(IS_MUTEX_VALID(mux)) CloseHandle(mux) #define ACQUIRE_MUTEX(mux) WaitForSingleObject(mux, INFINITE); #define RELEASE_MUTEX(mux) ReleaseMutex(mux) #define PACKED( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop) ) #endif
ftl999/libkatherine
src/status.c
<gh_stars>0 // // Created by petr on 14.6.18. // #include <stdio.h> #include <string.h> #include <katherine/status.h> #include <katherine/device.h> #include <katherine/command_interface.h> #ifndef WIN32 #define PACKED( __Declaration__ ) __Declaration__ __attribute__((__packed__)) #else #define PACKED( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop) ) #endif /** * Inquire the status of the readout. * @param device Katherine device * @param status Retrieved status information * @return Error code. */ int katherine_get_readout_status(katherine_device_t *device, katherine_readout_status_t *status) { int res; res = katherine_cmd_get_readout_status(&device->control_socket); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; PACKED( const struct { uint8_t hw_type; uint8_t hw_revision; uint16_t hw_serial_number; uint16_t fw_version; }) *status_crd = (const void *) &crd; status->hw_type = status_crd->hw_type; status->hw_revision = status_crd->hw_revision; status->hw_serial_number = status_crd->hw_serial_number; status->fw_version = status_crd->fw_version; return 0; err: return res; } /** * Inquire the communication status of the readout. * @param device Katherine device * @param status Retrieve status information * @return Error code. */ int katherine_get_comm_status(katherine_device_t *device, katherine_comm_status_t *status) { int res; res = katherine_cmd_get_comm_status(&device->control_socket); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; PACKED( const struct { uint8_t comm_lines_mask; uint8_t total_data_rate; uint8_t chip_detected_flag; }) *status_crd = (const void *) &crd; status->comm_lines_mask = status_crd->comm_lines_mask; status->data_rate = 5u * status_crd->total_data_rate; status->chip_detected = status_crd->chip_detected_flag; return 0; err: return res; } /** * Retrieve Timepix3 chip identifier. * @param device Katherine device * @param s_chip_id Start of string buffer of size `KATHERINE_CHIP_ID_STR_SIZE` * @return Error code. */ int katherine_get_chip_id(katherine_device_t *device, char *s_chip_id) { int res; res = katherine_cmd_echo_chip_id(&device->control_socket); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; int chip_id = *(int*) crd; int x = (chip_id & 0xF) - 1; int y = (chip_id >> 4) & 0xF; int w = (chip_id >> 8) & 0xFFF; memset(s_chip_id, '\0', KATHERINE_CHIP_ID_STR_SIZE); sprintf(s_chip_id, "%c%d-W000%d", 65 + x, y, w); return 0; err: return res; } /** * Measure the temperature of the readout. * @param device Katherine device * @param temperature Measured temperature in Celsius. * @return Error code. */ int katherine_get_readout_temperature(katherine_device_t *device, float *temperature) { int res; res = katherine_cmd_get_readout_temperature(&device->control_socket); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; *temperature = *(float*) crd; return 0; err: return res; } /** * Measure the temperature of the sensor chip. * @param device Katherine device * @param temperature Measured temperature in Celsius. * @return Error code. */ int katherine_get_sensor_temperature(katherine_device_t *device, float *temperature) { int res; res = katherine_cmd_get_sensor_temperature(&device->control_socket); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; *temperature = *(float*) crd; return 0; err: return res; } /** * Test communication between the readout and the sensor chip (may take several seconds). * @param device Katherine device * @return Error code. */ int katherine_perform_digital_test(katherine_device_t *device) { int res; res = katherine_cmd_digital_test(&device->control_socket); if (res) goto err; char crd[8]; int attempts = 100; // 10 seconds do { // This can take a while, spin for a limited amount of attempts. res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); --attempts; } while (res && attempts); if (res) goto err; if (crd[0] != 64) { // The test did not go well. res = 1; goto err; } return 0; err: return res; } /** * Measure ADC voltage. * @param device Katherine device * @param channel_id Index of the measured ADC channel * @param voltage Retrieved voltage * @return Error code. */ int katherine_get_adc_voltage(katherine_device_t *device, unsigned char channel_id, float *voltage) { int res; res = katherine_cmd_get_adc_voltage(&device->control_socket, channel_id); if (res) goto err; char crd[8]; res = katherine_cmd_wait_ack_crd(&device->control_socket, crd); if (res) goto err; *voltage = *(float*) crd; return 0; err: return res; }
ftl999/libkatherine
include/katherine/config.h
// // Created by petr on 10.6.18. // #ifndef THESIS_CONFIG_H #define THESIS_CONFIG_H /** * @file * @brief Functions related to detector and readout configuration. */ #include <stdbool.h> #include <stdint.h> #include <katherine/bmc.h> #ifdef __cplusplus extern "C" { #endif typedef struct katherine_device katherine_device_t; typedef struct katherine_trigger { bool enabled; char channel; bool use_falling_edge; } katherine_trigger_t; typedef union katherine_dacs { uint16_t array[18]; struct { uint16_t Ibias_Preamp_ON; uint16_t Ibias_Preamp_OFF; uint16_t VPReamp_NCAS; uint16_t Ibias_Ikrum; uint16_t Vfbk; uint16_t Vthreshold_fine; uint16_t Vthreshold_coarse; uint16_t Ibias_DiscS1_ON; uint16_t Ibias_DiscS1_OFF; uint16_t Ibias_DiscS2_ON; uint16_t Ibias_DiscS2_OFF; uint16_t Ibias_PixelDAC; uint16_t Ibias_TPbufferIn; uint16_t Ibias_TPbufferOut; uint16_t VTP_coarse; uint16_t VTP_fine; uint16_t Ibias_CP_PLL; uint16_t PLL_Vcntrl; } named; } katherine_dacs_t; typedef enum katherine_phase { PHASE_1 = 0, PHASE_2 = 1, PHASE_4 = 2, PHASE_8 = 3, PHASE_16 = 4, } katherine_phase_t; typedef enum katherine_freq { FREQ_40 = 1, FREQ_80 = 2, FREQ_160 = 3, } katherine_freq_t; typedef enum katherine_acquisition_mode { ACQUISITION_MODE_TOA_TOT = 0, ACQUISITION_MODE_ONLY_TOA = 1, ACQUISITION_MODE_EVENT_ITOT = 2, } katherine_acquisition_mode_t; typedef struct katherine_config { katherine_bmc_t pixel_config; bool seq_readout_start; bool fast_vco_enabled; katherine_acquisition_mode_t acq_mode; unsigned char bias_id; double acq_time; // ns int no_frames; float bias; katherine_trigger_t start_trigger; bool delayed_start; katherine_trigger_t stop_trigger; bool gray_enable; bool polarity_holes; katherine_phase_t phase; katherine_freq_t freq; katherine_dacs_t dacs; } katherine_config_t; int katherine_configure(katherine_device_t *, const katherine_config_t *); int katherine_set_all_pixel_config(katherine_device_t *, const katherine_bmc_t *); int katherine_set_acq_time(katherine_device_t *, double); int katherine_set_acq_mode(katherine_device_t *, katherine_acquisition_mode_t, bool); int katherine_set_no_frames(katherine_device_t *, int); int katherine_set_bias(katherine_device_t *, unsigned char, float); int katherine_set_seq_readout_start(katherine_device_t *, int); int katherine_acquisition_setup(katherine_device_t *, const katherine_trigger_t *, bool, const katherine_trigger_t *); typedef enum katherine_tpx3_reg { TPX3_REG_TEST_PULSE_METHOD = 0, TPX3_REG_NUMBER_TEST_PULSES = 1, TPX3_REG_OUT_BLOCK_CONFIG = 2, TPX3_REG_PLL_CONFIG = 3, TPX3_REG_GENERAL_CONFIG = 4, TPX3_REG_SLVS_CONFIG = 5, TPX3_REG_POWER_PULSING_PATTERN = 6, TPX3_REG_SET_TIMER_LOW = 7, TPX3_REG_SET_TIMER_MID = 8, TPX3_REG_SET_TIMER_HIGH = 9, TPX3_REG_SENSE_DAC_SELECTOR = 10, TPX3_REG_EXT_DAC_SELECTOR = 11, } katherine_tpx3_reg_t; int katherine_set_sensor_register(katherine_device_t *, char, int32_t); int katherine_update_sensor_registers(katherine_device_t *); int katherine_set_dacs(katherine_device_t *, const katherine_dacs_t *); #ifdef __cplusplus } #endif #endif //THESIS_CONFIG_H
ftl999/libkatherine
include/katherine/device.h
<reponame>ftl999/libkatherine<filename>include/katherine/device.h<gh_stars>0 // // Created by petr on 14.6.18. // #ifndef THESIS_DEVICE_H #define THESIS_DEVICE_H /** * @file * @brief Functions related to Katherine. */ #include <katherine/udp.h> #ifdef __cplusplus extern "C" { #endif typedef struct katherine_device { katherine_udp_t control_socket; katherine_udp_t data_socket; } katherine_device_t; int katherine_device_init(katherine_device_t *device, const char *addr); void katherine_device_fini(katherine_device_t * device); #ifdef __cplusplus } #endif #endif //THESIS_DEVICE_H
ftl999/libkatherine
include/katherine/status.h
<filename>include/katherine/status.h // // Created by petr on 14.6.18. // #ifndef THESIS_STATUS_H #define THESIS_STATUS_H /** * @file * @brief Functions related to readout status inquiry. */ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif typedef struct katherine_device katherine_device_t; typedef struct katherine_readout_status { int hw_type; int hw_revision; int hw_serial_number; int fw_version; } katherine_readout_status_t; int katherine_get_readout_status(katherine_device_t *, katherine_readout_status_t *); typedef struct katherine_comm_status { uint8_t comm_lines_mask; uint32_t data_rate; bool chip_detected; } katherine_comm_status_t; int katherine_get_comm_status(katherine_device_t *, katherine_comm_status_t *); #define KATHERINE_CHIP_ID_STR_SIZE 16 int katherine_get_chip_id(katherine_device_t *, char *); int katherine_get_readout_temperature(katherine_device_t *, float *); int katherine_get_sensor_temperature(katherine_device_t *, float *); int katherine_perform_digital_test(katherine_device_t *); int katherine_get_adc_voltage(katherine_device_t *, unsigned char, float *); #ifdef __cplusplus } #endif #endif //THESIS_STATUS_H
ftl999/libkatherine
include/katherine/acquisition.h
<filename>include/katherine/acquisition.h // // Created by petr on 29.5.18. // #ifndef THESIS_ACQUISITION_H #define THESIS_ACQUISITION_H /** * @file * @brief Functions related to the data acquisition process. */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <katherine/device.h> #include <katherine/config.h> #define KATHERINE_MD_SIZE 6 #ifdef __cplusplus extern "C" { #endif typedef struct katherine_coord { uint8_t x; uint8_t y; } katherine_coord_t; typedef struct katherine_px_f_toa_tot { katherine_coord_t coord; uint8_t ftoa; uint64_t toa; uint16_t tot; } katherine_px_f_toa_tot_t; typedef struct katherine_px_toa_tot { katherine_coord_t coord; uint64_t toa; uint8_t hit_count; uint16_t tot; } katherine_px_toa_tot_t; typedef struct katherine_px_f_toa_only { katherine_coord_t coord; uint8_t ftoa; uint64_t toa; } katherine_px_f_toa_only_t; typedef struct katherine_px_toa_only { katherine_coord_t coord; uint64_t toa; uint8_t hit_count; } katherine_px_toa_only_t; typedef struct katherine_px_f_event_itot { katherine_coord_t coord; uint8_t hit_count; uint16_t event_count; uint16_t integral_tot; } katherine_px_f_event_itot_t; typedef struct katherine_px_event_itot { katherine_coord_t coord; uint16_t event_count; uint16_t integral_tot; } katherine_px_event_itot_t; typedef struct katherine_frame_info { uint64_t received_pixels; uint64_t sent_pixels; uint64_t lost_pixels; union { struct { uint32_t msb, lsb; } b; uint64_t d; } start_time; union { struct { uint32_t msb, lsb; } b; uint64_t d; } end_time; } katherine_frame_info_t; typedef struct katherine_acquisition_handlers { void (*pixels_received)(const void *, size_t); void (*frame_started)(int); void (*frame_ended)(int, bool, const katherine_frame_info_t *); } katherine_acquisition_handlers_t; typedef enum katherine_readout_type { READOUT_SEQUENTIAL = 0, READOUT_DATA_DRIVEN = 1 } katherine_readout_type_t; typedef enum katherine_acquisition_state { ACQUISITION_NOT_STARTED = 0, ACQUISITION_RUNNING = 1, ACQUISITION_SUCCEEDED = 2, ACQUISITION_TIMED_OUT = 3, ACQUISITION_ABORTED = 4 } katherine_acquisition_state_t; typedef struct katherine_acquisition { katherine_device_t *device; char state; char readout_mode; char acq_mode; bool fast_vco_enabled; void *md_buffer; size_t md_buffer_size; void *pixel_buffer; size_t pixel_buffer_size; size_t pixel_buffer_valid; size_t pixel_buffer_max_valid; int requested_frames; int completed_frames; size_t dropped_measurement_data; katherine_acquisition_handlers_t handlers; katherine_frame_info_t current_frame_info; uint64_t last_toa_offset; } katherine_acquisition_t; int katherine_acquisition_init(katherine_acquisition_t *, katherine_device_t *, size_t md_buffer_size, size_t pixel_buffer_size); void katherine_acquisition_fini(katherine_acquisition_t *); int katherine_acquisition_begin(katherine_acquisition_t *, const katherine_config_t *, char); int katherine_acquisition_abort(katherine_acquisition_t *); int katherine_acquisition_read(katherine_acquisition_t *); const char * katherine_str_acquisition_status(char); #ifdef __cplusplus } #endif #endif //THESIS_ACQUISITION_H
ftl999/libkatherine
include/katherine/katherine.h
<reponame>ftl999/libkatherine<filename>include/katherine/katherine.h // // Created by petr on 29.5.18. // #ifndef THESIS_KATHERINE_H #define THESIS_KATHERINE_H /** * @file * @brief Main umbrella header. */ #include "acquisition.h" #include "bmc.h" #include "config.h" #include "device.h" #include "status.h" #include "udp.h" /* #include <katherine/acquisition.h> #include <katherine/bmc.h> #include <katherine/config.h> #include <katherine/device.h> #include <katherine/status.h> #include <katherine/udp.h>*/ #endif //THESIS_KATHERINE_H
ftl999/libkatherine
include/katherine/udp.h
<gh_stars>0 // // Created by petr on 29.5.18. // #ifndef THESIS_UDP_H #define THESIS_UDP_H /** * @file * @brief Functions related to the UDP communication layer. */ #include <stdio.h> #ifndef WIN32 #include <arpa/inet.h> #include <pthread.h> #else #include "Winsock2.h" #include <Windows.h> #include <stdint.h> #pragma comment(lib, "Ws2_32.lib") //Link against Ws2_32.lib #endif #include "MultiplattformNetwork.h" #include "MultiplattformTypes.h" #ifdef __cplusplus extern "C" { #endif typedef struct katherine_udp { SOCKETTYPE sock; SOCKET_ADDR_T addr_local; SOCKET_ADDR_T addr_remote; MUTEXTYPE mutex; } katherine_udp_t; int katherine_udp_init(katherine_udp_t *u, uint16_t local_port, const char *remote_addr, uint16_t remote_port, uint32_t timeout_ms); void katherine_udp_fini(katherine_udp_t * u); int katherine_udp_send_exact(katherine_udp_t* u, const void* data, size_t count); int katherine_udp_recv_exact(katherine_udp_t* u, void*, size_t count); int katherine_udp_recv(katherine_udp_t* u, void*, size_t* count); int katherine_udp_mutex_lock(katherine_udp_t* u); int katherine_udp_mutex_unlock(katherine_udp_t* u); #ifdef __cplusplus } #endif #endif //THESIS_UDP_H
ftl999/libkatherine
src/device.c
// // Created by petr on 14.6.18. // #include <katherine/device.h> #ifndef DOXYGEN_SHOULD_SKIP_THIS static const uint16_t CONTROL_PORT = 1555; static const uint16_t DATA_PORT = 1556; static const uint16_t REMOTE_PORT = 1555; static const uint32_t CONTROL_TIMEOUT = 100; static const uint32_t DATA_TIMEOUT = 2000; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /** * Initialize Katherine device. * @param device Katherine device * @param addr IP address * @return Error code. */ int katherine_device_init(katherine_device_t *device, const char *addr) { int res; if ((res = katherine_udp_init(&device->control_socket, CONTROL_PORT, addr, REMOTE_PORT, CONTROL_TIMEOUT))) { goto err_control; } if ((res = katherine_udp_init(&device->data_socket, DATA_PORT, addr, REMOTE_PORT, DATA_TIMEOUT))) { goto err_data; } return 0; err_data: katherine_udp_fini(&device->control_socket); err_control: return res; } /** * Finalize Katherine device. * @param device Device to finalize. */ void katherine_device_fini(katherine_device_t *device) { katherine_udp_fini(&device->data_socket); katherine_udp_fini(&device->control_socket); }
ftl999/libkatherine
src/acquisition.c
<reponame>ftl999/libkatherine // // Created by petr on 29.5.18. // #include <stdlib.h> #include <string.h> #include <katherine/acquisition.h> #include <katherine/command_interface.h> #include "katherine/MultiplattformTypes.h" #ifndef DOXYGEN_SHOULD_SKIP_THIS PACKED( typedef struct md { uint64_t : 44; uint8_t header : 4; }) md_t; PACKED( typedef struct md_time_offset { uint32_t offset : 32; // 31..0 uint16_t : 12; // 43..32 }) md_time_offset_t; PACKED( typedef struct md_frame_finished { uint64_t n_sent : 44; // 0..43 }) md_frame_finished_t; PACKED( typedef struct md_time_lsb { uint32_t lsb : 32; // 31..0 uint16_t : 12; // 43..32 }) md_time_lsb_t; PACKED( typedef struct md_time_msb { uint16_t msb : 16; // 15..0 uint32_t : 24; // 43..16 }) md_time_msb_t; PACKED( typedef struct md_lost_px { uint64_t n_lost : 44; // 43..0 }) md_lost_px_t; #define DEFINE_PMD_MAP(SUFFIX) \ static inline void\ pmd_##SUFFIX##_map(katherine_px_##SUFFIX##_t *dst, const pmd_##SUFFIX##_t *src, const katherine_acquisition_t *acq) #define DEFINE_PMD_PAIR(NAME) \ dst->NAME = src->NAME #define DEFINE_PMD_PAIR_TOA \ dst->toa = src->toa + acq->last_toa_offset #define DEFINE_PMD_PAIR_COORD \ {\ dst->coord.x = src->coord_x;\ dst->coord.y = src->coord_y;\ } PACKED( typedef struct pmd_f_toa_tot { uint16_t ftoa : 4; // 0..3 uint16_t tot : 10; // 13..4 uint16_t toa : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_f_toa_tot_t; DEFINE_PMD_MAP(f_toa_tot) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR_TOA; DEFINE_PMD_PAIR(ftoa); DEFINE_PMD_PAIR(tot); } PACKED( typedef struct pmd_toa_tot { uint16_t hit_count : 4; // 0..3 uint16_t tot : 10; // 13..4 uint16_t toa : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_toa_tot_t; DEFINE_PMD_MAP(toa_tot) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR_TOA; DEFINE_PMD_PAIR(hit_count); DEFINE_PMD_PAIR(tot); } PACKED( typedef struct pmd_f_toa_only { uint16_t ftoa : 4; // 0..3 uint16_t : 10; // 13..4 uint16_t toa : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_f_toa_only_t; DEFINE_PMD_MAP(f_toa_only) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR_TOA; DEFINE_PMD_PAIR(ftoa); } PACKED( typedef struct pmd_toa_only { uint16_t hit_count : 4; // 0..3 uint16_t : 10; // 13..4 uint16_t toa : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_toa_only_t; DEFINE_PMD_MAP(toa_only) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR_TOA; DEFINE_PMD_PAIR(hit_count); } PACKED( typedef struct pmd_f_event_itot { uint16_t hit_count : 4; // 0..3 uint16_t event_count : 10; // 13..4 uint16_t integral_tot : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_f_event_itot_t; DEFINE_PMD_MAP(f_event_itot) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR(hit_count); DEFINE_PMD_PAIR(event_count); DEFINE_PMD_PAIR(integral_tot); } PACKED( typedef struct pmd_event_itot { uint16_t : 4; // 0..3 uint16_t event_count : 10; // 13..4 uint16_t integral_tot : 14; // 27..14 uint16_t coord_x : 8; // 35..28 uint16_t coord_y : 8; // 43..36 uint16_t : 4; // 44..47 }) pmd_event_itot_t; DEFINE_PMD_MAP(event_itot) { DEFINE_PMD_PAIR_COORD; DEFINE_PMD_PAIR(event_count); DEFINE_PMD_PAIR(integral_tot); } #undef DEFINE_PMD_MAP #undef DEFINE_PMD_PAIR #undef DEFINE_PMD_PAIR_COORD #undef DEFINE_PMD_PAIR_TOA static inline void flush_buffer(katherine_acquisition_t *acq) { acq->handlers.pixels_received(acq->pixel_buffer, acq->pixel_buffer_valid); acq->current_frame_info.received_pixels += acq->pixel_buffer_valid; acq->pixel_buffer_valid = 0; } static inline void handle_new_frame(katherine_acquisition_t *acq, const void *data) { memset(&acq->current_frame_info, 0, sizeof(katherine_frame_info_t)); acq->handlers.frame_started(acq->completed_frames); } static inline void handle_timestamp_offset_driven_mode(katherine_acquisition_t *acq, const void *data) { const md_time_offset_t *md = data; acq->last_toa_offset = 16384 * md->offset; } static inline void handle_current_frame_finished(katherine_acquisition_t *acq, const void *data) { const md_frame_finished_t *md = data; flush_buffer(acq); acq->current_frame_info.sent_pixels = md->n_sent; acq->handlers.frame_ended(acq->completed_frames, true, &acq->current_frame_info); ++acq->completed_frames; if (acq->completed_frames == acq->requested_frames) { acq->state = ACQUISITION_SUCCEEDED; } } static inline void handle_frame_start_timestamp_lsb(katherine_acquisition_t *acq, const void *data) { const md_time_lsb_t *md = data; acq->current_frame_info.start_time.b.lsb = md->lsb; } static inline void handle_frame_start_timestamp_msb(katherine_acquisition_t *acq, const void *data) { const md_time_msb_t *md = data; acq->current_frame_info.start_time.b.msb = md->msb; } static inline void handle_frame_end_timestamp_lsb(katherine_acquisition_t *acq, const void *data) { const md_time_lsb_t *md = data; acq->current_frame_info.end_time.b.lsb = md->lsb; } static inline void handle_frame_end_timestamp_msb(katherine_acquisition_t *acq, const void *data) { const md_time_msb_t *md = data; acq->current_frame_info.end_time.b.msb = md->msb; } static inline void handle_lost_pixel_count(katherine_acquisition_t *acq, const void *data) { const md_lost_px_t *md = data; acq->current_frame_info.lost_pixels += md->n_lost; } static inline void handle_aborted_measurement(katherine_acquisition_t *acq, const void *data) { acq->state = ACQUISITION_ABORTED; flush_buffer(acq); acq->handlers.frame_ended(acq->completed_frames, false, &acq->current_frame_info); } static inline void handle_unknown_msg(katherine_acquisition_t *acq, const void *data) { ++acq->dropped_measurement_data; } #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /** * Initialize acquisition. * @param acq Acquisition to initialize * @param device Katherine device * @param md_buffer_size Size of the measurement data buffer in bytes * @param pixel_buffer_size Size of the pixel buffer in bytes * @return Error code. */ int katherine_acquisition_init(katherine_acquisition_t *acq, katherine_device_t *device, size_t md_buffer_size, size_t pixel_buffer_size) { acq->device = device; acq->state = ACQUISITION_NOT_STARTED; acq->md_buffer_size = md_buffer_size; acq->md_buffer = malloc(acq->md_buffer_size); if (!acq->md_buffer) goto err_datagram_buffer; acq->pixel_buffer_size = pixel_buffer_size; acq->pixel_buffer = malloc(acq->pixel_buffer_size); acq->pixel_buffer_valid = 0; if (!acq->pixel_buffer) goto err_pixel_buffer; return 0; err_pixel_buffer: free(acq->md_buffer); err_datagram_buffer: return 1; } /** * Finalize acquisition * @param acq Acquisition to finalize */ void katherine_acquisition_fini(katherine_acquisition_t *acq) { free(acq->md_buffer); free(acq->pixel_buffer); } /** TEST static inline void handle_measurement_data_f_toa_tot(katherine_acquisition_t *acq, const void *data) { static const int PIXEL_SIZE = sizeof(katherine_px_f_toa_tot_t); const md_t *md = ((const md_t*)data);\ if (md->header == 0x4) { if (acq->pixel_buffer_valid == acq->pixel_buffer_max_valid) { flush_buffer(acq); } pmd_f_toa_tot_map((katherine_px_f_toa_tot_t *) ((char*)acq->pixel_buffer) + acq->pixel_buffer_valid, (pmd_f_toa_tot_t *) md, acq); ++acq->pixel_buffer_valid; } else { switch (md->header) { case 0x5: handle_timestamp_offset_driven_mode(acq, data); break; case 0x7: handle_new_frame(acq, data); break; case 0x8: handle_frame_start_timestamp_lsb(acq, data); break; case 0x9: handle_frame_start_timestamp_msb(acq, data); break; case 0xA: handle_frame_end_timestamp_lsb(acq, data); break; case 0xB: handle_frame_end_timestamp_msb(acq, data); break; case 0xC: handle_current_frame_finished(acq, data); break; case 0xD: handle_lost_pixel_count(acq, data); break; case 0xE: handle_aborted_measurement(acq, data); break; default: handle_unknown_msg(acq, data); break; } } } static int acquisition_read_f_toa_tot(katherine_acquisition_t *acq) { static const int TRIES = 64; static const int PIXEL_SIZE = sizeof(katherine_px_f_toa_tot_t); if (katherine_udp_mutex_lock(&acq->device->data_socket) != 0) return 1; \ int tries = TRIES; int res; size_t i; size_t received; acq->pixel_buffer_valid = 0; acq->pixel_buffer_max_valid = acq->pixel_buffer_size / PIXEL_SIZE; while (acq->state == ACQUISITION_RUNNING) { received = acq->md_buffer_size; res = katherine_udp_recv(&acq->device->data_socket, acq->md_buffer, &received); if (res) { if (--tries == 0) { acq->state = ACQUISITION_TIMED_OUT; } continue; } tries = TRIES; const char *it = ((char*)acq->md_buffer); for (i = 0; i < received; i += KATHERINE_MD_SIZE, it += KATHERINE_MD_SIZE) { handle_measurement_data_f_toa_tot(acq, it); } } (void) katherine_udp_mutex_unlock(&acq->device->data_socket); return acq->state == ACQUISITION_SUCCEEDED; } /*******/ #define DEFINE_ACQ_IMPL(SUFFIX) \ static inline void\ handle_measurement_data_##SUFFIX(katherine_acquisition_t *acq, const void *data)\ {\ static const int PIXEL_SIZE = sizeof(katherine_px_##SUFFIX##_t);\ const md_t *md = ((const md_t*)data);\ \ if (md->header == 0x4) {\ if (acq->pixel_buffer_valid == acq->pixel_buffer_max_valid) {\ flush_buffer(acq);\ }\ \ pmd_##SUFFIX##_map((katherine_px_##SUFFIX##_t *) ((char*)acq->pixel_buffer) + acq->pixel_buffer_valid, (pmd_##SUFFIX##_t *) md, acq);\ ++acq->pixel_buffer_valid;\ } else {\ switch (md->header) {\ case 0x5: handle_timestamp_offset_driven_mode(acq, data); break;\ case 0x7: handle_new_frame(acq, data); break;\ case 0x8: handle_frame_start_timestamp_lsb(acq, data); break;\ case 0x9: handle_frame_start_timestamp_msb(acq, data); break;\ case 0xA: handle_frame_end_timestamp_lsb(acq, data); break;\ case 0xB: handle_frame_end_timestamp_msb(acq, data); break;\ case 0xC: handle_current_frame_finished(acq, data); break;\ case 0xD: handle_lost_pixel_count(acq, data); break;\ case 0xE: handle_aborted_measurement(acq, data); break;\ default: handle_unknown_msg(acq, data); break;\ }\ }\ }\ \ static int\ acquisition_read_##SUFFIX(katherine_acquisition_t *acq)\ {\ static const int TRIES = 64;\ static const int PIXEL_SIZE = sizeof(katherine_px_##SUFFIX##_t);\ \ if (katherine_udp_mutex_lock(&acq->device->data_socket) != 0) return 1;\ \ int tries = TRIES;\ int res;\ \ size_t i;\ size_t received;\ \ acq->pixel_buffer_valid = 0;\ acq->pixel_buffer_max_valid = acq->pixel_buffer_size / PIXEL_SIZE;\ \ while (acq->state == ACQUISITION_RUNNING) {\ received = acq->md_buffer_size;\ res = katherine_udp_recv(&acq->device->data_socket, acq->md_buffer, &received);\ \ if (res) {\ if (--tries == 0) {\ acq->state = ACQUISITION_TIMED_OUT;\ }\ \ continue;\ }\ \ tries = TRIES;\ \ const /*void*/char *it = ((char*)acq->md_buffer);\ for (i = 0; i < received; i += KATHERINE_MD_SIZE, it += KATHERINE_MD_SIZE) {\ handle_measurement_data_##SUFFIX(acq, it);\ }\ }\ \ (void) katherine_udp_mutex_unlock(&acq->device->data_socket);\ return acq->state == ACQUISITION_SUCCEEDED;\ } DEFINE_ACQ_IMPL(f_toa_tot); DEFINE_ACQ_IMPL(toa_tot); DEFINE_ACQ_IMPL(f_toa_only); DEFINE_ACQ_IMPL(toa_only); DEFINE_ACQ_IMPL(f_event_itot); DEFINE_ACQ_IMPL(event_itot); #undef DEFINE_ACQ_IMPL /** * Read measurement data from acquisition. * @param acq Acquisition * @return Error code. */ int katherine_acquisition_read(katherine_acquisition_t *acq) { switch (acq->acq_mode) { case ACQUISITION_MODE_TOA_TOT: if (acq->fast_vco_enabled) { return acquisition_read_f_toa_tot(acq); } else { return acquisition_read_toa_tot(acq); } case ACQUISITION_MODE_ONLY_TOA: if (acq->fast_vco_enabled) { return acquisition_read_f_toa_only(acq); } else { return acquisition_read_toa_only(acq); } case ACQUISITION_MODE_EVENT_ITOT: if (acq->fast_vco_enabled) { return acquisition_read_f_event_itot(acq); } else { return acquisition_read_event_itot(acq); } default: return 1; } } /** * Set detector configuration and begin acquisition. * @param acq Acquisition * @param config Configuration * @param readout_mode Readout mode * @return Error code. */ int katherine_acquisition_begin(katherine_acquisition_t *acq, const katherine_config_t *config, char readout_mode) { int res; res = katherine_configure(acq->device, config); if (res) goto err; acq->readout_mode = readout_mode; acq->state = ACQUISITION_RUNNING; acq->completed_frames = 0; acq->requested_frames = config->no_frames; acq->dropped_measurement_data = 0; acq->acq_mode = config->acq_mode; acq->fast_vco_enabled = config->fast_vco_enabled; acq->pixel_buffer_valid = 0; acq->pixel_buffer_max_valid = 0; acq->last_toa_offset = 0; res = katherine_udp_mutex_lock(&acq->device->control_socket); if (res) goto err; res = katherine_cmd_start_acquisition(&acq->device->control_socket, readout_mode); if (res) goto err_cmd; (void) katherine_udp_mutex_unlock(&acq->device->control_socket); return 0; err_cmd: (void) katherine_udp_mutex_unlock(&acq->device->control_socket); err: return res; } /** * Abort acquisition (not recommended). * @param acq Acquisition * @return Error code. */ int katherine_acquisition_abort(katherine_acquisition_t *acq) { int res; res = katherine_udp_mutex_lock(&acq->device->control_socket); if (res) goto err; res = katherine_cmd_stop_acquisition(&acq->device->control_socket, acq->readout_mode); if (res) goto err; res = katherine_cmd_wait_ack(&acq->device->control_socket); if (res) goto err; (void) katherine_udp_mutex_unlock(&acq->device->control_socket); return 0; err: (void) katherine_udp_mutex_unlock(&acq->device->control_socket); return res; } /** * Get human-readable description of acquisition status. * @param status Status to describe * @return Null-terminated string. */ const char* katherine_str_acquisition_status(char status) { switch (status) { case ACQUISITION_NOT_STARTED: return "not started"; case ACQUISITION_SUCCEEDED: return "succeeded"; case ACQUISITION_ABORTED: return "aborted"; case ACQUISITION_RUNNING: return "running"; case ACQUISITION_TIMED_OUT: return "timed out"; default: return "unknown"; } }
danidiaz1/Estructura-de-Datos-UGR-2017-2018
QuienEsQuien/include/pregunta.h
<filename>QuienEsQuien/include/pregunta.h #ifndef _PREGUNTA_H_ #define _PREGUNTA_H_ #include <string> #include <iostream> #include <cassert> using namespace std; /** * @brief En cada estructura pregunta se almacena la cadena de la pregunta y el * número de personajes que aún no han sido eliminados. Si el * número de personajes es 1, entonces la cadena pregunta * contiene el nombre del personaje. */ class Pregunta{ private: /** * @brief Atributo sobre el que se pregunta en este nodo. En el caso de que haya un único * personaje restante, este campo almacena su nombre. */ string atributo; /** * @brief Número de personajes que quedan al llegar a esta pregunta. */ int num_personajes; public: /** * @brief Constructor por defecto de la pregunta. * * Reserva los recursos. */ Pregunta(); /** * @brief Constructor de copias * @param pregunta Pregunta a copiar * * Construye la pregunta duplicando el contenido de @e pregunta en la pregunta * receptora. */ Pregunta(const Pregunta & pregunta); /** * @brief Constructor de la pregunta * @param atributo Atributo sobre el que se pregunta en este nodo. En el caso de que haya un único * personaje restante, este campo almacena su nombre. * @param num_personajes Número de personajes que quedan al llegar a esta pregunta. */ Pregunta(const string atributo, const int num_personajes); /** * @brief Destructor * * Libera los recursos ocupados por la pregunta receptora. */ ~Pregunta(); /** * @brief Operador de asignación * @param pregunta Pregunta a copiar * @return Referencia a la pregunta receptora. * * Asigna el valor de la pregunta duplicando el contenido de @e pregunta en la * pregunta receptora. */ Pregunta & operator = (const Pregunta & pregunta); /** * @brief Operador de comparación * @param pregunta Pregunta a comparar * @return true o false. * * Compara dos preguntas comparando el valor de la pregunta y el número de * personajes asociados. */ bool operator == (const Pregunta & pregunta) const; /** * @brief Operador de inserción de flujo. * @param os Stream de salida. * @param pregunta Pregunta a escribir. * @return Referencia al stream de salida. * * Escribe en la salida la pregunta, escribiendo primero la cadena de la pregunta y * después el número de personajes que quedan al llegar a esta pregunta. */ friend ostream& operator<< (ostream& os, const Pregunta &pregunta); /** * @brief Devuelve el atributo sobre el que se pregunta en el nodo. * * @pre El nodo debe ser un nodo de pregunta (num_personaje>1). */ string obtener_pregunta() const; /** * @brief Devuelve el personaje del nodo * * @pre El nodo debe ser un nodo de personaje (num_personaje==1). */ string obtener_personaje() const; /** * @brief Devuelve el número de personajes sin eliminar al llegar a esta pregunta. */ int obtener_num_personajes() const; /** * @brief Devuelve true si el nodo es de personaje. */ bool es_personaje() const; /** * @brief Devuelve true si el nodo es de pregunta. */ bool es_pregunta() const; }; #endif
danidiaz1/Estructura-de-Datos-UGR-2017-2018
P3_STL_Iteradores/include/cronologia.h
/** * @file cronologia.h * @brief Fichero cabecera del TDA Cronologia * */ #ifndef __CRONOLOGIA #define __CRONOLOGIA #include <iostream> #include <map> #include "fechahistorica.h" using namespace std; /** * @brief T.D.A. Cronologia * * Una instancia @e c del tipo de datos abstracto @c Cronologia es un conjunto * de fechas históricas ordenadas por año. * * Ejemplos de su uso: * @include union_cronologia.cpp * @include filtradoPalabraClave.cpp * @include filtradoIntervalo.cpp * @include estadisticaEventos.cpp * * @author <NAME> * @date Octubre 2017 */ class Cronologia { private: /** * @page repConjunto Rep del TDA Cronologia * * @section invConjunto Invariante de la representación * * Si consideramos una Cronologia como un conjunto de fechas históricas * c={ f1, f2, f3...} el invariante es * \e f1.fecha < fn+1.fecha y no existen fechas históricas tal que \e fi == fj * * @section faConjunto Función de abstracción * * Un objeto válido @e rep del TDA Cronologia representa al valor * * rep.c={f1, f2, f3,...} * */ map<unsigned int, FechaHistorica> c; public: /** * @brief Constructor por defecto. * @return Objeto Cronología sin fechas históricas. */ Cronologia(); /** * @brief Constructor de copias de la clase * @param otra objeto de la clase que se quiere copiar * @return Cronología con los datos de otra */ Cronologia(const Cronologia & otra); /** * @brief Añade una fecha histórica a la cronología. Si ya existía el año de la * fecha histórica, realiza la union de las fechas. * @param f Fecha histórica a añadir */ void aniadirFechaHistorica(FechaHistorica & f); /** * @brief Elimina una fecha histórica de la cronología. * @param f Año de la fecha histórica a eliminar. * @return número de elementos borrados */ unsigned int eliminarFechaHistorica(const unsigned int f); /** * @brief Obtiene los eventos acaecidos en un año. * @param anio Año del que obtener los eventos. * @pre anio >= 0 * @return Objeto FechaHistorica cuya fecha es "anio" y con los acontecimientos * sucedidos en el mismo. Si no se encuentra, se devuelve la fecha histórica vacía. */ FechaHistorica buscarEventos(const unsigned int anio); /** * @brief buscador de eventos dado una palabra clave * @param s vector de string con la palabra a buscar * @return Devuelve una nueva Cronología */ Cronologia buscarEventos(const string & s); /** * @brief Obtiene los eventos en un rango de años. * @param i Año inicial. * @param f Año final. * @pre anio_inicial >= 0 * @return Devuelve una nueva Cronología. */ Cronologia buscarEventos(const unsigned int i, const unsigned int f); /** * @brief Operador suma. Realiza la unión de dos cronologías * @param cr Cronología a unir. * @return Nueva cronologia con la unión */ Cronologia operator+(const Cronologia & cr); /** * @brief Cuenta el número total de años para los que se especifican FechasHistoricas * en la Cronología * @return número de años para los que hay eventos históricos */ const unsigned int totalAnios() const; /** * @brief Cuenta el número total de acontecimientos de la Cronología * @return número total de acontecimientos */ const unsigned int totalAcontecimientos() const; /** * @brief Calcula el número máximo de acontecimientos de una FechaHistórica * en la Cronología * @return número máximo de acontecimientos en la cronología */ const unsigned int maxAcontecimientos() const; /** * @brief Calcula el promedio de acontecimientos por año en la Cronología * @return promedio de acontecimientos */ const float promedioAcontecimientos() const; /** * @brief Salida de una Cronologia a ostream * @param os stream de salida * @param cr Cronologia a escribir */ friend ostream& operator<< (ostream& os, Cronologia& cr); /** * @brief Entrada de una Cronologia desde istream * @param is stream de entrada * @param cr Cronologia que recibe el valor * @retval La Cronologia leída en c * @pre La entrada tiene el formato año#Acontecimiento1#Acontecimiento2\\n año#Acontecimiento1#Acontecimiento2\\naño#Acontecimiento1#Acontecimiento2... */ friend istream& operator>> (istream& is, Cronologia& cr); /** * @brief Operador de asignación. * @param otra Cronologia a asignar al objeto implícito. * @return Objeto implícito. */ Cronologia & operator= (const Cronologia & otra); /** * @brief Clase para iterar sobre la cronologia */ class iterator{ private: map<unsigned int, FechaHistorica>::iterator it; public: iterator & operator++(){ ++it; return *this; } iterator & operator--(){ --it; return *this; } FechaHistorica & operator*(){ return (*it).second; } bool operator ==(const iterator &i){ return i.it==it; } bool operator !=(const iterator &i){ return i.it!=it; } iterator & operator=(const iterator &i){ it = i.it; return *this; } friend class Cronologia; }; /** * @brief Inicializa un iterator al comienzo de la cronología */ iterator begin(){ iterator i; i.it=c.begin(); return i; } /** * @brief Inicializa un iterator al final de la cronología */ iterator end(){ iterator i; i.it=c.end(); return i; } /** * @brief Clase para iterar sobre la cronologia (modo const) */ class const_iterator{ private: map<unsigned int, FechaHistorica>::const_iterator it; public: const_iterator & operator++(){ ++it; return *this; } const_iterator & operator--(){ --it; return *this; } const FechaHistorica & operator*() const{ return (*it).second; } bool operator ==(const const_iterator &i) const{ return i.it==it; } bool operator !=(const const_iterator &i) const{ return i.it!=it; } const_iterator & operator=(const const_iterator &i){ it = i.it; return *this; } friend class Cronologia; }; /** * @brief Inicializa un const_iterator al comienzo de la cronología */ const_iterator begin() const{ const_iterator i; i.it=c.begin(); return i; } /** * @brief Inicializa un const_iterator al final de la cronología */ const_iterator end() const{ const_iterator i; i.it=c.end(); return i; } }; #endif
danidiaz1/Estructura-de-Datos-UGR-2017-2018
P2_Abstraccion/include/fechahistorica.h
<reponame>danidiaz1/Estructura-de-Datos-UGR-2017-2018<filename>P2_Abstraccion/include/fechahistorica.h /** * @file fechahistorica.h * @brief Fichero cabecera del TDA Fecha Histórica * */ #ifndef __FECHAHISTORICA #define __FECHAHISTORICA #include <iostream> #include <vector> #include <string> using namespace std; /** * @brief T.D.A. Fecha Histórica * * Una instancia @e c del tipo de datos abstracto @c Fecha Histórica se * compone de una fecha y uno o más eventos sucedidos en dicha * fecha. La fecha representará únicamente el año en el que tuvieron lugar los * acontecimientos en forma de número natural, y cada uno de los acontecimientos * podrá contener más de una palabra. * * Un ejemplo de su uso: * @include pruebacronologia.cpp * * @author <NAME> * @date Octubre 2017 */ class FechaHistorica { private: /** * @page repConjunto Rep del TDA Fecha Histórica * * @section invConjunto Invariante de la representación * * El invariante es \e rep.fecha >= 0 * * @section faConjunto Función de abstracción * * Un objeto válido @e rep del TDA Fecha Histórica representa al valor * * (rep.fecha, rep.acontecimientos) * */ unsigned int m_fecha; vector<string> m_acontecimientos; public: /** * @brief Constructor por defecto. Crea la FechaHistorica con fecha = 0 y * sin acontecimientos. */ FechaHistorica(); /** * @brief Constructor de la clase. * @param fecha Fecha en que se producieron los acontecimientos * @param acontecimientos Vector de acontecimientos (strings) que se produjeron * en la fecha. * @return Objeto de tipo FechaHistorica con fecha y acontecimientos introducidos * @pre fecha >= 0 */ FechaHistorica(const unsigned int & fecha, const vector<string> & acontecimientos); /** * @brief Constructor de copias de la clase * @param otra objeto de la clase que se quiere copiar * @return Crea el evento con los datos de otra */ FechaHistorica(const FechaHistorica& otra); /** * @brief Obtiene la fecha (versión no constante, es decir, para escritura) * @return Devuelve un entero positivo con la fecha. */ unsigned int & fecha(); /** * @brief Obtiene la fecha (versión constante, es decir, para lectura) * @return Devuelve un entero positivo con la fecha. */ const unsigned int & fecha() const; /** * @brief Obtiene los acontecimientos (versión no constante, es decir, para escritura). * @return Vector de Strings con los acontecimientos. */ vector<string> & acontecimientos(); /** * @brief Obtiene los acontecimientos (versión constante, es decir, para lectura). * @return Vector de Strings con los acontecimientos. */ const vector<string> & acontecimientos() const; /** * @brief Imprime la fecha histórica en cout. * @post Se imprime en \a cout lacadena año \\n\\t Acontecimiento1 \\n\\t Acontecimiento2... */ void print(); /** * @brief Añade un nuevo acontecimiento a la fecha histórica * @param ac Acontecimiento a añadir */ void aniadirAcontecimiento(const string & ac); /** * @brief Elimina un acontecimiento * @param ac String con el contecimiento a eliminar */ void eliminarAcontecimiento(const string & ac); /** * @brief busca de eventos dado una palabra clave * @param s string con la palabra a buscar * @param nuevo es el Evento_Historico donde se van a introducir los resultados * @return Devuelve true o false indicando si está o no está */ bool buscarEventos(string s, FechaHistorica &nuevo) const; /** * @brief busca de eventos dado una palabra clave * @param s string con la palabra a buscar * @return Devuelve true o false indicando si está o no está */ bool buscarEventos(string s) const; /** * @brief Salida de una FechaHistorica a ostream * @param os stream de salida * @param f Racional a escribir * @post Se obtiene en \a os la cadena año \\n\\t Acontecimiento1 \\n\\t Acontecimiento2... * con \e f el valor de la fecha y AcontecimientoN el texto con cada acontecimiento. */ friend ostream& operator<< (ostream& os, FechaHistorica& f); /** * @brief Entrada de una FechaHistorica desde istream * @param is stream de entrada * @param f FechaHistorica que recibe el valor * @retval La FechaHistorica leída en f * @pre La entrada tiene el formato año#Acontecimiento1#Acontecimiento2#... con \e año * el valor de la fecha y AcontecimientoN el texto de cada acontecimiento. Todo en una * cadena de texto. */ friend istream& operator>> (istream& is, FechaHistorica& f); /** * @brief Operador de comparación menor * @param der Fecha histórica correspondiente a la parte derecha de la expresión * @return true si izq.fecha < der.fecha, false en caso contrario */ bool operator < (const FechaHistorica & der); /** * @brief Operador de comparación mayor * @param der Fecha histórica correspondiente a la parte derecha de la expresión * @return true si izq.fecha > der.fecha, false en caso contrario */ bool operator > (const FechaHistorica & der); /** * @brief Operador de comparación menor o igual * @param der Fecha histórica correspondiente a la parte derecha de la expresión * @return true si izq.fecha <= der.fecha, false en caso contrario */ bool operator <= (const FechaHistorica & der); /** * @brief Operador de comparación mayor o igual * @param der Fecha histórica correspondiente a la parte derecha de la expresión * @return true si izq.fecha >= der.fecha, false en caso contrario */ bool operator >= (const FechaHistorica & der); /** * @brief Operador de comparación * @param der Fecha histórica correspondiente a la parte derecha de la expresión * @return true si izq.fecha == der.fecha, false en caso contrario */ bool operator == (const FechaHistorica & der); /** * @brief Compara el año de la fecha implícita con la pasada por parámetro. * @param otra Fecha a comparar. * @return true si los años son iguales, false si no. */ bool mismoAnio (const FechaHistorica & otra); /** * @brief Operador suma. Une los eventos de dos fechas históricas con el mismo año. * @param otra Fecha a sumar. * @pre otra.fecha == (*this).fecha * @return Unión de las fechas históricas. */ FechaHistorica operator+ (const FechaHistorica & otra); /** * @brief Operador de asignación. * @param otra Fecha histórica a asignar al objeto implícito. * @return Objeto implícito. */ FechaHistorica & operator= (const FechaHistorica & otra); }; #endif
danidiaz1/Estructura-de-Datos-UGR-2017-2018
P2_Abstraccion/include/cronologia.h
/** * @file cronologia.h * @brief Fichero cabecera del TDA Cronologia * */ #ifndef __CRONOLOGIA #define __CRONOLOGIA #include <iostream> #include <vector> #include "fechahistorica.h" using namespace std; /** * @brief T.D.A. Cronologia * * Una instancia @e c del tipo de datos abstracto @c Cronologia es un conjunto * de fechas históricas ordenadas por año. * * Un ejemplo de su uso: * @include pruebacronologia.cpp * * @author <NAME> * @date Octubre 2017 */ class Cronologia { private: /** * @page repConjunto Rep del TDA Cronologia * * @section invConjunto Invariante de la representación * * Si consideramos una Cronologia como un conjunto de fechas históricas * c={ f1, f2, f3...} el invariante es * \e f1.fecha < fn+1.fecha y no existen fechas históricas tal que \e fi == fj * * @section faConjunto Función de abstracción * * Un objeto válido @e rep del TDA Cronologia representa al valor * * rep.c={f1, f2, f3,...} * */ vector<FechaHistorica> c; void ordenar(); //Ordena el vector c de fechas históricas de menor a mayor. int buscarAnio(const unsigned int fecha); // Busca en el vector c si existe alguna fecha con el año fecha // Devuelve la posición en el vector (-1 si no se encuentra) public: // Se omite el constructor por defecto, ya que el dado por el compilador crearía // el vector c con 0 elementos, que es lo que se pretende /** * @brief Constructor por defecto. * @return Objeto Cronología sin fechas históricas. */ Cronologia(); /** * @brief Constructor con parámetros. * @param f Vector de fechas históricas. * @return Objeto Cronología con fechas históricas. */ Cronologia(const vector<FechaHistorica> & f); /** * @brief Constructor de copias de la clase * @param otra objeto de la clase que se quiere copiar * @return Crea el evento con los datos de c */ Cronologia(const Cronologia& otra); /** * @brief Añade una fecha histórica a la cronología. Si ya existía el año de la * fecha histórica, realiza la union de las fechas. * @param f Fecha histórica a añadir */ void aniadirFechaHistorica(FechaHistorica & f); /** * @brief Elimina una fecha histórica de la cronología. * @param f Año de la fecha histórica a eliminar. * @return true si se ha eliminado, false si no se ha encontrado */ bool eliminarFechaHistorica(const unsigned int f); /** * @brief Obtiene los eventos acaecidos en un año. * @param anio Año del que obtener los eventos. * @pre anio >= 0 * @return Objeto FechaHistorica cuya fecha es "anio" y con los acontecimientos * sucedidos en el mismo. Si no se encuentra, se devuelve la fecha histórica vacía. */ FechaHistorica buscarEventos(const unsigned int anio); /** * @brief buscador de eventos dado una palabra clave * @param s vector de string con la palabra a buscar * @return Devuelve una nueva Cronología */ Cronologia buscarEventos(const string & s); /** * @brief Obtiene los eventos en un rango de años. * @param i Año inicial. * @param f Año final. * @pre anio_inicial >= 0 * @return Devuelve una nueva Cronología. */ Cronologia buscarEventos(const unsigned int i, const unsigned int f); /** * @brief Operador suma. Realiza la unión de dos cronologías * @param cr Cronología a unir. * @return Nueva cronologia con la unión */ Cronologia operator+(const Cronologia & cr); /** * @brief Salida de una Cronologia a ostream * @param os stream de salida * @param cr Cronologia a escribir */ friend ostream& operator<< (ostream& os, Cronologia& cr); /** * @brief Entrada de una Cronologia desde istream * @param is stream de entrada * @param cr Cronologia que recibe el valor * @retval La Cronologia leída en c * @pre La entrada tiene el formato año#Acontecimiento1#Acontecimiento2\\n año#Acontecimiento1#Acontecimiento2\\naño#Acontecimiento1#Acontecimiento2... */ friend istream& operator>> (istream& is, Cronologia& cr); /** * @brief Operador de asignación. * @param otra Cronologia a asignar al objeto implícito. * @return Objeto implícito. */ Cronologia & operator= (const Cronologia & otra); }; #endif
JeanVinge/OHHTTPStubsExample
OHHTTPStubs/Constants.h
<filename>OHHTTPStubs/Constants.h // // Constants.h // OHHTTPStubs // // Created by <NAME> on 27/10/15. // Copyright © 2015 <NAME>. All rights reserved. // #ifndef Constants_h #define Constants_h static NSString *const kAPIBase = @"https://tests.com"; static NSString *const kPathTest = @"tests"; #endif /* Constants_h */
JeanVinge/OHHTTPStubsExample
OHHTTPStubs/Client.h
<reponame>JeanVinge/OHHTTPStubsExample // // Client.h // Wattpad-app // // Created by <NAME> on 24/08/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <AFNetworking/AFHTTPRequestOperationManager.h> @interface Client : AFHTTPRequestOperationManager + (instancetype)sharedInstance; - (void)testsWithSuccess:(void (^)(NSString *name))success failure:(void(^)(NSError *error))failure; @end
JeanVinge/OHHTTPStubsExample
OHHTTPStubs/ViewController.h
<reponame>JeanVinge/OHHTTPStubsExample // // ViewController.h // OHHTTPStubs // // Created by <NAME> on 27/10/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
JeanVinge/OHHTTPStubsExample
OHHTTPStubs/StubRequests.h
// // StubRequests.h // OHHTTPStubs // // Created by <NAME> on 27/10/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface StubRequests : NSObject + (void)mockTest; @end
nilsreichardt/Agora-Flutter-RTM-SDK
ios/Classes/RTMChannel.h
// // RTMChannel.h // agora_rtm // // Created by LY on 2019/8/16. // #import <AgoraRtmKit/AgoraRtmKit.h> #import <Flutter/Flutter.h> @interface RTMChannel : NSObject<FlutterStreamHandler, AgoraRtmChannelDelegate> @property (strong, nonatomic) NSObject<FlutterBinaryMessenger> *messenger; @property (strong, nonatomic) AgoraRtmChannel *channel; @property (strong, nonatomic) NSNumber *clientIndex; @property (strong, nonatomic) NSString *channelId; @property (strong, nonatomic) FlutterEventChannel *eventChannel; @property (strong, nonatomic) FlutterEventSink eventSink; - (instancetype) initWithClientIndex:(NSNumber *)clientIndex channelId:(NSString *)channelId messenger:(id)messenger kit:(AgoraRtmKit*)kit; @end
nilsreichardt/Agora-Flutter-RTM-SDK
ios/Classes/RTMClient.h
<filename>ios/Classes/RTMClient.h // // RTMClient.h // agora_rtm // // Created by LY on 2019/8/15. // #import <AgoraRtmKit/AgoraRtmKit.h> #import <Flutter/Flutter.h> #import "RTMChannel.h" @interface RTMClient : NSObject<FlutterStreamHandler, AgoraRtmDelegate, AgoraRtmCallDelegate> @property (strong, nonatomic) AgoraRtmKit *kit; @property (strong, nonatomic) AgoraRtmCallKit *callKit; @property (strong, nonatomic) NSMutableDictionary<NSString *, RTMChannel*> *channels; @property (strong, nonatomic) NSMutableDictionary<NSString *, AgoraRtmRemoteInvitation *> *remoteInvitations; @property (strong, nonatomic) NSMutableDictionary<NSString *, AgoraRtmLocalInvitation *> *localInvitations; @property (strong, nonatomic) NSObject<FlutterBinaryMessenger> *messenger; @property (strong, nonatomic) NSNumber *clientIndex; @property (strong, nonatomic) FlutterEventChannel *eventChannel; @property (strong, nonatomic) FlutterEventSink eventSink; - (instancetype) initWithAppId:(NSString *)appId clientIndex:(NSNumber *)clientIndex messenger:(NSObject<FlutterBinaryMessenger>*)messenger; @end
1320014053/V8-debugger
debugger.h
<gh_stars>0 #pragma once #pragma warning(disable:4996) #define JumpIfFalseHandler 0
DossierSansTitreEx/MiaouOS
include/stddef.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _STDDEF_H #define _STDDEF_H 1 #include <sys/cdefs.h> #include <sys/_types/_null.h> #define offsetof(st, m) __builtin_offsetof(st, m) #include <sys/_types/_ptrdiff_t.h> #include <sys/_types/_wchar_t.h> #include <sys/_types/_size_t.h> #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_ssize_t.h
#ifndef _SYS__TYPES__SSIZE_T_H_ #define _SYS__TYPES__SSIZE_T_H_ #if (__SIZEOF_SIZE_T__ == 8) typedef __INT64_TYPE__ ssize_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/mfs.h
<gh_stars>1-10 #ifndef _EFFEL_MFS_H #define _EFFEL_MFS_H 1 #include <stddef.h> #include <stdint.h> #include <boot/boot_params.h> struct mfs { uint8_t device; uint64_t lba; struct dpte dpte; uint64_t root; char* buffers[4]; }; struct mfs_fileinfo_ { uint64_t inode; uint64_t size; uint64_t data[12]; uint64_t idata; uint64_t idata2; }; typedef struct mfs_fileinfo_ mfs_fileinfo; void mfs_init(const boot_params* params); void mfs_init_buffers(); void mfs_read_info(mfs_fileinfo* info, const char* path); void mfs_read(char* dst, const mfs_fileinfo* info, size_t offset, size_t length); #endif
DossierSansTitreEx/MiaouOS
src/boot/stage3.c
<gh_stars>1-10 #include <boot/boot_params.h> #define PAGESIZE 4096 struct file_info_ { uint64_t size; uint64_t data[12]; uint64_t idata; }; typedef struct file_info_ file_info; void disk_read(void* dst, uint64_t lba, uint64_t count, void* dpte); static volatile char* monitor; static uint16_t cursor_x; static uint16_t cursor_y; static boot_params* g_params; static void scroll() { for (uint32_t i = 0; i < (80 * 24 * 2); ++i) monitor[i] = monitor[i + 80 * 2]; for (uint32_t i = 0; i < 80 * 2; ++i) monitor[(24 * 80 * 2) + i] = 0; cursor_x = 0; cursor_y = 24; } static void putchar(char c) { uint32_t index; if (c == '\n') { cursor_x = 0; cursor_y++; return; } if (cursor_y >= 25) scroll(); index = cursor_y * 80 + cursor_x; monitor[index * 2 + 0] = c; monitor[index * 2 + 1] = 0x07; cursor_x++; if (cursor_x >= 80) { cursor_x = 0; cursor_y++; } } static void print(const char* s) { for (uint32_t i = 0; s[i]; ++i) putchar(s[i]); } static void puts(const char* s) { print(s); putchar('\n'); } static void _print_hex(uint64_t num) { static const char* const table = "0123456789abcdef"; uint8_t nibble; nibble = num % 16; num /= 16; if (num) _print_hex(num); putchar(table[nibble]); } static void print_hex(uint64_t num) { print("0x"); _print_hex(num); } static void dump_memory_map(boot_params* params) { memory_zone* zone; puts("Memory Map:"); for (uint64_t i = 0; i < params->memory_size; ++i) { zone = params->memory_zones + i; putchar(' '); print_hex(zone->base); print(" -> "); print_hex(zone->base + zone->length); print(" (type: "); print_hex(zone->type); puts(")"); } } uint64_t next_free_page() { uint64_t page; memory_zone* zone; for (uint64_t i = 0; i < g_params->memory_size; ++i) { zone = g_params->memory_zones + i; if (zone->base < 0x100000 || zone->length == 0 || zone->type != 0x01) continue; page = zone->base; zone->base += PAGESIZE; zone->length -= PAGESIZE; return page; } return 0; } uint64_t create_page_layer(uint64_t addr, uint16_t flags) { uint64_t* ptr; uint64_t value; ptr = (uint64_t*)addr; value = *ptr; if (!(value & 1)) { value = next_free_page() | flags; *ptr = value; } value &= 0xfffffffffffff000; return value; } void print_hex(uint64_t); void map_page(uint64_t dst, uint16_t flags) { uint64_t pml4; uint64_t pdp; uint64_t pd; uint64_t pt; uint16_t pml4_slot; uint16_t pdp_slot; uint16_t pd_slot; uint16_t pt_slot; pml4_slot = ((dst & 0xff8000000000) >> 36); pdp_slot = ((dst & 0x7fc0000000) >> 27); pd_slot = ((dst & 0x3fe00000) >> 18); pt_slot = ((dst & 0x1ff000) >> 9); pml4 = 0x1000; pdp = create_page_layer(pml4 + pml4_slot, 3); pd = create_page_layer(pdp + pdp_slot, 3); pt = create_page_layer(pd + pd_slot, 3); create_page_layer(pt + pt_slot, flags); } char* virtual_alloc(uint64_t dst, uint64_t size, uint16_t flags) { char* ptr; uint64_t end; ptr = (char*)dst; end = dst + size; dst &= 0xfffffffffffff000; size = end - dst; size = (size + 4095) / 4096; print("MAP: "); print_hex(dst); print(" -> "); print_hex(dst + size * 4096); putchar('\n'); for (uint64_t i = 0; i < size; ++i) { map_page(dst + i * 4096, flags); } return ptr; } static void memcpy(char* dst, char* src, uint64_t size) { for (uint64_t i = 0; i < size; ++i) dst[i] = src[i]; } static void memset(char* dst, int value, uint64_t size) { for (uint64_t i = 0; i < size; ++i) dst[i] = (char)value; } static int strequ(const char* s1, const char* s2) { int i; i = 0; while (s1[i] == s2[i]) { i++; if (s1[i] == 0) return 1; } return 0; } static char* disk_buffer(uint64_t lba, uint64_t count) { char* dst; dst = (char*)0x10000; disk_read(dst, lba, count, &g_params->dpte); return dst; } static char* load_chunk(boot_params* params, uint64_t chunk) { uint64_t lba; lba = params->mbr->lba_base + 40 + chunk * 8; return disk_buffer(lba, 8); } static char* load_inode(boot_params* params, uint64_t inode) { return load_chunk(params, inode); } static void load_file(boot_params* params, file_info* info, char* dst, uint64_t offset, uint64_t size) { char* tmp; uint64_t chunk_first = offset / 4096; uint64_t chunk_last = (offset + size - 1) / 4096; uint64_t chunk_count = chunk_last - chunk_first + 1; uint64_t i; uint64_t j; uint64_t base; uint64_t range_start; uint64_t range_length; for (i = 0; i < chunk_count; ++i) { base = chunk_first + i; /* We load into out temp buffer */ if (base < 12) tmp = load_inode(params, info->data[base]); else { tmp = load_inode(params, info->idata); j = ((uint64_t*)tmp)[base]; tmp = load_inode(params, j); } /* Now we have one of the chunk we need. We want to copy it into the destination. */ /* First chunk */ range_start = 0; range_length = 4096; if (i == 0) range_start = offset % 4096; if (i == (chunk_count - 1)) range_length = ((offset + size) - 1) % 4096 + 1; memcpy(dst, tmp + range_start, range_length); dst += range_length; } } void enter_kernel(uint64_t, boot_params* params); static void load_elf(boot_params* params, uint64_t inode) { file_info info; char* buf; char* tmp; uint64_t entry_point; uint16_t entry_size; uint16_t entry_count; uint64_t entry_offset; buf = load_inode(params, inode); info.size = *(uint64_t*)(buf + 0x38); for (int i = 0; i < 12; ++i) info.data[i] = *(uint64_t*)(buf + 0x40 + 0x08 * i); info.idata = *(uint64_t*)(buf + 0x100); tmp = (char*)(0x11000); load_file(params, &info, tmp, 0, 64); entry_point = *(uint64_t*)(tmp + 24); entry_offset = *(uint64_t*)(tmp + 32); entry_size = *(uint16_t*)(tmp + 54); entry_count = *(uint16_t*)(tmp + 56); print_hex(entry_offset); putchar('\n'); print_hex(entry_size); putchar('\n'); print_hex(entry_count); putchar('\n'); load_file(params, &info, tmp, entry_offset, entry_count * entry_size); for (uint32_t i = 0; i < entry_count; ++i) { char* dst; uint32_t type = *(uint32_t*)(tmp + (entry_size * i) + 0); uint32_t flags = *(uint32_t*)(tmp + (entry_size * i) + 4); uint64_t p_offset = *(uint64_t*)(tmp + (entry_size * i) + 8); uint64_t p_vaddr = *(uint64_t*)(tmp + (entry_size * i) + 16); uint64_t p_filesz = *(uint64_t*)(tmp + (entry_size * i) + 32); uint64_t p_memsz = *(uint64_t*)(tmp + (entry_size * i) + 40); (void)flags; if (type != 0x01) continue; print_hex(p_offset); putchar('\n'); print_hex(p_vaddr); putchar('\n'); dst = virtual_alloc(p_vaddr, p_memsz, 0x03); if (p_filesz) load_file(params, &info, dst, p_offset, p_filesz); if (p_memsz > p_filesz) memset(dst + p_filesz, 0, p_memsz - p_filesz); } enter_kernel(entry_point, params); } static uint64_t find_child(boot_params* params, uint64_t parent, const char* child_name) { char* buf; char name[256]; uint16_t namelen; uint64_t tmp; int i; buf = load_inode(params, parent); tmp = *(uint64_t*)(buf + 0x40); buf = load_inode(params, tmp); for (;;) { namelen = *(uint16_t*)(buf); buf += 2; for (i = 0; i < namelen; ++i) name[i] = buf[i]; name[i] = 0; buf += namelen; tmp = *(uint64_t*)(buf); buf += 8; if (strequ(name, child_name)) return tmp; } } static void load_effel(boot_params* params) { uint64_t inode; char* buffer; buffer = load_inode(params, 0x0); inode = *(uint64_t*)(buffer + 0x18); puts(buffer); print("Root: "); print_hex(inode); putchar('\n'); inode = find_child(params, inode, "boot"); inode = find_child(params, inode, "effel"); print("Found kernel inode: "); print_hex(inode); putchar('\n'); load_elf(params, inode); } void start(boot_params* params) { g_params = params; monitor = (char*)0xb8000; cursor_x = 0; cursor_y = 0; puts("Entering 64-bit mode"); print("Boot params: "); print_hex((uint64_t)params); putchar('\n'); print("Boot drive: "); print_hex(params->drive); putchar('\n'); print("Partition: "); print_hex(params->mbr->lba_base); print(" -> "); print_hex(params->mbr->lba_base + params->mbr->lba_length); putchar('\n'); dump_memory_map(params); load_effel(params); for (;;) {} }
DossierSansTitreEx/MiaouOS
src/effel/tss.h
<gh_stars>1-10 #ifndef TSS_H #define TSS_H #include <stdint.h> struct tss { uint32_t zero1; uint64_t rsp[3]; uint64_t zero2; uint64_t ist[8]; uint64_t zero3; uint16_t zero4; uint16_t iomb; } __attribute__ ((packed, aligned(16))); extern struct tss tss; void tss_init(); #endif
DossierSansTitreEx/MiaouOS
src/effel/vmm.h
<gh_stars>1-10 #ifndef _VMM_H #define _VMM_H 1 #include <stddef.h> #include <boot/boot_params.h> #define PAGESIZE 4096 #define VMM_WRITE 0x00000002 #define VMM_USER 0x00000004 void vmm_init(boot_params* params); void* vmm_alloc_over(uint64_t physical_addr, size_t size, uint32_t flags); void* vmm_alloc(size_t size, uint32_t flags); void* vmm_allocv(uint64_t vaddr, size_t size, uint32_t flags); void vmm_switch(uint64_t pml4); uint64_t vmm_kfork(); #endif
DossierSansTitreEx/MiaouOS
src/effel/proc.h
#ifndef _EFFEL_PROC_ #define _EFFEL_PROC_ 1 #include <stdint.h> #include <stddef.h> #define P_PRESENT 1 typedef uint64_t proc_id; struct cpu_state { /* iret-style state */ uint64_t ss; uint64_t rsp; uint64_t rflags; uint64_t cs; uint64_t rip; /* regulat state */ uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rsi; uint64_t rdi; uint64_t rbp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; } __attribute__ ((packed)); struct proc { struct cpu_state* cpu_state; uint64_t pml4; uint64_t flags; }; struct proc_table { struct proc* procs; proc_id running; size_t proc_count; } __attribute__ ((packed)); struct proc* proc_current(); void proc_init(); void proc_create(const char* s); void proc_schedule(); #endif
DossierSansTitreEx/MiaouOS
src/effel/syscall.c
#include <syscall.h> #include <stdint.h> #include <stddef.h> #include <screen.h> void* sys_table[512]; void syscall_handler(); void syscall_set_handler(void* handler); void sys_write(int fd, const void* mem, size_t size) { (void)fd; kprint_raw(mem, size); } void syscall_init() { sys_table[0x01] = sys_write; syscall_set_handler(&syscall_handler); }
DossierSansTitreEx/MiaouOS
src/libc/string/strrchr.c
<reponame>DossierSansTitreEx/MiaouOS #include <string.h> char* strrchr(const char* s, int c) { char cc; char sc; size_t i; cc = c; i = strlen(s) + 1; while (i--) { sc = s[i - 1]; if (sc == cc) return (char*)s + i; } return NULL; }
DossierSansTitreEx/MiaouOS
include/sys/_types/_uintmax_t.h
#ifndef _SYS__TYPES__UINTMAX_T_H_ #define _SYS__TYPES__UINTMAX_T_H_ typedef unsigned long long uintmax_t; #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_int32_t.h
<filename>include/sys/_types/_int32_t.h #ifndef _SYS__TYPES__INT32_T_H_ #define _SYS__TYPES__INT32_T_H_ #if defined(__INT32_TYPE__) typedef __INT32_TYPE__ int32_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/vmm.c
<filename>src/effel/vmm.c #include <string.h> #include <vmm.h> #include <util.h> #define PAGE_MASK 0xfffffffffffff000 #define PAGE_RECURSE 0x1fe #define PAGES_PER_TABLE 512 #define KERNEL_HEAP_BASE 0xffffffffc0000000 typedef struct { uint64_t base; uint64_t length; } vmm_mem_store; typedef struct { uint64_t kernel_heap; uint64_t mem_store_size; vmm_mem_store mem_store[128]; uint64_t* free_pages; uint64_t free_pages_count; uint64_t free_pages_capacity; } virtual_memory_manager; static virtual_memory_manager vmm; static uint64_t* addr5(uint16_t a, uint16_t b, uint16_t c, uint16_t d, uint16_t e) { uint64_t addr; /* We need to sign extend over 48 bits */ addr = ((uint64_t)a & 0x100) << 40; addr |= (addr << 1); addr |= (addr << 2); addr |= (addr << 4); addr |= (addr << 8); addr |= ((uint64_t)a << (12 + 9 * 3)); addr |= ((uint64_t)b << (12 + 9 * 2)); addr |= ((uint64_t)c << (12 + 9 * 1)); addr |= ((uint64_t)d << (12 + 9 * 0)); addr |= ((uint64_t)e << 3); return (uint64_t*)addr; } static uint64_t* addr4(uint16_t a, uint16_t b, uint16_t c, uint16_t d) { return addr5(a, b, c, d, 0x0); } static void raddr4(uint16_t* dst, uint64_t addr) { dst[0] = ((addr >> (12 + 9 * 3))) & 0x1ff; dst[1] = ((addr >> (12 + 9 * 2))) & 0x1ff; dst[2] = ((addr >> (12 + 9 * 1))) & 0x1ff; dst[3] = ((addr >> (12 + 9 * 0))) & 0x1ff; } static uint64_t pml4_read() { uint64_t v; __asm__ __volatile__ ("mov %%cr3, %%rax" : "=a" (v)); return v; } static uint64_t pml4_addr() { return (pml4_read() & PAGE_MASK); } static uint64_t alloc_vaddr(size_t size) { uint64_t v; v = vmm.kernel_heap; vmm.kernel_heap += size; return v; } static uint64_t mem_store_fetch() { uint64_t v; v = vmm.mem_store[0].base; vmm.mem_store[0].base += PAGESIZE; vmm.mem_store[0].length -= PAGESIZE; if (vmm.mem_store[0].length == 0) { memmove(vmm.mem_store, vmm.mem_store + 1, (vmm.mem_store_size - 1) * sizeof(vmm_mem_store)); vmm.mem_store_size--; } return v; } static uint64_t physical_page() { return mem_store_fetch(); } static void init_free_list() { uint64_t kernel_page; uint64_t physical_page; uint64_t pml4; uint64_t pdp; uint64_t pd; uint64_t pt; uint16_t pml4_slot; uint16_t pdp_slot; uint16_t pd_slot; uint16_t pt_slot; kernel_page = alloc_vaddr(PAGESIZE); pml4_slot = ((kernel_page & 0xff8000000000) >> 36); pdp_slot = ((kernel_page & 0x7fc0000000) >> 27); pd_slot = ((kernel_page & 0x3fe00000) >> 18); pt_slot = ((kernel_page & 0x1ff000) >> 9); pml4 = pml4_addr(); physical_page = mem_store_fetch(); uint64_t tmp; tmp = *(uint64_t*)(pml4 + pml4_slot); if (tmp & 1) pdp = tmp & PAGE_MASK; else { pdp = mem_store_fetch(); *(uint64_t*)(pml4 + pml4_slot) = (pdp | 3); } tmp = *(uint64_t*)(pdp + pdp_slot); if (tmp & 1) pd = tmp & PAGE_MASK; else { pd = mem_store_fetch(); *(uint64_t*)(pdp + pdp_slot) = (pd | 3); } tmp = *(uint64_t*)(pd + pd_slot); if (tmp & 1) pt = tmp & PAGE_MASK; else { pt = mem_store_fetch(); *(uint64_t*)(pd + pd_slot) = (pt | 3); } *(uint64_t*)(pt + pt_slot) = (physical_page | 3); vmm.free_pages = (uint64_t*)kernel_page; vmm.free_pages_count = 0; vmm.free_pages_capacity = PAGES_PER_TABLE; } static void init_mem_store(boot_params* params) { size_t store_size; size_t i; store_size = 0; for (i = 0; i < params->memory_size; ++i) { memory_zone* zone; zone = params->memory_zones + i; if (zone->type != 0x01 || zone->length == 0 || zone->base < 0x100000) continue; vmm.mem_store[store_size].base = zone->base; vmm.mem_store[store_size].length = zone->length; store_size++; zone->length = 0; } vmm.mem_store_size = store_size; vmm.free_pages = NULL; vmm.free_pages_count = 0; vmm.free_pages_capacity = 0; } static void touch_page_dir(uint16_t a, uint16_t b, uint16_t c, uint16_t d, uint32_t flags) { uint64_t* tmp; uint64_t req_mask; tmp = addr5(PAGE_RECURSE, a, b, c, d); req_mask = ((flags & (VMM_USER | VMM_WRITE)) | 1); if ((*tmp & 1) == 0) *tmp = (physical_page() | req_mask); else if ((*tmp & req_mask) != req_mask) *tmp |= req_mask; } static void map_page_raw(uint64_t virtual_addr, uint64_t physical_addr, uint32_t flags) { uint16_t v[4]; uint64_t* tmp; raddr4(v, virtual_addr); touch_page_dir(PAGE_RECURSE, PAGE_RECURSE, PAGE_RECURSE, v[0], flags); touch_page_dir(PAGE_RECURSE, PAGE_RECURSE, v[0], v[1], flags); touch_page_dir(PAGE_RECURSE, v[0], v[1], v[2], flags); tmp = addr5(PAGE_RECURSE, v[0], v[1], v[2], v[3]); *tmp = (physical_addr | flags | 1); } static size_t page_count_from_size(size_t size) { return (size + (PAGESIZE - 1)) / PAGESIZE; } static void map_pages_raw(uint64_t virtual_addr, uint64_t physical_addr, size_t size, uint32_t flags) { size_t count; count = page_count_from_size(size); for (size_t i = 0; i < count; ++i) map_page_raw(virtual_addr + i * PAGESIZE, physical_addr + i * PAGESIZE, flags); } void* vmm_alloc_over(uint64_t physical_addr, size_t size, uint32_t flags) { uint64_t vaddr; size_t count; count = page_count_from_size(size); vaddr = alloc_vaddr(count * PAGESIZE); map_pages_raw(vaddr, physical_addr, size, flags); return (void*)vaddr; } void* vmm_alloc(size_t size, uint32_t flags) { uint64_t vaddr; size_t count; count = page_count_from_size(size); vaddr = alloc_vaddr(count * PAGESIZE); return vmm_allocv(vaddr, size, flags); } void* vmm_allocv(uint64_t vaddr, size_t size, uint32_t flags) { size_t count; size += vaddr & 0xfff; vaddr &= PAGE_MASK; count = page_count_from_size(size); for (size_t i = 0; i < count; ++i) map_page_raw(vaddr + i * PAGESIZE, physical_page(), flags); return (void*)vaddr; } void reload_paging() { __asm__ __volatile__ ( "mov %%cr3, %%rax\r\n" "mov %%rax, %%cr3\r\n" ::: "rax" ); } void init_paging() { /* TODO: reclaim memory */ uint64_t *pte; pte = addr4(PAGE_RECURSE, PAGE_RECURSE, PAGE_RECURSE, PAGE_RECURSE); *pte = 0x0; reload_paging(); } void vmm_init(boot_params* params) { uint64_t pml4; /* Setup a temporary self-paging trick */ pml4 = pml4_addr(); *(uint64_t*)(pml4 + 0xff0) = (pml4 | 3); vmm.kernel_heap = KERNEL_HEAP_BASE; init_mem_store(params); init_free_list(); init_paging(); } void vmm_switch(uint64_t pml4) { __asm__ __volatile__ ("mov %%rax, %%cr3" :: "a" (pml4)); } uint64_t vmm_kfork() { uint64_t physical; uint64_t* vaddr; physical = physical_page(); vaddr = vmm_alloc_over(physical, PAGESIZE, 0); vaddr[511] = *(addr5(PAGE_RECURSE, PAGE_RECURSE, PAGE_RECURSE, PAGE_RECURSE, 511)); vaddr[510] = (physical | 1); vmm_switch(physical); return physical; }
DossierSansTitreEx/MiaouOS
src/libc/string/memcmp.c
#include <string.h> int memcmp(const void* s1, const void* s2, size_t n) { const unsigned char* u1; const unsigned char* u2; int diff; u1 = s1; u2 = s2; for (size_t i = 0; i < n; ++i) { diff = (int)(u1[i]) - (int)(u2[i]); if (diff) return diff; } return 0; }
DossierSansTitreEx/MiaouOS
src/effel/interrupt.h
<reponame>DossierSansTitreEx/MiaouOS<gh_stars>1-10 #ifndef _INTERRUPT_H #define _INTERRUPT_H 1 void irq_enable(uint8_t line); void irq_disable(uint8_t line); void interrupt_register(uint8_t slot, void* isr); void interrupt_init(); #endif
DossierSansTitreEx/MiaouOS
include/unistd.h
<filename>include/unistd.h #ifndef _UNISTD_H #define _UNISTD_H 1 #include <sys/cdefs.h> #include <sys/_types/_size_t.h> #include <sys/_types/_ssize_t.h> #ifndef __KERNEL __BEGIN_DECL ssize_t write(int fd, const void* buf, size_t len); __END_DECL #endif #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_intmax_t.h
#ifndef _SYS__TYPES__INTMAX_T_H_ #define _SYS__TYPES__INTMAX_T_H_ typedef long long intmax_t; #endif
DossierSansTitreEx/MiaouOS
src/libc/string/strcmp.c
#include <string.h> int strcmp(const char* s1, const char* s2) { size_t i; int diff; int c1; int c2; i = 0; for (;;) { c1 = (unsigned char)(s1[i]); c2 = (unsigned char)(s2[i]); diff = c1 - c2; if (diff) return diff; if (c1 == 0) return 0; i++; } }
DossierSansTitreEx/MiaouOS
include/sys/cpuinfo.h
<gh_stars>1-10 #ifndef _SYS_CPUINFO_H_ #define _SYS_CPUINFO_H_ #include <sys/cdefs.h> #include <sys/cpuid.h> #define CPUINFO_SSE (1 << 0) #define CPUINFO_SSE2 (1 << 1) #define CPUINFO_SSE3 (1 << 2) #define CPUINFO_SSSE3 (1 << 3) #define CPUINFO_SSE4_1 (1 << 4) #define CPUINFO_SSE4_2 (1 << 5) #define CPUINFO_SSE4A (1 << 6) #define CPUINFO_SSE5 (1 << 7) #define CPUINFO_AVX (1 << 8) #define CPUINFO_AVX2 (1 << 9) #define CPUINFO_AVX_512 (1 << 10) typedef struct { uint32_t support; char vendor[13]; } cpuinfo_t; __BEGIN_DECL void cpuinfo(cpuinfo_t* info); __END_DECL #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_uint16_t.h
#ifndef _SYS__TYPES__UINT16_T_H_ #define _SYS__TYPES__UINT16_T_H_ #if defined(__UINT16_TYPE__) typedef __UINT16_TYPE__ uint16_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/util.h
#ifndef _UTIL_H #define _UTIL_H 1 static inline void magic_break() { __asm__ __volatile__ ("xchg %bx, %bx"); } #endif
DossierSansTitreEx/MiaouOS
include/string.h
<gh_stars>1-10 #ifndef _STRING_H #define _STRING_H 1 #include <sys/cdefs.h> #include <sys/_types/_null.h> #include <sys/_types/_size_t.h> __BEGIN_DECL void* memcpy(void* __restrict dst, const void* __restrict src, size_t n); void* memmove(void* dst, const void* src, size_t len); void* memchr(const void* s, int c, size_t num); int memcmp(const void* s1, const void* s2, size_t n); void* memset(void* b, int c, size_t len); char* strcat(char* __restrict s1, const char* __restrict s2); char* strncat(char* __restrict s1, const char* __restrict s2, size_t n); char* strchr(const char* s, int c); char* strrchr(const char* s, int c); int strcmp(const char* s1, const char* s2); int strncmp(const char* s1, const char* s2, size_t n); size_t strlen(const char* s) __attribute__((pure)); char* strcpy(char* dst, const char* src); char* strncpy(char* dst, const char* src, size_t n); size_t strlcpy(char* __restrict dst, const char* __restrict src, size_t len); __END_DECL #endif
DossierSansTitreEx/MiaouOS
src/libc/string/memchr.c
<reponame>DossierSansTitreEx/MiaouOS #include <string.h> void* memchr(const void* s, int c, size_t num) { unsigned char* cptr; unsigned char cc; cptr = (unsigned char*)s; cc = c; for (size_t i = 0; i < num; ++i) { if (cptr[i] == cc) return cptr + i; } return NULL; }
DossierSansTitreEx/MiaouOS
include/stdlib.h
<filename>include/stdlib.h #ifndef _STDLIB_H #define _STDLIB_H 1 #include <sys/cdefs.h> __BEGIN_DECL void abort(void) __attribute__((noreturn)); __END_DECL #endif
DossierSansTitreEx/MiaouOS
include/stdint.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _STDINT_H #define _STDINT_H 1 #include <sys/cdefs.h> #include <sys/_types/_int8_t.h> #include <sys/_types/_int16_t.h> #include <sys/_types/_int32_t.h> #include <sys/_types/_int64_t.h> #include <sys/_types/_uint8_t.h> #include <sys/_types/_uint16_t.h> #include <sys/_types/_uint32_t.h> #include <sys/_types/_uint64_t.h> typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; #include <sys/_types/_intptr_t.h> #include <sys/_types/_uintptr_t.h> #include <sys/_types/_intmax_t.h> #include <sys/_types/_uintmax_t.h> #define INT8_MIN -128 #define INT16_MIN -32768 #define INT32_MIN (-2147483647-1) #define INT64_MIN (-9223372036854775807LL-1) #define INT8_MAX 127 #define INT16_MAX 32767 #define INT32_MAX 2147483647 #define INT64_MAX 9223372036854775807LL #define UINT8_MAX 255 #define UINT16_MAX 65535 #define UINT32_MAX 4294967295 #define UINT64_MAX 18446744073709551616LL #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX #define INT_FAST8_MIN INT8_MIN #define INT_FAST16_MIN INT16_MIN #define INT_FAST32_MIN INT32_MIN #define INT_FAST64_MIN INT64_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX #define INTPTR_MIN INT64_MIN #define INTPTR_MAX INT64_MAX #define UINTPTR_MAX UINT64_MAX #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX #define PTRDIFF_MIN INT64_MIN #define PTRDIFF_MAX INT64_MAX #define SIG_ATOMIC_MIN INT64_MIN #define SIG_ATOMIC_MAX INT64_MAX #define SIZE_MAX UINT64_MAX #define WCHAR_MIN INT32_MIN #define WCHAR_MAX INT32_MAX #define WINT_MIN INT32_MIN #define WINT_MAX INT32_MAX #define INT8_C(a) a #define INT16_C(a) a #define INT32_C(a) a #define INT64_C(a) (a ## LL) #define UINT8_C(a) (a ## U) #define UINT16_C(a) (a ## U) #define UINT32_C(a) (a ## U) #define UINT64_C(a) (a ## ULL) #define INTMAX_C(a) (a ## LL) #define UINTMAX_C(a) (a ## ULL) #endif
DossierSansTitreEx/MiaouOS
src/libc/string/memmove.c
<filename>src/libc/string/memmove.c<gh_stars>1-10 #include <string.h> void* memmove(void* dst, const void* src, size_t len) { char* dst_ptr; const char* src_ptr; size_t i; dst_ptr = dst; src_ptr = src; /* No overlap */ if (src_ptr + len < dst_ptr || dst_ptr + len < src_ptr) return memcpy(dst, src, len); else if (src_ptr < dst_ptr) { for (i = len; i > 0; --i) dst_ptr[i - 1] = src_ptr[i - 1]; } else { for (i = 0; i < len; ++i) dst_ptr[i] = src_ptr[i]; } return dst; }
DossierSansTitreEx/MiaouOS
src/effel/gdt.h
#ifndef _GDT_H #define _GDT_H 1 void gdt_init(); #endif
DossierSansTitreEx/MiaouOS
include/sys/cdefs.h
#ifndef _SYS_CDEFS_H_ #define _SYS_CDEFS_H_ #if !defined(__GNUC__) # define __attribute__(x) #endif #if defined(__cplusplus) # define __BEGIN_DECL extern "C" { # define __END_DECL } # define __restrict #else # define __BEGIN_DECL # define __END_DECL # define __restrict restrict #endif #endif
DossierSansTitreEx/MiaouOS
src/libc/string/strncpy.c
<reponame>DossierSansTitreEx/MiaouOS<filename>src/libc/string/strncpy.c #include <string.h> char* strncpy(char* dst, const char* src, size_t n) { size_t i; char c; for (i = 0; i < n; ++i) { c = src[i]; dst[i] = c; if (c == 0) break; i++; } for (i = 0; i < n; ++i) dst[i] = 0; return dst; }
DossierSansTitreEx/MiaouOS
include/stdbool.h
<filename>include/stdbool.h #ifndef _STDBOOL_H #define _STDBOOL_H 1 #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif
DossierSansTitreEx/MiaouOS
src/effel/screen.c
<reponame>DossierSansTitreEx/MiaouOS #include <stdint.h> #include <string.h> #include <screen.h> #include <vmm.h> static char* monitor; static int32_t cursor_x; static int32_t cursor_y; void kscroll() { memmove(monitor, monitor + 80 * 2, 80 * 24 * 2); memset(monitor + 80 * 24 * 2, 0, 80 * 2); cursor_x = 0; cursor_y--; if (cursor_y < 0) cursor_y = 0; } void kputchar(char c) { uint32_t index; if (c == '\n') { cursor_x = 0; cursor_y++; return; } if (cursor_y >= 25) kscroll(); index = cursor_y * 80 + cursor_x; monitor[index * 2 + 0] = c; monitor[index * 2 + 1] = 0x07; cursor_x++; if (cursor_x >= 80) { cursor_x = 0; cursor_y++; } } void kprint_raw(const char* s, size_t size) { for (size_t i = 0; i < size; ++i) kputchar(s[i]); } void kprint(const char* s) { for (uint32_t i = 0; s[i]; ++i) kputchar(s[i]); } void kputs(const char* s) { kprint(s); kputchar('\n'); } static void _kprint_hex(uint64_t num) { static const char* const table = "0123456789abcdef"; uint8_t nibble; nibble = num % 16; num /= 16; if (num) _kprint_hex(num); kputchar(table[nibble]); } void kprint_hex(uint64_t num) { kprint("0x"); _kprint_hex(num); } void screen_init() { monitor = vmm_alloc_over(0xb8000, 80 * 25 * 2, 0); cursor_x = 0; cursor_y = 0; for (int i = 0; i < 25; ++i) kscroll(); }
DossierSansTitreEx/MiaouOS
include/sys/_types/_size_t.h
#ifndef _SYS__TYPES__SIZE_T_H_ #define _SYS__TYPES__SIZE_T_H_ #if defined(__SIZE_TYPE__) typedef __SIZE_TYPE__ size_t; #endif #endif