hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
0054a68a9816dda5f204d0d1133113d7bfb64ffc
12,925
c
C
src/pydegensac/degensac/ranH2el.c
evanscottgray/pydegensac
0b146e5c002833116adb59e3f676c9d35542fef5
[ "MIT" ]
191
2020-04-24T15:17:36.000Z
2022-03-30T03:08:47.000Z
src/pydegensac/degensac/ranH2el.c
evanscottgray/pydegensac
0b146e5c002833116adb59e3f676c9d35542fef5
[ "MIT" ]
11
2020-06-20T12:49:01.000Z
2022-03-31T11:20:58.000Z
src/pydegensac/degensac/ranH2el.c
evanscottgray/pydegensac
0b146e5c002833116adb59e3f676c9d35542fef5
[ "MIT" ]
29
2020-04-25T06:12:06.000Z
2022-02-28T03:57:46.000Z
#include <stdlib.h> #include <limits.h> #include <math.h> #include <memory.h> #include <matutls/ccmath.h> #include "lapwrap.h" /*#include <mex.h> */ #include "../matutls/matutl.h" #include "Htools.h" #include "rtools.h" #include "utools.h" #include "ranH.h" #include "ranH2el.h" Score ransacH2el (double *u10, int len, double th, double conf, int max_sam, double *H, unsigned char * inl, int *data_out, int do_lo, int inlLimit) { int *pool, no_sam, new_sam, *samidx; double *u6, *Z, *buffer; double *err, *d, h[9]; double *errs[5]; int i, j, *inliers, new_max, do_iterate, iter_cnt = 0, rej_cnt = 0; Score maxS = {0,0}, maxSs = {0,0}, S; unsigned seed; double N1[9], D1[9], N2[9], D2[9]; /* stored column-wise! */ double tol, v; if (inlLimit == 0) { /* in the case of unlimited least squares */ inlLimit = INT_MAX; } /* allocations */ u6 = (double *) malloc(6 * len * sizeof(double)); for (i = 0; i < len; ++i) { u6[i*6 + 0] = u10[i*10 + 0]; u6[i*6 + 1] = u10[i*10 + 1]; u6[i*6 + 2] = 1; u6[i*6 + 3] = u10[i*10 + 5]; u6[i*6 + 4] = u10[i*10 + 6]; u6[i*6 + 5] = 1; } pool = (int *)malloc(len * sizeof(int)); for (i = 0; i < len; i++) { pool[i] = i; } samidx = pool + len - 2; /* drawn sample (indexes) is moved to the back of the pool */ Z = (double *) malloc(len * 18 * sizeof(double)); lin_hg(u6, Z, pool, len); buffer = (double *) malloc(len * 18 * sizeof(double)); err = (double *) malloc(len * 4 * sizeof(double)); for (i = 0; i < 4; i++) { errs[i] = err + i * len; } errs[4] = errs[3]; inliers = (int *) malloc(len * sizeof(int)); no_sam = 0; seed = rand(); /* main RANSAC loop */ while(no_sam < max_sam) { no_sam ++; new_max = 0; do_iterate = 0; srand(seed); /* random minimal sample */ randsubset(pool, len, 2); seed = rand(); /* model */ getTransf(u10 + 10*samidx[0], N1, D1); getTransf(u10 + 10*samidx[1], N2, D2); if (A2toRH(N1, D1, N2, D2, u10, samidx, h)) { continue; } v = det3(h); tol = h[8]; tol = tol*tol*tol; //TODO if tol == 0 if (fabs(v/tol) < 10e-2) { continue; } /* consensus */ d = errs[0]; HDs(Z, u6, h, d, len); S = inlidxs(d, len, th, inliers); if (scoreLess(maxS, S)) { /* so-far-the-best */ maxS = S; errs[0] = errs[3]; errs[3] = d; memcpy(H,h,9*sizeof(double)); new_max = 1; } S = inlidxs(d, len, th*TAU, inliers); if (scoreLess(maxSs, S)) { /* so-far-the-best from sample */ maxSs = S; do_iterate = no_sam > ITER_SAM; if (!new_max) { errs[0] = errs[2]; errs[2] = d; } errs[4] = d; } if (no_sam >= ITER_SAM && iter_cnt == 0 && maxSs.I > 4) { /* after blocking, run LO on sftb sample */ do_iterate = 1; } /* Local Optimisation */ if (do_iterate && do_lo) { iter_cnt ++; /*******/ /* minimalistic LO' (just one iterations) */ /* S = iterH(u6, len, inliers, th, TC*th, 4, h, Z, errs, buffer, inlLimit); */ /*******/ /* full LO (subsampling and iterations) */ d = errs[0]; S = inlidxs(errs[4], len, TC*th*TAU, inliers); u2h(u6, inliers, S.I, h, buffer); HDs(Z, u6, h, d, len); S = inlidxs(d, len, th, inliers); S = inHraniEl (u10, u6, len, inliers, S.I, th, Z, errs, buffer, h, inlLimit); /*******/ tol = h[8]; tol = tol*tol*tol; if (scoreLess(maxS, S) && (fabs(det3(h)/tol) > 10e-2)) { maxS = S; d = errs[0]; errs[0] = errs[3]; errs[3] = d; memcpy(H, h, 9*sizeof(double)); new_max = 1; } } if (new_max) { /* update number of samples needed */ new_sam = nsamples(maxS.I+1, len, 2, conf); if (new_sam < max_sam) { max_sam = new_sam; } } } /* If there were no LO's, make at least one NOW! */ if (do_lo && !iter_cnt) { ++iter_cnt; /*******/ /* minimalistic LO' (just one iterations) */ /* S = iterH(u6, len, inliers, th, TC*th, 4, h, Z, errs, buffer, inlLimit); */ /*******/ /* full LO (subsampling and iterations) */ d = errs[0]; S = inlidxs(errs[4], len, TC*th*TAU, inliers); u2h(u6, inliers, S.I, h, buffer); HDs(Z, u6, h, d, len); S = inlidxs(d, len, th, inliers); S = inHraniEl (u10, u6, len, inliers, S.I, th, Z, errs, buffer, h, inlLimit); /*******/ tol = h[8]; tol = tol*tol*tol; if(scoreLess(maxS, S) && (fabs(det3(h)/tol) > 10e-2)) { maxS = S; d = errs[0]; errs[0] = errs[3]; errs[3] = d; memcpy(H, h, 9*sizeof(double)); } } if (inl) { /* set output field of inliers (binary this time) */ d = errs[3]; for (j = 0; j < len; j++) { if (d[j] <= th) { inl[j] = 1; } else { inl[j] = 0; } } } if (data_out) { data_out[0] = no_sam; data_out[1] = iter_cnt; data_out[2] = rej_cnt; } /* deallocations */ free(pool); free(Z); free(buffer); free(err); free(inliers); free(u6); return maxS; } void getTransf (double *u10, double *N, double *D) { D[0] = u10[2]; /* a */ D[1] = u10[3]; /* b */ D[2] = 0; D[3] = 0; D[4] = u10[4]; /* c */ D[5] = 0; D[6] = u10[0]; /* x */ D[7] = u10[1]; /* y */ D[8] = 1; N[0] = 1 / u10[7]; /* 1/a */ N[1] = - u10[8] / u10[7] / u10[9]; /* -b/(ac) */ N[2] = 0; N[3] = 0; N[4] = 1 / u10[9]; /* 1/c */ N[5] = 0; N[6] = - u10[5] / u10[7]; /* -x/a */ N[7] = (u10[8]*u10[5] - u10[7]*u10[6]) / u10[7] / u10[9]; /* (bx - ay)/(ac) */ N[8] = 1; } int A2toRH(double *N1, double *D1, double *N2, double *D2, double *u, int *samidx, double *h) { int do_norm = 0, i; double Z[15*15], ZT[15*15]; /* everything here is stored column-wise, unless noted */ double U[15*15]; double T1[3*3], iT1[3*3], T2[3*3], iT2[3*3]; double N1N[3*3], N2N[3*3], D1N[3*3], D2N[3*3], temp[3*3]; int nullsize, nullspace_buff[2*15]; for (i = 0; i < 2*7*15; ++i) { Z[i] = 0.0; } if (do_norm) { norm2pt(u[10*samidx[0] + 0], u[10*samidx[0] + 1], u[10*samidx[1] + 0], u[10*samidx[1] + 1], T1, iT1); norm2pt(u[10*samidx[0] + 5], u[10*samidx[0] + 6], u[10*samidx[1] + 5], u[10*samidx[1] + 6], T2, iT2); ZuN(Z, u + 10*samidx[0], T1, T2, 2); ZuN(Z+7, u + 10*samidx[1], T1, T2, 2); mmul(N1N, iT2, N1, 3); /* CCMath works with row-wise stored matrices, so we use reverted order: A = B*C -> A^T = C^T*B^T */ mmul(N2N, iT2, N2, 3); mmul(D1N, D1, T1, 3); mmul(D2N, D2, T1, 3); Znd(Z + 2*7*9, D1N, N1N, 2); Znd(Z + 2*7*9 + 2*7*3 + 7, D2N, N2N, 2); } else { Zu(Z, u + 10*samidx[0], 2); Zu(Z+7, u + 10*samidx[1], 2); Znd(Z + 2*7*9, D1, N1, 2); Znd(Z + 2*7*9 + 2*7*3 + 7, D2, N2, 2); } mattr(ZT, Z, 15, 2*7); for (i = 14*15; i < 15*15; ++i) { ZT[i] = 0; } nullsize = nullspace(ZT, U, 15, nullspace_buff); memcpy(h, U, 3*3 * sizeof(double)); trnm(h, 3); /* Equations are made for H stored row-wise, so transpose now */ if (do_norm) { /* Hn = iT1 * H * T2 -> Hn^T = T2^T * H^T * iT1^T */ mmul(temp, T2, h, 3); mmul(h, temp, iT1, 3); } return nullsize != 1; } int AntoRH(double *u, int *inls, int len, double *h) { if (len < 2) { return 1; } double Ni[3*3], Di[3*3]; if (len == 2) { double N2[3*3], D2[3*3]; getTransf(u + 10*inls[0], Ni, Di); getTransf(u + 10*inls[1], N2, D2); return A2toRH(Ni, Di, N2, D2, u, inls, h); } int do_norm = 1, i;//, k, l; double *Z; /* everything here is stored column-wise, unless noted */ double *U, *VT, *D; double T1[3*3], iT1[3*3], T2[3*3], iT2[3*3]; double Nn[3*3], Dn[3*3], temp[3*3]; int res; int noRows = 7 * len; int noCols = 9 + 3 * len; Z = (double *) malloc (noRows * noCols * sizeof(double)); U = (double *) malloc (noRows * noRows * sizeof(double)); VT = (double *) malloc (noCols * noCols * sizeof(double)); D = (double *) malloc (noCols * sizeof(double)); for (i = 0; i < noRows * noCols; ++i) { Z[i] = 0.0; } if (do_norm) { norm10(u, inls, len, T1, iT1); norm10(u+5, inls, len, T2, iT2); } for (i = 0; i < len; ++i) { getTransf(u + 10*inls[i], Ni, Di); /*printf("\n%dth correspondence:\n", inls[i]); printf("N_%d:\n", i); for (k = 0; k < 3; ++k) { for (l = 0; l < 3; ++l) { printf("%9.4f", Ni[k + l*3]); } printf("\n"); } printf("D_%d:\n", i); for (k = 0; k < 3; ++k) { for (l = 0; l < 3; ++l) { printf("%9.4f", Di[k + l*3]); } printf("\n"); }*/ if (do_norm) { mmul(Nn, iT2, Ni, 3); /* CCMath works with row-wise stored matrices, so we use reverted order: A = B*C -> A^T = C^T*B^T */ mmul(Dn, Di, T1, 3); ZuN(Z + 7*i, u + 10*inls[i], T1, T2, len); Znd(Z + len*7*9 + len*7*3*i + 7*i, Dn, Nn, len); } else { Zu(Z + 7*i, u + 10*inls[i], len); Znd(Z + len*7*9 + len*7*3*i + 7*i, Di, Ni, len); } } res = lap_SVD (D, Z, U, noRows, VT, noCols); for (i = 0; i < 9; ++i) { h[i] = VT[(i+1)*noCols - 1]; } trnm(h, 3); if (do_norm) { /* Hn = iT1 * H * T2 -> Hn^T = T2^T * H^T * iT1^T */ mmul(temp, T2, h, 3); mmul(h, temp, iT1, 3); } free(Z); free(U); free(D); free(VT); return res; } void Zu(double * Z, double * u, int len) { Z[0 + 0*len*7] = -1; Z[0 + 6*len*7] = _u1; Z[1 + 1*len*7] = -1; Z[1 + 7*len*7] = _u1; Z[2 + 2*len*7] = -1; Z[2 + 6*len*7] = - _u1 * _u4; Z[2 + 7*len*7] = - _u1 * _u5; Z[3 + 3*len*7] = -1; Z[3 + 6*len*7] = _u2; Z[4 + 4*len*7] = -1; Z[4 + 7*len*7] = _u2; Z[5 + 5*len*7] = -1; Z[5 + 6*len*7] = - _u2 * _u4; Z[5 + 7*len*7] = - _u2 * _u5; Z[6 + 8*len*7] = -1; Z[6 + 6*len*7] = - _u4; Z[6 + 7*len*7] = - _u5; } void ZuN(double * Z, double * u, double * T1, double * T2, int len) { Z[0 + 0*len*7] = -1; Z[0 + 6*len*7] = _u1*T1[0] + _u2*T1[3] + T1[6]; Z[1 + 1*len*7] = -1; Z[1 + 7*len*7] = _u1*T1[0] + _u2*T1[3] + T1[6]; Z[2 + 2*len*7] = -1; Z[2 + 6*len*7] = - (_u1*T1[0] + _u2*T1[3] + T1[6]) * (_u4*T2[0] + _u5*T2[3] + T2[6]); Z[2 + 7*len*7] = - (_u1*T1[0] + _u2*T1[3] + T1[6]) * (_u4*T2[1] + _u5*T2[4] + T2[7]); Z[3 + 3*len*7] = -1; Z[3 + 6*len*7] = _u1*T1[1] + _u2*T1[4] + T1[7]; Z[4 + 4*len*7] = -1; Z[4 + 7*len*7] = _u1*T1[1] + _u2*T1[4] + T1[7]; Z[5 + 5*len*7] = -1; Z[5 + 6*len*7] = - (_u1*T1[1] + _u2*T1[4] + T1[7]) * (_u4*T2[0] + _u5*T2[3] + T2[6]); Z[5 + 7*len*7] = - (_u1*T1[1] + _u2*T1[4] + T1[7]) * (_u4*T2[1] + _u5*T2[4] + T2[7]); Z[6 + 8*len*7] = -1; Z[6 + 6*len*7] = - (_u4*T2[0] + _u5*T2[3] + T2[6]); Z[6 + 7*len*7] = - (_u4*T2[1] + _u5*T2[4] + T2[7]); } void Znd(double * Z, double * A, double * B, int len) { /* A&B transposed by #defines! */ Z[2 + 2*len*7] = _a3; Z[5 + 2*len*7] = _a6; Z[6 + 2*len*7] = 1; Z[0 + 0*len*7] = _a2*_b1 - _a1*_b4; Z[1 + 0*len*7] = _a2*_b2 - _a1*_b5; Z[2 + 0*len*7] = _a2*_b3 - _a1*_b6; Z[3 + 0*len*7] = _a5*_b1 - _a4*_b4; Z[4 + 0*len*7] = _a5*_b2 - _a4*_b5; Z[5 + 0*len*7] = _a5*_b3 - _a4*_b6; Z[0 + 1*len*7] = _a1*_b1 + _a2*_b4; Z[1 + 1*len*7] = _a1*_b2 + _a2*_b5; Z[2 + 1*len*7] = _a1*_b3 + _a2*_b6; Z[3 + 1*len*7] = _a4*_b1 + _a5*_b4; Z[4 + 1*len*7] = _a4*_b2 + _a5*_b5; Z[5 + 1*len*7] = _a4*_b3 + _a5*_b6; } void norm2pt(double x1, double y1, double x2, double y2, double *T, double *iT) { double xm = (x1 + x2) / 2; double ym = (y1 + y2) / 2; double dx = (x1 - x2) / 2; double dy = (y1 - y2) / 2; double sc = sqrt(dx*dx + dy*dy); if (sc < 1) { sc = 1; } iT[0] = sc; iT[1] = 0; iT[2] = 0; iT[3] = 0; iT[4] = sc; iT[5] = 0; iT[6] = xm; iT[7] = ym; iT[8] = 1; sc = 1 / sc; T[0] = sc; T[1] = 0; T[2] = 0; T[3] = 0; T[4] = sc; T[5] = 0; T[6] = - xm * sc; T[7] = - ym * sc; T[8] = 1; } void norm10(double * u10, int * inls, int len, double * T, double * iT) { double xm = 0, ym = 0, sc = 0; int i; for (i = 0; i < len; ++i) { xm += u10[10 * inls[i]] / len; ym += u10[10 * inls[i] + 1] / len; } for (i = 0; i < len; ++i) { sc += sqrt((u10[10*inls[i]] - xm) * (u10[10*inls[i]] - xm) + (u10[10*inls[i]+1] - ym) * (u10[10*inls[i]+1] - ym)) / len; } sc /= SQRT2; iT[0] = sc; iT[1] = 0; iT[2] = 0; iT[3] = 0; iT[4] = sc; iT[5] = 0; iT[6] = xm; iT[7] = ym; iT[8] = 1; sc = 1 / sc; T[0] = sc; T[1] = 0; T[2] = 0; T[3] = 0; T[4] = sc; T[5] = 0; T[6] = - xm * sc; T[7] = - ym * sc; T[8] = 1; } Score inHraniEl (double * u10, double *u6, int len, int *inliers, int ninl, double th, double *Z, double **errs, double *buffer, double *H, unsigned inlLimit) { int ssiz, i; Score S, maxS = {0,0}; double *d, h[9]; int *sample; int *intbuff; int minPts = 4, loLimit = 8; intbuff = (int *) malloc (len * sizeof(int)); if (ninl < loLimit) { return maxS; } ssiz = ninl / 2; if (ssiz > 12) { ssiz = 12; } d = errs[2]; errs[2] = errs[0]; errs[0] = d; for (i = 0; i < RAN_REP; ++i) { sample = randsubset(inliers, ninl, ssiz); if (ssiz < minPts) { AntoRH(u10, sample, ssiz, h); } else { u2h(u6, sample, ssiz, h, buffer); } HDs (Z, u6, h, errs[0], len); errs[4] = errs[0]; S = iterH(u6, len, intbuff, th, TC*th, h, Z, errs, buffer, inlLimit); if (scoreLess(maxS, S)) { maxS = S; d = errs[2]; errs[2] = errs[0]; errs[0] = d; memcpy(H, h, 9*sizeof(double)); } } d = errs[2]; errs[2] = errs[0]; errs[0] = d; free(intbuff); return maxS; }
23.5
125
0.504371
63965dddbd3005f166eadd9a9fd93f80e27ae7bb
2,470
c
C
glibc/sysdeps/unix/sysv/linux/posix_fadvise.c
chyidl/mirror-glibc
3b17633afc85a9fb8cba0edc365d19403158c5a0
[ "BSD-3-Clause" ]
null
null
null
glibc/sysdeps/unix/sysv/linux/posix_fadvise.c
chyidl/mirror-glibc
3b17633afc85a9fb8cba0edc365d19403158c5a0
[ "BSD-3-Clause" ]
null
null
null
glibc/sysdeps/unix/sysv/linux/posix_fadvise.c
chyidl/mirror-glibc
3b17633afc85a9fb8cba0edc365d19403158c5a0
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2003-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #include <errno.h> #include <fcntl.h> #include <sysdep.h> /* Advice the system about the expected behaviour of the application with respect to the file associated with FD. */ #ifndef __OFF_T_MATCHES_OFF64_T /* Default implementation will use __NR_fadvise64 with expected argument positions (for instance i386 and powerpc32 that uses __ALIGNMENT_ARG). Second option will be used by arm which define __NR_arm_fadvise64_64 (redefined to __NR_fadvise64_64 in kernel-features.h) that behaves as __NR_fadvise64_64 (without the aligment argument required for the ABI). Third option will be used by mips o32. Mips will use a 7 argument syscall with __NR_fadvise64. s390 implements fadvice64_64 using a specific struct with arguments packed inside. This is the only implementation handled in arch-specific code. */ int posix_fadvise (int fd, off_t offset, off_t len, int advise) { INTERNAL_SYSCALL_DECL (err); # if defined (__NR_fadvise64) && !defined (__ASSUME_FADVISE64_AS_64_64) int ret = INTERNAL_SYSCALL_CALL (fadvise64, err, fd, __ALIGNMENT_ARG SYSCALL_LL (offset), len, advise); # else # ifdef __ASSUME_FADVISE64_64_6ARG int ret = INTERNAL_SYSCALL_CALL (fadvise64_64, err, fd, advise, SYSCALL_LL (offset), SYSCALL_LL (len)); # else # ifndef __NR_fadvise64_64 # define __NR_fadvise64_64 __NR_fadvise64 # endif int ret = INTERNAL_SYSCALL_CALL (fadvise64_64, err, fd, __ALIGNMENT_ARG SYSCALL_LL (offset), SYSCALL_LL (len), advise); # endif # endif if (INTERNAL_SYSCALL_ERROR_P (ret, err)) return INTERNAL_SYSCALL_ERRNO (ret, err); return 0; } #endif /* __OFF_T_MATCHES_OFF64_T */
35.797101
75
0.746964
a0a9ca4d679dd923a93699035c3ae090b1fa487b
1,313
c
C
libft/ft_strsub.c
Kys3r/Fdf
306506ca5c88aef6a814a3cb3c9d04d4082a5506
[ "MIT" ]
null
null
null
libft/ft_strsub.c
Kys3r/Fdf
306506ca5c88aef6a814a3cb3c9d04d4082a5506
[ "MIT" ]
null
null
null
libft/ft_strsub.c
Kys3r/Fdf
306506ca5c88aef6a814a3cb3c9d04d4082a5506
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_strsub.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: albarbos <albarbos@student.42.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2017/11/13 10:19:57 by albarbos #+# ## ## #+# */ /* Updated: 2018/02/19 15:34:31 by albarbos ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "libft.h" char *ft_strsub(char const *s, unsigned int start, size_t len) { unsigned int i; char *str; i = 0; if (!s || ft_strlen((char *)s) <= start) return (NULL); if (!(str = (char *)malloc(sizeof(char) * (len + 1)))) return (NULL); while (i < len && s[i]) str[i++] = s[start++]; str[i] = '\0'; return (str); }
42.354839
80
0.223153
9db525b478372d0688e5935160c6141c257c2b2a
10,725
h
C
Project/NeoPixelTest.X/mcc_generated_files/pin_manager.h
leb-phi/MicrochipNeoPixel
39a95529fd74298b33982e40123e777208445bdd
[ "MIT" ]
null
null
null
Project/NeoPixelTest.X/mcc_generated_files/pin_manager.h
leb-phi/MicrochipNeoPixel
39a95529fd74298b33982e40123e777208445bdd
[ "MIT" ]
null
null
null
Project/NeoPixelTest.X/mcc_generated_files/pin_manager.h
leb-phi/MicrochipNeoPixel
39a95529fd74298b33982e40123e777208445bdd
[ "MIT" ]
null
null
null
/** @Generated Pin Manager Header File @Company: Microchip Technology Inc. @File Name: pin_manager.h @Summary: This is the Pin Manager file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs @Description This header file provides APIs for driver for . Generation Information : Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.81.6 Device : PIC18F47K42 Driver Version : 2.11 The generated drivers are tested against the following: Compiler : XC8 2.30 and above MPLAB : MPLAB X 5.40 */ /* (c) 2018 Microchip Technology Inc. and its subsidiaries. Subject to your compliance with these terms, you may use Microchip software and any derivatives exclusively with Microchip products. It is your responsibility to comply with third party license terms applicable to your use of third party software (including open source software) that may accompany Microchip software. THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. */ #ifndef PIN_MANAGER_H #define PIN_MANAGER_H /** Section: Included Files */ #include <xc.h> #define INPUT 1 #define OUTPUT 0 #define HIGH 1 #define LOW 0 #define ANALOG 1 #define DIGITAL 0 #define PULL_UP_ENABLED 1 #define PULL_UP_DISABLED 0 // get/set RA0 procedures #define RA0_SetHigh() do { LATAbits.LATA0 = 1; } while(0) #define RA0_SetLow() do { LATAbits.LATA0 = 0; } while(0) #define RA0_Toggle() do { LATAbits.LATA0 = ~LATAbits.LATA0; } while(0) #define RA0_GetValue() PORTAbits.RA0 #define RA0_SetDigitalInput() do { TRISAbits.TRISA0 = 1; } while(0) #define RA0_SetDigitalOutput() do { TRISAbits.TRISA0 = 0; } while(0) #define RA0_SetPullup() do { WPUAbits.WPUA0 = 1; } while(0) #define RA0_ResetPullup() do { WPUAbits.WPUA0 = 0; } while(0) #define RA0_SetAnalogMode() do { ANSELAbits.ANSELA0 = 1; } while(0) #define RA0_SetDigitalMode() do { ANSELAbits.ANSELA0 = 0; } while(0) // get/set RA4 procedures #define RA4_SetHigh() do { LATAbits.LATA4 = 1; } while(0) #define RA4_SetLow() do { LATAbits.LATA4 = 0; } while(0) #define RA4_Toggle() do { LATAbits.LATA4 = ~LATAbits.LATA4; } while(0) #define RA4_GetValue() PORTAbits.RA4 #define RA4_SetDigitalInput() do { TRISAbits.TRISA4 = 1; } while(0) #define RA4_SetDigitalOutput() do { TRISAbits.TRISA4 = 0; } while(0) #define RA4_SetPullup() do { WPUAbits.WPUA4 = 1; } while(0) #define RA4_ResetPullup() do { WPUAbits.WPUA4 = 0; } while(0) #define RA4_SetAnalogMode() do { ANSELAbits.ANSELA4 = 1; } while(0) #define RA4_SetDigitalMode() do { ANSELAbits.ANSELA4 = 0; } while(0) // get/set RB1 procedures #define RB1_SetHigh() do { LATBbits.LATB1 = 1; } while(0) #define RB1_SetLow() do { LATBbits.LATB1 = 0; } while(0) #define RB1_Toggle() do { LATBbits.LATB1 = ~LATBbits.LATB1; } while(0) #define RB1_GetValue() PORTBbits.RB1 #define RB1_SetDigitalInput() do { TRISBbits.TRISB1 = 1; } while(0) #define RB1_SetDigitalOutput() do { TRISBbits.TRISB1 = 0; } while(0) #define RB1_SetPullup() do { WPUBbits.WPUB1 = 1; } while(0) #define RB1_ResetPullup() do { WPUBbits.WPUB1 = 0; } while(0) #define RB1_SetAnalogMode() do { ANSELBbits.ANSELB1 = 1; } while(0) #define RB1_SetDigitalMode() do { ANSELBbits.ANSELB1 = 0; } while(0) // get/set RB3 procedures #define RB3_SetHigh() do { LATBbits.LATB3 = 1; } while(0) #define RB3_SetLow() do { LATBbits.LATB3 = 0; } while(0) #define RB3_Toggle() do { LATBbits.LATB3 = ~LATBbits.LATB3; } while(0) #define RB3_GetValue() PORTBbits.RB3 #define RB3_SetDigitalInput() do { TRISBbits.TRISB3 = 1; } while(0) #define RB3_SetDigitalOutput() do { TRISBbits.TRISB3 = 0; } while(0) #define RB3_SetPullup() do { WPUBbits.WPUB3 = 1; } while(0) #define RB3_ResetPullup() do { WPUBbits.WPUB3 = 0; } while(0) #define RB3_SetAnalogMode() do { ANSELBbits.ANSELB3 = 1; } while(0) #define RB3_SetDigitalMode() do { ANSELBbits.ANSELB3 = 0; } while(0) // get/set RB4 procedures #define RB4_SetHigh() do { LATBbits.LATB4 = 1; } while(0) #define RB4_SetLow() do { LATBbits.LATB4 = 0; } while(0) #define RB4_Toggle() do { LATBbits.LATB4 = ~LATBbits.LATB4; } while(0) #define RB4_GetValue() PORTBbits.RB4 #define RB4_SetDigitalInput() do { TRISBbits.TRISB4 = 1; } while(0) #define RB4_SetDigitalOutput() do { TRISBbits.TRISB4 = 0; } while(0) #define RB4_SetPullup() do { WPUBbits.WPUB4 = 1; } while(0) #define RB4_ResetPullup() do { WPUBbits.WPUB4 = 0; } while(0) #define RB4_SetAnalogMode() do { ANSELBbits.ANSELB4 = 1; } while(0) #define RB4_SetDigitalMode() do { ANSELBbits.ANSELB4 = 0; } while(0) // get/set RC3 procedures #define RC3_SetHigh() do { LATCbits.LATC3 = 1; } while(0) #define RC3_SetLow() do { LATCbits.LATC3 = 0; } while(0) #define RC3_Toggle() do { LATCbits.LATC3 = ~LATCbits.LATC3; } while(0) #define RC3_GetValue() PORTCbits.RC3 #define RC3_SetDigitalInput() do { TRISCbits.TRISC3 = 1; } while(0) #define RC3_SetDigitalOutput() do { TRISCbits.TRISC3 = 0; } while(0) #define RC3_SetPullup() do { WPUCbits.WPUC3 = 1; } while(0) #define RC3_ResetPullup() do { WPUCbits.WPUC3 = 0; } while(0) #define RC3_SetAnalogMode() do { ANSELCbits.ANSELC3 = 1; } while(0) #define RC3_SetDigitalMode() do { ANSELCbits.ANSELC3 = 0; } while(0) // get/set RC4 procedures #define RC4_SetHigh() do { LATCbits.LATC4 = 1; } while(0) #define RC4_SetLow() do { LATCbits.LATC4 = 0; } while(0) #define RC4_Toggle() do { LATCbits.LATC4 = ~LATCbits.LATC4; } while(0) #define RC4_GetValue() PORTCbits.RC4 #define RC4_SetDigitalInput() do { TRISCbits.TRISC4 = 1; } while(0) #define RC4_SetDigitalOutput() do { TRISCbits.TRISC4 = 0; } while(0) #define RC4_SetPullup() do { WPUCbits.WPUC4 = 1; } while(0) #define RC4_ResetPullup() do { WPUCbits.WPUC4 = 0; } while(0) #define RC4_SetAnalogMode() do { ANSELCbits.ANSELC4 = 1; } while(0) #define RC4_SetDigitalMode() do { ANSELCbits.ANSELC4 = 0; } while(0) // get/set RC6 procedures #define RC6_SetHigh() do { LATCbits.LATC6 = 1; } while(0) #define RC6_SetLow() do { LATCbits.LATC6 = 0; } while(0) #define RC6_Toggle() do { LATCbits.LATC6 = ~LATCbits.LATC6; } while(0) #define RC6_GetValue() PORTCbits.RC6 #define RC6_SetDigitalInput() do { TRISCbits.TRISC6 = 1; } while(0) #define RC6_SetDigitalOutput() do { TRISCbits.TRISC6 = 0; } while(0) #define RC6_SetPullup() do { WPUCbits.WPUC6 = 1; } while(0) #define RC6_ResetPullup() do { WPUCbits.WPUC6 = 0; } while(0) #define RC6_SetAnalogMode() do { ANSELCbits.ANSELC6 = 1; } while(0) #define RC6_SetDigitalMode() do { ANSELCbits.ANSELC6 = 0; } while(0) // get/set LED0 aliases #define LED0_TRIS TRISEbits.TRISE0 #define LED0_LAT LATEbits.LATE0 #define LED0_PORT PORTEbits.RE0 #define LED0_WPU WPUEbits.WPUE0 #define LED0_OD ODCONEbits.ODCE0 #define LED0_ANS ANSELEbits.ANSELE0 #define LED0_SetHigh() do { LATEbits.LATE0 = 1; } while(0) #define LED0_SetLow() do { LATEbits.LATE0 = 0; } while(0) #define LED0_Toggle() do { LATEbits.LATE0 = ~LATEbits.LATE0; } while(0) #define LED0_GetValue() PORTEbits.RE0 #define LED0_SetDigitalInput() do { TRISEbits.TRISE0 = 1; } while(0) #define LED0_SetDigitalOutput() do { TRISEbits.TRISE0 = 0; } while(0) #define LED0_SetPullup() do { WPUEbits.WPUE0 = 1; } while(0) #define LED0_ResetPullup() do { WPUEbits.WPUE0 = 0; } while(0) #define LED0_SetPushPull() do { ODCONEbits.ODCE0 = 0; } while(0) #define LED0_SetOpenDrain() do { ODCONEbits.ODCE0 = 1; } while(0) #define LED0_SetAnalogMode() do { ANSELEbits.ANSELE0 = 1; } while(0) #define LED0_SetDigitalMode() do { ANSELEbits.ANSELE0 = 0; } while(0) // get/set SW0 aliases #define SW0_TRIS TRISEbits.TRISE2 #define SW0_LAT LATEbits.LATE2 #define SW0_PORT PORTEbits.RE2 #define SW0_WPU WPUEbits.WPUE2 #define SW0_OD ODCONEbits.ODCE2 #define SW0_ANS ANSELEbits.ANSELE2 #define SW0_SetHigh() do { LATEbits.LATE2 = 1; } while(0) #define SW0_SetLow() do { LATEbits.LATE2 = 0; } while(0) #define SW0_Toggle() do { LATEbits.LATE2 = ~LATEbits.LATE2; } while(0) #define SW0_GetValue() PORTEbits.RE2 #define SW0_SetDigitalInput() do { TRISEbits.TRISE2 = 1; } while(0) #define SW0_SetDigitalOutput() do { TRISEbits.TRISE2 = 0; } while(0) #define SW0_SetPullup() do { WPUEbits.WPUE2 = 1; } while(0) #define SW0_ResetPullup() do { WPUEbits.WPUE2 = 0; } while(0) #define SW0_SetPushPull() do { ODCONEbits.ODCE2 = 0; } while(0) #define SW0_SetOpenDrain() do { ODCONEbits.ODCE2 = 1; } while(0) #define SW0_SetAnalogMode() do { ANSELEbits.ANSELE2 = 1; } while(0) #define SW0_SetDigitalMode() do { ANSELEbits.ANSELE2 = 0; } while(0) /** @Param none @Returns none @Description GPIO and peripheral I/O initialization @Example PIN_MANAGER_Initialize(); */ void PIN_MANAGER_Initialize (void); /** * @Param none * @Returns none * @Description Interrupt on Change Handling routine * @Example PIN_MANAGER_IOC(); */ void PIN_MANAGER_IOC(void); #endif // PIN_MANAGER_H /** End of File */
46.030043
106
0.637016
a5d1e02aa753d843933adaa4b643477cbd41a58e
8,802
h
C
VTK/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/TestingImplicitFunction.h
brown-ccv/paraview-scalable
64b221a540737d2ac94a120039bd8d1e661bdc8f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
VTK/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/TestingImplicitFunction.h
brown-ccv/paraview-scalable
64b221a540737d2ac94a120039bd8d1e661bdc8f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
VTK/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/TestingImplicitFunction.h
brown-ccv/paraview-scalable
64b221a540737d2ac94a120039bd8d1e661bdc8f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2014 UT-Battelle, LLC. // Copyright 2014 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ #ifndef vtk_m_cont_testing_TestingImplicitFunction_h #define vtk_m_cont_testing_TestingImplicitFunction_h #include <vtkm/cont/CoordinateSystem.h> #include <vtkm/cont/DeviceAdapterListTag.h> #include <vtkm/cont/ImplicitFunctionHandle.h> #include <vtkm/cont/internal/DeviceAdapterTag.h> #include <vtkm/cont/testing/MakeTestDataSet.h> #include <vtkm/cont/testing/Testing.h> #include <vtkm/internal/Configure.h> #include <vtkm/worklet/DispatcherMapField.h> #include <vtkm/worklet/WorkletMapField.h> #include <array> namespace vtkm { namespace cont { namespace testing { namespace implicit_function_detail { class EvaluateImplicitFunction : public vtkm::worklet::WorkletMapField { public: using ControlSignature = void(FieldIn<Vec3>, FieldOut<Scalar>); using ExecutionSignature = void(_1, _2); EvaluateImplicitFunction(const vtkm::ImplicitFunction* function) : Function(function) { } template <typename VecType, typename ScalarType> VTKM_EXEC void operator()(const VecType& point, ScalarType& val) const { val = this->Function->Value(point); } private: const vtkm::ImplicitFunction* Function; }; template <typename DeviceAdapter> void EvaluateOnCoordinates(vtkm::cont::CoordinateSystem points, const vtkm::cont::ImplicitFunctionHandle& function, vtkm::cont::ArrayHandle<vtkm::FloatDefault>& values, DeviceAdapter device) { using EvalDispatcher = vtkm::worklet::DispatcherMapField<EvaluateImplicitFunction, DeviceAdapter>; EvaluateImplicitFunction eval(function.PrepareForExecution(device)); EvalDispatcher(eval).Invoke(points, values); } template <std::size_t N> bool TestArrayEqual(const vtkm::cont::ArrayHandle<vtkm::FloatDefault>& result, const std::array<vtkm::FloatDefault, N>& expected) { bool success = false; auto portal = result.GetPortalConstControl(); vtkm::Id count = portal.GetNumberOfValues(); if (static_cast<std::size_t>(count) == N) { success = true; for (vtkm::Id i = 0; i < count; ++i) { if (!test_equal(portal.Get(i), expected[static_cast<std::size_t>(i)])) { success = false; break; } } } if (!success) { if (count == 0) { std::cout << "result: <empty>\n"; } else { std::cout << "result: " << portal.Get(0); for (vtkm::Id i = 1; i < count; ++i) { std::cout << ", " << portal.Get(i); } std::cout << "\n"; } } return success; } } // anonymous namespace class TestingImplicitFunction { public: TestingImplicitFunction() : Input(vtkm::cont::testing::MakeTestDataSet().Make3DExplicitDataSet2()) { } template <typename DeviceAdapter> void Run(DeviceAdapter device) { this->TestBox(device); this->TestCylinder(device); this->TestFrustum(device); this->TestPlane(device); this->TestSphere(device); } private: template <typename DeviceAdapter> void TestBox(DeviceAdapter device) { std::cout << "Testing vtkm::Box on " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName() << "\n"; vtkm::cont::ArrayHandle<vtkm::FloatDefault> values; implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), vtkm::cont::make_ImplicitFunctionHandle( vtkm::Box({ 0.0f, -0.5f, -0.5f }, { 1.5f, 1.5f, 0.5f })), values, device); std::array<vtkm::FloatDefault, 8> expected = { { 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, -0.5f, 0.5f, 0.5f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected), "Result does not match expected values"); } template <typename DeviceAdapter> void TestCylinder(DeviceAdapter device) { std::cout << "Testing vtkm::Cylinder on " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName() << "\n"; vtkm::Cylinder cylinder; cylinder.SetCenter({ 0.0f, 0.0f, 1.0f }); cylinder.SetAxis({ 0.0f, 1.0f, 0.0f }); cylinder.SetRadius(1.0f); vtkm::cont::ArrayHandle<vtkm::FloatDefault> values; implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), vtkm::cont::ImplicitFunctionHandle(&cylinder, false), values, device); std::array<vtkm::FloatDefault, 8> expected = { { 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected), "Result does not match expected values"); } template <typename DeviceAdapter> void TestFrustum(DeviceAdapter device) { std::cout << "Testing vtkm::Frustum on " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName() << "\n"; vtkm::Vec<vtkm::FloatDefault, 3> points[8] = { { 0.0f, 0.0f, 0.0f }, // 0 { 1.0f, 0.0f, 0.0f }, // 1 { 1.0f, 0.0f, 1.0f }, // 2 { 0.0f, 0.0f, 1.0f }, // 3 { 0.5f, 1.5f, 0.5f }, // 4 { 1.5f, 1.5f, 0.5f }, // 5 { 1.5f, 1.5f, 1.5f }, // 6 { 0.5f, 1.5f, 1.5f } // 7 }; vtkm::Frustum frustum; frustum.CreateFromPoints(points); vtkm::cont::ArrayHandle<vtkm::FloatDefault> values; implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), vtkm::cont::make_ImplicitFunctionHandle(frustum), values, device); std::array<vtkm::FloatDefault, 8> expected = { { 0.0f, 0.0f, 0.0f, 0.0f, 0.316228f, 0.316228f, -0.316228f, 0.316228f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected), "Result does not match expected values"); } template <typename DeviceAdapter> void TestPlane(DeviceAdapter device) { std::cout << "Testing vtkm::Plane on " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName() << "\n"; auto planeHandle = vtkm::cont::make_ImplicitFunctionHandle<vtkm::Plane>( vtkm::make_Vec(0.5f, 0.5f, 0.5f), vtkm::make_Vec(1.0f, 0.0f, 1.0f)); auto plane = static_cast<vtkm::Plane*>(planeHandle.Get()); vtkm::cont::ArrayHandle<vtkm::FloatDefault> values; implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), planeHandle, values, device); std::array<vtkm::FloatDefault, 8> expected1 = { { -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected1), "Result does not match expected values"); plane->SetNormal({ -1.0f, 0.0f, -1.0f }); implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), planeHandle, values, device); std::array<vtkm::FloatDefault, 8> expected2 = { { 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected2), "Result does not match expected values"); } template <typename DeviceAdapter> void TestSphere(DeviceAdapter device) { std::cout << "Testing vtkm::Sphere on " << vtkm::cont::DeviceAdapterTraits<DeviceAdapter>::GetName() << "\n"; vtkm::cont::ArrayHandle<vtkm::FloatDefault> values; implicit_function_detail::EvaluateOnCoordinates( this->Input.GetCoordinateSystem(0), vtkm::cont::make_ImplicitFunctionHandle<vtkm::Sphere>(vtkm::make_Vec(0.0f, 0.0f, 0.0f), 1.0f), values, device); std::array<vtkm::FloatDefault, 8> expected = { { -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 2.0f, 1.0f } }; VTKM_TEST_ASSERT(implicit_function_detail::TestArrayEqual(values, expected), "Result does not match expected values"); } vtkm::cont::DataSet Input; }; } } } // vtmk::cont::testing #endif //vtk_m_cont_testing_TestingImplicitFunction_h
31.891304
100
0.643604
cbdd7881bf7701a7c9aa14b5e910cce88e925ea1
816
h
C
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESpriteKitParticleEditor/SKObjectLibraryAsset.h
wokalski/Distraction-Free-Xcode-plugin
54ab4b9d9825e8370855b7985d6ff39d64c19f25
[ "MIT" ]
25
2016-03-03T07:43:56.000Z
2021-09-05T08:47:40.000Z
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESpriteKitParticleEditor/SKObjectLibraryAsset.h
wokalski/Distraction-Free-Xcode-plugin
54ab4b9d9825e8370855b7985d6ff39d64c19f25
[ "MIT" ]
8
2016-02-23T18:40:20.000Z
2016-08-18T13:21:05.000Z
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESpriteKitParticleEditor/SKObjectLibraryAsset.h
wokalski/Distraction-Free-Xcode-plugin
54ab4b9d9825e8370855b7985d6ff39d64c19f25
[ "MIT" ]
4
2016-02-24T13:24:27.000Z
2016-06-28T12:50:36.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "NSCoding.h" @class NSImage, NSString, SKNode; @interface SKObjectLibraryAsset : NSObject <NSCoding> { SKNode *_node; NSImage *_image; NSString *_title; NSString *_subtitle; NSString *_summary; } @property(copy) NSString *summary; // @synthesize summary=_summary; @property(copy) NSString *subtitle; // @synthesize subtitle=_subtitle; @property(copy) NSString *title; // @synthesize title=_title; @property(retain) NSImage *image; // @synthesize image=_image; @property(retain, nonatomic) SKNode *node; // @synthesize node=_node; - (void).cxx_destruct; - (id)initWithCoder:(id)arg1; - (void)encodeWithCoder:(id)arg1; @end
24.727273
83
0.703431
8531a4c7a7b88924cd1688f469c4ede9a1cb88ad
1,134
h
C
PIPS-IPM/Drivers/statgdx/pchutil.h
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
6
2020-10-29T15:14:14.000Z
2021-07-14T13:31:54.000Z
PIPS-IPM/Drivers/statgdx/pchutil.h
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
null
null
null
PIPS-IPM/Drivers/statgdx/pchutil.h
dRehfeldt/PIPS
24d3ea89a0a1aa77c133cfc698a568eb685c9fdb
[ "BSD-3-Clause-LBNL" ]
1
2019-02-15T16:30:44.000Z
2019-02-15T16:30:44.000Z
#ifndef _P3___pchutil___H #define _P3___pchutil___H typedef SYSTEM_uint8 _sub_0PCHUTIL; typedef SYSTEM_ansichar PCHUTIL_shortstrbuf[256]; Function(SYSTEM_P3_pansichar ) PCHUTIL_strtopchar( const SYSTEM_ansichar *s); Function(SYSTEM_P3_pansichar ) PCHUTIL_emptytopchar(void); Function(SYSTEM_ansichar *) PCHUTIL_pchartostr( SYSTEM_ansichar *result, SYSTEM_uint8 _len_ret, SYSTEM_P3_pansichar p); Procedure PCHUTIL_convertpchar( SYSTEM_P3_pansichar p, SYSTEM_ansichar *s); Function(SYSTEM_integer ) PCHUTIL_pcharlen( SYSTEM_P3_pansichar p); Procedure PCHUTIL_pcharconcatpchar( SYSTEM_P3_pansichar pdest, SYSTEM_integer *w, SYSTEM_P3_pansichar psrc); Procedure PCHUTIL_pcharconcatstr( SYSTEM_P3_pansichar pdest, SYSTEM_integer *w, const SYSTEM_ansichar *src); Procedure PCHUTIL_strpcopyn( SYSTEM_P3_pansichar pdest, const SYSTEM_ansichar *src, SYSTEM_integer n); Function(SYSTEM_P3_pansichar ) PCHUTIL_strtostrbuf( const SYSTEM_ansichar *src, SYSTEM_ansichar *dest); extern void _Init_Module_pchutil(void); extern void _Final_Module_pchutil(void); #endif /* ! defined _P3___pchutil___H */
24.12766
58
0.816578
e34f0cb3d082492ffbd1d8baf21a5dcdede844a9
93,271
c
C
convert.c
rbultje/c99-to-c89
47826cc230b64d99fb357956b242c5908510be1e
[ "Apache-2.0" ]
17
2015-02-05T20:59:02.000Z
2020-07-07T05:20:39.000Z
convert.c
rbultje/c99-to-c89
47826cc230b64d99fb357956b242c5908510be1e
[ "Apache-2.0" ]
null
null
null
convert.c
rbultje/c99-to-c89
47826cc230b64d99fb357956b242c5908510be1e
[ "Apache-2.0" ]
null
null
null
/* * C99-to-MSVC-compatible-C89 syntax converter * Copyright (c) 2012 Ronald S. Bultje <rsbultje@gmail.com> * Copyright (c) 2012 Derek Buitenhuis <derek.buitenhuis@gmail.com> * Copyright (c) 2012 Martin Storsjo <martin@martin.st> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <stdio.h> #include <clang-c/Index.h> #include <string.h> #include <stdlib.h> #include <inttypes.h> /* * The basic idea of the token parser is to "stack" ordered tokens * (i.e. ordering is done by libclang) in such a way that we can * re-arrange them on the fly before printing it back out to an * output file. * * Example: * * x = (AVRational) { y, z }; * becomes * { AVRational temp = { y, z }; x = temp; } * * x = function((AVRational) { y, z }); * becomes * { AVRational temp = { y, z }; x = function(temp); } * * return function((AVRational) { y, z }); * becomes * { AVRational temp = { y, z }; return function(temp); } * * int var = ((int[2]) { 1, 2 })[1]; * becomes * int var; { int temp[2] = { 1, 2 }; var = temp[1]; { [..] } } * * Note in the above, that the [..] indeed means the whole rest * of the statements in the same context needs to be within the * brackets, otherwise the resulting code could contain mixed * variable declarations and statements, which c89 does not allow. * * Like for compound literals, c89 does not support designated * initializers, thus we attempt to replace them. The basic idea * is to parse the layout of structs and enums, and then to parse * expressions like: * { * [index1] = val1, * [index2] = val2, * } * or * { * .member1 = val1, * .member2 = val2, * } * and convert these to ordered struct/array initializers without * designation, i.e.: * { * val1, * val2, * } * Note that in cases where the indexes or members are not ordered, * i.e. their order in the struct (for members) is different from * the order of initialization in the expression, or their numeric * values are not linearly ascending in the same way as they are * presented in the expression, then we have to reorder the expressions * and, in some cases, insert gap fillers. For example, * { * [index3] = val3, * [index1] = val1, * } * becomes * { * val1, 0, * val3, * } * (assuming index1 is the first value and index3 is the third value * in an enum, and in between these two is a value index2 which is * not used in this designated initializer expression. If the values * themselves are structs, we use {} instead of 0 as a gap filler. */ typedef struct { char *type; unsigned struct_decl_idx; char *name; unsigned n_ptrs; // 0 if not a pointer unsigned array_depth; // 0 if no array CXCursor cursor; } StructMember; typedef struct { StructMember *entries; unsigned n_entries; unsigned n_allocated_entries; char *name; CXCursor cursor; int is_union; } StructDeclaration; static StructDeclaration *structs = NULL; static unsigned n_structs = 0; static unsigned n_allocated_structs = 0; typedef struct { char *name; int value; CXCursor cursor; } EnumMember; typedef struct { EnumMember *entries; unsigned n_entries; unsigned n_allocated_entries; char *name; CXCursor cursor; } EnumDeclaration; static EnumDeclaration *enums = NULL; static unsigned n_enums = 0; static unsigned n_allocated_enums = 0; /* FIXME we're not taking pointers or array sizes into account here, * in large part because Libav doesn't use those in combination with * typedefs. */ typedef struct { char *proxy; char *name; unsigned struct_decl_idx; unsigned enum_decl_idx; CXCursor cursor; } TypedefDeclaration; static TypedefDeclaration *typedefs = NULL; static unsigned n_typedefs = 0; static unsigned n_allocated_typedefs = 0; enum StructArrayType { TYPE_IRRELEVANT = 0, TYPE_STRUCT = 1, TYPE_ARRAY = 2, }; typedef struct { unsigned index; struct { unsigned start, end; } value_offset, expression_offset; } StructArrayItem; typedef struct { enum StructArrayType type; unsigned struct_decl_idx; unsigned array_depth; StructArrayItem *entries; unsigned level; unsigned n_entries; unsigned n_allocated_entries; struct { unsigned start, end; } value_offset; int convert_to_assignment; char *name; } StructArrayList; static StructArrayList *struct_array_lists = NULL; static unsigned n_struct_array_lists = 0; static unsigned n_allocated_struct_array_lists = 0; typedef struct { int end; int n_scopes; } EndScope; static EndScope *end_scopes = NULL; static unsigned n_end_scopes = 0; static unsigned n_allocated_end_scopes = 0; static FILE *out; static CXTranslationUnit TU; #define DEBUG 0 #define dprintf(...) \ if (DEBUG) \ printf(__VA_ARGS__) static unsigned find_token_index(CXToken *tokens, unsigned n_tokens, const char *str) { unsigned n; for (n = n_tokens - 1; n != (unsigned) -1; n--) { CXString tstr = clang_getTokenSpelling(TU, tokens[n]); const char *cstr = clang_getCString(tstr); int res = strcmp(str, cstr); clang_disposeString(tstr); if (!res) return n; } fprintf(stderr, "Could not find token %s in set\n", str); exit(1); } static char *concat_name(CXToken *tokens, unsigned int from, unsigned to) { unsigned int cnt = 0, n; char *str; for (n = from; n <= to; n++) { CXString tstr = clang_getTokenSpelling(TU, tokens[n]); const char *cstr = clang_getCString(tstr); cnt += strlen(cstr) + 1; clang_disposeString(tstr); } str = (char *) malloc(cnt); if (!str) { fprintf(stderr, "Out of memory\n"); exit(1); } for (cnt = 0, n = from; n <= to; n++) { CXString tstr = clang_getTokenSpelling(TU, tokens[n]); const char *cstr = clang_getCString(tstr); int len = strlen(cstr); memcpy(&str[cnt], cstr, len); if (n == to) { str[cnt + len] = 0; } else { str[cnt + len] = ' '; } cnt += len + 1; clang_disposeString(tstr); } return str; } static void register_struct(const char *str, CXCursor cursor, TypedefDeclaration *decl_ptr, int is_union); static void register_enum(const char *str, CXCursor cursor, TypedefDeclaration *decl_ptr); static unsigned find_struct_decl_idx_for_type_name(const char *name); static enum CXChildVisitResult find_anon_struct(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXString cstr = clang_getCursorSpelling(cursor); const char *str = clang_getCString(cstr); switch (cursor.kind) { case CXCursor_StructDecl: register_struct(str, cursor, client_data, 0); break; case CXCursor_UnionDecl: register_struct(str, cursor, client_data, 1); break; case CXCursor_EnumDecl: register_enum(str, cursor, client_data); break; case CXCursor_TypeRef: { TypedefDeclaration *td = client_data; td->struct_decl_idx = find_struct_decl_idx_for_type_name(str); break; } default: break; } clang_disposeString(cstr); return CXChildVisit_Continue; } static enum CXChildVisitResult fill_struct_members(CXCursor cursor, CXCursor parent, CXClientData client_data) { unsigned decl_idx = (unsigned) client_data; StructDeclaration *decl = &structs[decl_idx]; CXString cstr = clang_getCursorSpelling(cursor); const char *str = clang_getCString(cstr); switch (cursor.kind) { case CXCursor_FieldDecl: { unsigned n = decl->n_entries, idx, m; CXToken *tokens = 0; unsigned int n_tokens = 0; CXSourceRange range = clang_getCursorExtent(cursor); TypedefDeclaration td; // padding bitfields if (!strcmp(str, "")) { clang_disposeString(cstr); return CXChildVisit_Continue; } clang_tokenize(TU, range, &tokens, &n_tokens); if (decl->n_entries == decl->n_allocated_entries) { unsigned num = decl->n_allocated_entries + 16; void *mem = realloc(decl->entries, sizeof(*decl->entries) * num); if (!mem) { fprintf(stderr, "Ran out of memory while declaring field %s in %s\n", str, decl->name); exit(1); } decl->entries = (StructMember *) mem; decl->n_allocated_entries = num; } decl->entries[n].name = strdup(str); decl->entries[n].cursor = cursor; decl->n_entries++; idx = find_token_index(tokens, n_tokens, str); decl->entries[n].n_ptrs = 0; decl->entries[n].array_depth = 0; for (m = idx + 1; m < n_tokens; m++) { CXString tstr = clang_getTokenSpelling(TU, tokens[m]); const char *cstr = clang_getCString(tstr); int res = strcmp(cstr, ";") && strcmp(cstr, ","); if (!strcmp(cstr, "[")) decl->entries[n].array_depth++; clang_disposeString(tstr); if (!res) break; } for (;;) { unsigned im1 = idx - 1 - decl->entries[n].n_ptrs; CXString tstr = clang_getTokenSpelling(TU, tokens[im1]); const char *cstr = clang_getCString(tstr); int res = strcmp(cstr, "*"); clang_disposeString(tstr); if (!res) { decl->entries[n].n_ptrs++; } else { break; } } do { unsigned im1 = idx - 1 - decl->entries[n].n_ptrs; CXString tstr = clang_getTokenSpelling(TU, tokens[im1]); const char *cstr = clang_getCString(tstr); if (!strcmp(cstr, ",")) { decl->entries[n].type = strdup(decl->entries[n - 1].type); } else { decl->entries[n].type = concat_name(tokens, 0, im1); } clang_disposeString(tstr); } while (0); memset(&td, 0, sizeof(td)); td.struct_decl_idx = (unsigned) -1; clang_visitChildren(cursor, find_anon_struct, &td); decl->entries[n].struct_decl_idx = td.struct_decl_idx; // FIXME it's not hard to find the struct name (either because // tokens[idx-2-n_ptrs] == 'struct', or because tokens[idx-1-n_ptrs] // is a typedef for the struct name), and then we can use // find_struct_decl() to find the StructDeclaration belonging to // that type. clang_disposeTokens(TU, tokens, n_tokens); break; } case CXCursor_StructDecl: register_struct(str, cursor, NULL, 0); break; case CXCursor_UnionDecl: register_struct(str, cursor, NULL, 1); break; case CXCursor_EnumDecl: register_enum(str, cursor, NULL); break; default: break; } clang_disposeString(cstr); return CXChildVisit_Continue; } static void register_struct(const char *str, CXCursor cursor, TypedefDeclaration *decl_ptr, int is_union) { unsigned n; StructDeclaration *decl; for (n = 0; n < n_structs; n++) { if ((str[0] != 0 && !strcmp(structs[n].name, str)) || !memcmp(&cursor, &structs[n].cursor, sizeof(cursor))) { /* already exists */ if (decl_ptr) decl_ptr->struct_decl_idx = n; if (structs[n].n_entries == 0) { // Fill in structs that were defined (empty) earlier, i.e. // 'struct AVFilterPad;', followed by the full declaration // 'struct AVFilterPad { ... };' clang_visitChildren(cursor, fill_struct_members, (void *) n); } return; } } if (n_structs == n_allocated_structs) { unsigned num = n_allocated_structs + 16; void *mem = realloc(structs, sizeof(*structs) * num); if (!mem) { fprintf(stderr, "Out of memory while registering struct %s\n", str); exit(1); } structs = (StructDeclaration *) mem; n_allocated_structs = num; } if (decl_ptr) decl_ptr->struct_decl_idx = n_structs; decl = &structs[n_structs++]; decl->name = strdup(str); decl->cursor = cursor; decl->n_entries = 0; decl->n_allocated_entries = 0; decl->entries = NULL; decl->is_union = is_union; clang_visitChildren(cursor, fill_struct_members, (void *) (n_structs - 1)); } static int arithmetic_expression(int val1, const char *expr, int val2) { assert(expr[1] == 0 || expr[2] == 0); if (expr[1] == 0) { switch (expr[0]) { case '^': return val1 ^ val2; case '|': return val1 | val2; case '&': return val1 & val2; case '+': return val1 + val2; case '-': return val1 - val2; case '*': return val1 * val2; case '/': return val1 / val2; case '%': return val1 % val2; default: fprintf(stderr, "Arithmetic expression '%c' not handled\n", expr[0]); exit(1); } } else { #define TWOCHARCODE(a, b) ((a << 8) | b) #define TWOCHARTAG(expr) (TWOCHARCODE(expr[0], expr[1])) switch (TWOCHARTAG(expr)) { case TWOCHARCODE('<', '='): return val1 <= val2; case TWOCHARCODE('>', '='): return val1 >= val2; case TWOCHARCODE('!', '='): return val1 != val2; case TWOCHARCODE('=', '='): return val1 == val2; case TWOCHARCODE('<', '<'): return val1 << val2; case TWOCHARCODE('>', '>'): return val1 >> val2; default: fprintf(stderr, "Arithmetic expression '%s' not handled\n", expr); exit(1); } } fprintf(stderr, "Unknown arithmetic expression %s\n", expr); exit(1); } static int find_enum_value(const char *str) { unsigned n, m; for (n = 0; n < n_enums; n++) { for (m = 0; m < enums[n].n_entries; m++) { if (!strcmp(enums[n].entries[m].name, str)) return enums[n].entries[m].value; } } fprintf(stderr, "Unknown enum value %s\n", str); exit(1); } typedef struct FillEnumMemberCache { int n[3]; char *op; } FillEnumMemberCache; static enum CXChildVisitResult fill_enum_value(CXCursor cursor, CXCursor parent, CXClientData client_data) { FillEnumMemberCache *cache = (FillEnumMemberCache *) client_data; CXToken *tokens = 0; unsigned int n_tokens = 0; CXSourceRange range = clang_getCursorExtent(cursor); clang_tokenize(TU, range, &tokens, &n_tokens); if (parent.kind == CXCursor_BinaryOperator && cache->n[0] == 0) { CXString str = clang_getTokenSpelling(TU, tokens[n_tokens - 1]); cache->op = strdup(clang_getCString(str)); clang_disposeString(str); } switch (cursor.kind) { case CXCursor_UnaryOperator: { CXString tsp = clang_getTokenSpelling(TU, tokens[0]); const char *str = clang_getCString(tsp); clang_visitChildren(cursor, fill_enum_value, client_data); assert(str[1] == 0 && (str[0] == '+' || str[0] == '-' || str[0] == '~')); assert(cache->n[0] == 1); if (str[0] == '-') { cache->n[1] = -cache->n[1]; } else if (str[0] == '~') { cache->n[1] = ~cache->n[1]; } clang_disposeString(tsp); break; } case CXCursor_BinaryOperator: { FillEnumMemberCache cache2; memset(&cache2, 0, sizeof(cache2)); assert(n_tokens >= 4); clang_visitChildren(cursor, fill_enum_value, &cache2); assert(cache2.n[0] == 2); assert(cache2.op != NULL); cache->n[++cache->n[0]] = arithmetic_expression(cache2.n[1], cache2.op, cache2.n[2]); free(cache2.op); break; } case CXCursor_IntegerLiteral: { CXString tsp; const char *str; char *end; assert(n_tokens == 2); tsp = clang_getTokenSpelling(TU, tokens[0]); str = clang_getCString(tsp); cache->n[++cache->n[0]] = strtol(str, &end, 0); assert(end - str == strlen(str)); clang_disposeString(tsp); break; } case CXCursor_DeclRefExpr: { CXString tsp; assert(n_tokens == 2); tsp = clang_getTokenSpelling(TU, tokens[0]); cache->n[++cache->n[0]] = find_enum_value(clang_getCString(tsp)); clang_disposeString(tsp); break; } case CXCursor_CharacterLiteral: { CXString spelling; const char *str; assert(n_tokens == 2); spelling = clang_getTokenSpelling(TU, tokens[0]); str = clang_getCString(spelling); assert(strlen(str) == 3 && str[0] == '\'' && str[2] == '\''); cache->n[++cache->n[0]] = str[1]; clang_disposeString(spelling); break; } case CXCursor_ParenExpr: clang_visitChildren(cursor, fill_enum_value, client_data); break; default: break; } clang_disposeTokens(TU, tokens, n_tokens); return CXChildVisit_Continue; } static enum CXChildVisitResult fill_enum_members(CXCursor cursor, CXCursor parent, CXClientData client_data) { EnumDeclaration *decl = (EnumDeclaration *) client_data; if (cursor.kind == CXCursor_EnumConstantDecl) { CXString cstr = clang_getCursorSpelling(cursor); const char *str = clang_getCString(cstr); unsigned n = decl->n_entries; FillEnumMemberCache cache; memset(&cache, 0, sizeof(cache)); if (decl->n_entries == decl->n_allocated_entries) { unsigned num = decl->n_allocated_entries + 16; void *mem = realloc(decl->entries, sizeof(*decl->entries) * num); if (!mem) { fprintf(stderr, "Ran out of memory while declaring field %s in %s\n", str, decl->name); exit(1); } decl->entries = (EnumMember *) mem; decl->n_allocated_entries = num; } decl->entries[n].name = strdup(str); decl->entries[n].cursor = cursor; clang_visitChildren(cursor, fill_enum_value, &cache); assert(cache.n[0] <= 1); if (cache.n[0] == 1) { decl->entries[n].value = cache.n[1]; } else if (n == 0) { decl->entries[n].value = 0; } else { decl->entries[n].value = decl->entries[n - 1].value + 1; } decl->n_entries++; clang_disposeString(cstr); } return CXChildVisit_Continue; } static void register_enum(const char *str, CXCursor cursor, TypedefDeclaration *decl_ptr) { unsigned n; EnumDeclaration *decl; for (n = 0; n < n_enums; n++) { if ((str[0] != 0 && !strcmp(enums[n].name, str)) || !memcmp(&cursor, &enums[n].cursor, sizeof(cursor))) { /* already exists */ if (decl_ptr) decl_ptr->enum_decl_idx = n; return; } } if (n_enums == n_allocated_enums) { unsigned num = n_allocated_enums + 16; void *mem = realloc(enums, sizeof(*enums) * num); if (!mem) { fprintf(stderr, "Out of memory while registering enum %s\n", str); exit(1); } enums = (EnumDeclaration *) mem; n_allocated_enums = num; } if (decl_ptr) decl_ptr->enum_decl_idx = n_enums; decl = &enums[n_enums++]; decl->name = strdup(str); decl->cursor = cursor; decl->n_entries = 0; decl->n_allocated_entries = 0; decl->entries = NULL; clang_visitChildren(cursor, fill_enum_members, decl); } static void register_typedef(const char *name, CXToken *tokens, unsigned n_tokens, TypedefDeclaration *decl, CXCursor cursor) { unsigned n; if (n_typedefs == n_allocated_typedefs) { unsigned num = n_allocated_typedefs + 16; void *mem = realloc(typedefs, sizeof(*typedefs) * num); if (!mem) { fprintf(stderr, "Ran out of memory while declaring typedef %s\n", name); exit(1); } n_allocated_typedefs = num; typedefs = (TypedefDeclaration *) mem; } n = n_typedefs++; typedefs[n].name = strdup(name); if (decl->struct_decl_idx != (unsigned) -1) { typedefs[n].struct_decl_idx = decl->struct_decl_idx; typedefs[n].proxy = NULL; typedefs[n].enum_decl_idx = (unsigned) -1; } else if (decl->enum_decl_idx != (unsigned) -1) { typedefs[n].enum_decl_idx = decl->enum_decl_idx; typedefs[n].struct_decl_idx = (unsigned) -1; typedefs[n].proxy = NULL; } else { typedefs[n].enum_decl_idx = (unsigned) -1; typedefs[n].struct_decl_idx = (unsigned) -1; typedefs[n].proxy = concat_name(tokens, 1, n_tokens - 3); } memcpy(&typedefs[n].cursor, &cursor, sizeof(cursor)); } static unsigned get_token_offset(CXToken token) { CXSourceLocation l = clang_getTokenLocation(TU, token); CXFile file; unsigned line, col, off; clang_getSpellingLocation(l, &file, &line, &col, &off); return off; } static unsigned find_struct_decl_idx_by_name(const char *name) { unsigned n; for (n = 0; n < n_structs; n++) { if (!strcmp(name, structs[n].name)) return n; } return (unsigned) -1; } static void resolve_proxy(TypedefDeclaration *decl) { if (decl->struct_decl_idx != (unsigned) -1 || decl->enum_decl_idx != (unsigned) -1) return; decl->struct_decl_idx = find_struct_decl_idx_for_type_name(decl->proxy); // we could theoretically also resolve the enum, but we wouldn't use // that information, so let's just not } static TypedefDeclaration *find_typedef_decl_by_name(const char *name) { unsigned n; for (n = 0; n < n_typedefs; n++) { if (!strcmp(name, typedefs[n].name)) { resolve_proxy(&typedefs[n]); return &typedefs[n]; } } return NULL; } // FIXME this function has some duplicate functionality compared to // fill_struct_members() further up. static unsigned find_struct_decl_idx(const char *var, CXToken *tokens, unsigned n_tokens, unsigned *depth) { /* * In the list of tokens that make up a sequence like: * 'static const struct str_type name = { val }', * A) find the token that contains 'var', get the type (token before that) * B) check the tokens before that one to see if type is a struct * C) if not, check if the type is a typedef and go back to (B) * D) if type is a struct, return that type's StructDeclaration; * if type is not a struct and not a typedef, return NULL. */ unsigned n, var_tok_idx; *depth = 0; for (n = 0; n < n_tokens; n++) { CXString spelling = clang_getTokenSpelling(TU, tokens[n]); int res = strcmp(clang_getCString(spelling), var); clang_disposeString(spelling); if (!res) break; } if (n == n_tokens) return (unsigned) -1; var_tok_idx = n; for (n = var_tok_idx + 1; n < n_tokens; n++) { CXString spelling = clang_getTokenSpelling(TU, tokens[n]); int res = strcmp(clang_getCString(spelling), "="); if (!strcmp(clang_getCString(spelling), "[")) (*depth)++; clang_disposeString(spelling); if (!res) break; } // is it a struct? if (var_tok_idx > 1) { CXString spelling; int res; spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 2]); res = strcmp(clang_getCString(spelling), "struct"); clang_disposeString(spelling); if (!res) { unsigned str_decl; spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 1]); str_decl = find_struct_decl_idx_by_name(clang_getCString(spelling)); clang_disposeString(spelling); return str_decl; } } // is it a typedef? if (var_tok_idx > 0) { CXString spelling; TypedefDeclaration *td_decl; spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 1]); td_decl = find_typedef_decl_by_name(clang_getCString(spelling)); clang_disposeString(spelling); if (td_decl && td_decl->struct_decl_idx != (unsigned) -1) return td_decl->struct_decl_idx; } return (unsigned) -1; } static unsigned find_member_index_in_struct(StructDeclaration *str_decl, const char *member) { unsigned n; for (n = 0; n < str_decl->n_entries; n++) { if (!strcmp(str_decl->entries[n].name, member)) return n; } return -1; } static unsigned find_struct_decl_idx_for_type_name(const char *name) { if (!strncmp(name, "const ", 6)) name += 6; if (!strncmp(name, "struct ", 7)) { return find_struct_decl_idx_by_name(name + 7); } else if (!strncmp(name, "union ", 6)) { return find_struct_decl_idx_by_name(name + 6); } else { TypedefDeclaration *decl = find_typedef_decl_by_name(name); return decl ? decl->struct_decl_idx : (unsigned) -1; } } /* * Structure to keep track of compound literals that we eventually want * to replace with something else. */ enum CLType { TYPE_UNKNOWN = 0, TYPE_OMIT_CAST, // AVRational x = (AVRational) { y, z } // -> AVRational x = { y, z } TYPE_TEMP_ASSIGN, // AVRational x; [..] x = (AVRational) { y, z } // -> [..] { AVRational tmp = { y, z }; x = tmp; } // can also be used for return TYPE_CONST_DECL, // anything with a const that can be statically // declared, e.g. x = ((const int[]){ y, z })[0] -> // static const int tmp[] = { y, z } [..] x = tmp[0] TYPE_NEW_CONTEXT, // func(); int x; [..] -> func(); { int x; [..] } TYPE_LOOP_CONTEXT, // for(int i = 0; ... -> { int i = 0; for (; ... } }; typedef struct { enum CLType type; struct { unsigned start, end; // to get the values } value_token, cast_token, context; unsigned cast_token_array_start; unsigned struct_decl_idx; // struct type union { struct { char *tmp_var_name; // temporary variable name for the constant // data, assigned in the first stage (var // declaration), and used in the second stage // (replacement of the CL with the var ref) } t_c_d; } data; } CompoundLiteralList; static CompoundLiteralList *comp_literal_lists = NULL; static unsigned n_comp_literal_lists = 0; static unsigned n_allocated_comp_literal_lists = 0; /* * Helper struct for traversing the tree. This allows us to keep state * beyond the current and parent node. */ typedef struct CursorRecursion CursorRecursion; struct CursorRecursion { enum CXCursorKind kind; CursorRecursion *parent; unsigned child_cntr; unsigned allow_var_decls; CXToken *tokens; unsigned n_tokens; union { void *opaque; unsigned sal_idx; // InitListExpr and UnexposedExpr // after an InitListExpr struct { unsigned struct_decl_idx; unsigned array_depth; } var_decl_data; // VarDecl TypedefDeclaration *td_decl; // TypedefDecl unsigned cl_idx; // CompoundLiteralExpr } data; int is_function; int end_scopes; }; static unsigned find_encompassing_struct_decl(unsigned start, unsigned end, StructArrayList **ptr, CursorRecursion *rec, unsigned *depth) { /* * In previously registered arrays/structs, find one with a start-end * that fully contains the given start/end function arguments. If found, * return that array/struct's type. If not found, return NULL. */ unsigned n; *depth = 0; *ptr = NULL; for (n = n_struct_array_lists - 1; n != (unsigned) -1; n--) { if (start >= struct_array_lists[n].value_offset.start && end <= struct_array_lists[n].value_offset.end && !(start == struct_array_lists[n].value_offset.start && end == struct_array_lists[n].value_offset.end)) { if (struct_array_lists[n].type == TYPE_ARRAY) { /* { <- parent * [..] = { .. }, <- us * } */ assert((rec->parent->kind == CXCursor_UnexposedExpr && rec->parent->parent->kind == CXCursor_InitListExpr) || rec->parent->kind == CXCursor_InitListExpr); *ptr = &struct_array_lists[n]; assert(struct_array_lists[n].array_depth > 0); *depth = struct_array_lists[n].array_depth - 1; return struct_array_lists[n].struct_decl_idx; } else if (struct_array_lists[n].type == TYPE_STRUCT) { /* { <- parent * .member = { .. }, <- us * } */ unsigned m; StructArrayList *l = *ptr = &struct_array_lists[n]; assert((rec->parent->kind == CXCursor_UnexposedExpr && rec->parent->parent->kind == CXCursor_InitListExpr) || rec->parent->kind == CXCursor_InitListExpr); assert(l->array_depth == 0); for (m = 0; m <= l->n_entries; m++) { if (start >= l->entries[m].expression_offset.start && end <= l->entries[m].expression_offset.end) { unsigned s_idx = l->struct_decl_idx; unsigned m_idx = l->entries[m].index; *depth = structs[s_idx].entries[m_idx].array_depth; return structs[s_idx].entries[m_idx].struct_decl_idx; } } // Can this ever trigger? return (unsigned) -1; } else if (rec->parent->kind == CXCursor_InitListExpr) { /* { <- parent * { .. }, <- us (so now the question is: array or struct?) * } */ StructArrayList *l = *ptr = &struct_array_lists[n]; unsigned s_idx = l->struct_decl_idx; unsigned m_idx = rec->parent->child_cntr - 1; assert(rec->parent->kind == CXCursor_InitListExpr); if (l->array_depth > 0) { *depth = l->array_depth - 1; return l->struct_decl_idx; } else if (s_idx != (unsigned) -1) { assert(m_idx < structs[s_idx].n_entries); *depth = structs[s_idx].entries[m_idx].array_depth; return structs[s_idx].entries[m_idx].struct_decl_idx; } else { return (unsigned) -1; } } else { // Can this ever trigger? return (unsigned) -1; } } } return (unsigned) -1; } static int is_const(CompoundLiteralList *l, CursorRecursion *rec) { unsigned n; for (n = 0; n < rec->n_tokens - 1; n++) { unsigned off = get_token_offset(rec->tokens[n]); if (off > l->cast_token.start && off < l->cast_token.end) { CXString spelling = clang_getTokenSpelling(TU, rec->tokens[n]); int res = strcmp(clang_getCString(spelling), "const"); clang_disposeString(spelling); if (!res) return 1; } else if (off >= l->cast_token.end) break; } return 0; } static CursorRecursion *find_function_or_top(CursorRecursion *rec) { CursorRecursion *p; for (p = rec; p->parent->kind != CXCursor_FunctionDecl && p->parent->kind != CXCursor_TranslationUnit; p = p->parent) ; return p; } static CursorRecursion *find_var_decl_context(CursorRecursion *rec) { CursorRecursion *p; /* Find a recursion level in which we can declare a new context, * i.e. a "{" or a "do {", within which we can declare new variables * in a c89-compatible way. At the end of the returned recursion * level's token range, we'll add a "}" or a "} while (0);". */ for (p = rec; p != NULL; p = p->parent) { switch (p->kind) { case CXCursor_VarDecl: case CXCursor_ReturnStmt: case CXCursor_CompoundStmt: case CXCursor_IfStmt: case CXCursor_SwitchStmt: return p; case CXCursor_CallExpr: case CXCursor_CompoundAssignOperator: case CXCursor_BinaryOperator: // FIXME: do/while/for if ((p->parent->kind == CXCursor_IfStmt && p->parent->child_cntr > 1) || (p->parent->kind == CXCursor_CaseStmt && p->parent->child_cntr > 1) || p->parent->kind == CXCursor_CompoundStmt || p->parent->kind == CXCursor_DefaultStmt) { return p; } break; default: break; } } return NULL; } static void analyze_compound_literal_lineage(CompoundLiteralList *l, CursorRecursion *rec) { CursorRecursion *p = rec, *p2; #define DEBUG 0 dprintf("CL lineage: "); do { dprintf("%d[%d], ", p->kind, p->child_cntr); } while ((p = p->parent)); dprintf("\n"); #define DEBUG 0 p = rec->parent->parent; p2 = find_function_or_top(rec); if (p2->parent->kind != CXCursor_FunctionDecl) { l->context.start = get_token_offset(p2->tokens[0]); l->type = TYPE_CONST_DECL; return; } if (p->kind == CXCursor_VarDecl) { l->type = TYPE_OMIT_CAST; l->context.start = l->cast_token.start; } else if ((p = find_var_decl_context(p))) { l->type = TYPE_TEMP_ASSIGN; l->context.start = get_token_offset(p->tokens[0]); if (p->kind == CXCursor_VarDecl) { /* if the parent is a VarDecl, the context.end should be the end * of the whole context in which that variable exists, not just * the end of the context of this particular statement. */ p = p->parent; assert(p->kind == CXCursor_DeclStmt); p = p->parent; } l->context.end = get_token_offset(p->tokens[p->n_tokens - 1]); } } static void analyze_decl_context(CompoundLiteralList *l, CursorRecursion *rec) { CursorRecursion *p = rec->parent; // FIXME if parent.kind == CXCursor_CompoundStmt, simply go from here until // the end of that compound context. // in other cases (e.g. declaration inside a for/while), find the complete // context (e.g. before the while/for) and declare new context around that // whole thing if (p->kind == CXCursor_CompoundStmt) { l->type = TYPE_NEW_CONTEXT; l->context.start = get_token_offset(rec->tokens[0]); l->cast_token.start = get_token_offset(rec->tokens[0]); l->context.end = get_token_offset(p->tokens[p->n_tokens - 1]); } else if (p->kind == CXCursor_ForStmt && rec->parent->child_cntr == 1) { l->type = TYPE_LOOP_CONTEXT; l->context.start = get_token_offset(p->tokens[0]); l->context.end = get_token_offset(p->tokens[p->n_tokens - 1]); l->cast_token.start = get_token_offset(rec->tokens[0]); l->cast_token.end = get_token_offset(rec->tokens[rec->n_tokens - 2]); } } static void get_comp_literal_type_info(StructArrayList *sal, CompoundLiteralList *cl, CXToken *tokens, unsigned n_tokens, unsigned start, unsigned end) { // FIXME also see find_struct_decl_idx() unsigned type_tok_idx = (unsigned) -1, array_tok_idx = (unsigned) -1, end_tok_idx = (unsigned) -1, n; char *type; for (n = 0; n < n_tokens; n++) { unsigned off = get_token_offset(tokens[n]); if (off == cl->cast_token.start) { type_tok_idx = n + 1; } else if (off == cl->cast_token.end) { end_tok_idx = n; } if (off == cl->cast_token_array_start) { array_tok_idx = n; } } assert(array_tok_idx != (unsigned) -1 && end_tok_idx != (unsigned) -1 && type_tok_idx != (unsigned) -1); sal->array_depth = 0; for (n = array_tok_idx; n < end_tok_idx; n++) { CXString spelling = clang_getTokenSpelling(TU, tokens[n]); int res = strcmp(clang_getCString(spelling), "["); clang_disposeString(spelling); if (!res) sal->array_depth++; } type = concat_name(tokens, type_tok_idx, array_tok_idx - 1); sal->struct_decl_idx = find_struct_decl_idx_for_type_name(type); free(type); sal->level = 0; for (n = n_struct_array_lists - 1; n != (unsigned) -1; n--) { if (start >= struct_array_lists[n].value_offset.start && end <= struct_array_lists[n].value_offset.end && !(start == struct_array_lists[n].value_offset.start && end == struct_array_lists[n].value_offset.end)) { sal->level = struct_array_lists[n].level + 1; return; } } } static unsigned get_n_tokens(CXToken *tokens, unsigned n_tokens) { /* clang will set n_tokens to the number including the start of the * next statement, regardless of whether that is part of the next * statement or not. We actually care, since in some cases (if it's * a ";"), we want to close contexts after it, whereas in other * cases (if it's the start of the next statement, e.g. "static void * function1(..) { .. } static void function2(..) { }", we want to * close context before the last token (which in the first case is * ";", but in the second case is "static"). */ int res; if (n_tokens > 0) { CXString spelling = clang_getTokenSpelling(TU, tokens[n_tokens - 1]); res = strcmp(clang_getCString(spelling), ";"); clang_disposeString(spelling); } else { res = 1; } return n_tokens - !!res; } static char *find_variable_name(CursorRecursion *rec) { unsigned n; // typename varname = { ... // typename can be a typedef or "union something" for (n = 1; n < rec->n_tokens; n++) { CXString spelling = clang_getTokenSpelling(TU, rec->tokens[n]); if (!strcmp(clang_getCString(spelling), "=")) { char *name; clang_disposeString(spelling); spelling = clang_getTokenSpelling(TU, rec->tokens[n - 1]); name = strdup(clang_getCString(spelling)); clang_disposeString(spelling); return name; } clang_disposeString(spelling); } fprintf(stderr, "Unable to find variable name in assignment\n"); abort(); } static int index_is_unique(StructArrayList *l, int idx) { int n; for (n = 0; n < l->n_entries; n++) { if (l->entries[n].index == idx) return 0; } return 1; } static enum CXChildVisitResult callback(CXCursor cursor, CXCursor parent, CXClientData client_data) { enum CXChildVisitResult res = CXChildVisit_Recurse; CXString str; CXSourceRange range; CXToken *tokens = 0; unsigned n_tokens = 0; CXSourceLocation pos; CXFile file; unsigned line, col, off, i; CXString filename; CursorRecursion rec, *rec_ptr; int is_union, is_in_function = 0; range = clang_getCursorExtent(cursor); pos = clang_getCursorLocation(cursor); str = clang_getCursorSpelling(cursor); clang_tokenize(TU, range, &tokens, &n_tokens); clang_getSpellingLocation(pos, &file, &line, &col, &off); filename = clang_getFileName(file); memset(&rec, 0, sizeof(rec)); rec.kind = cursor.kind; rec.allow_var_decls = 0; rec.parent = (CursorRecursion *) client_data; rec.parent->child_cntr++; rec.tokens = tokens; rec.n_tokens = get_n_tokens(tokens, n_tokens); if (cursor.kind == CXCursor_FunctionDecl) rec.is_function = 1; if (parent.kind == CXCursor_CompoundStmt) rec.parent->allow_var_decls &= cursor.kind == CXCursor_DeclStmt; rec_ptr = (CursorRecursion *) client_data; while (rec_ptr) { if (rec_ptr->is_function) { is_in_function = 1; break; } rec_ptr = rec_ptr->parent; } #define DEBUG 0 dprintf("DERP: %d [%d:%d] %s @ %d:%d in %s\n", cursor.kind, parent.kind, rec.parent->child_cntr, clang_getCString(str), line, col, clang_getCString(filename)); for (i = 0; i < n_tokens; i++) { CXString spelling = clang_getTokenSpelling(TU, tokens[i]); CXSourceLocation l = clang_getTokenLocation(TU, tokens[i]); clang_getSpellingLocation(l, &file, &line, &col, &off); dprintf("token = '%s' @ %d:%d\n", clang_getCString(spelling), line, col); clang_disposeString(spelling); } #define DEBUG 0 switch (cursor.kind) { case CXCursor_TypedefDecl: { TypedefDeclaration decl; memset(&decl, 0, sizeof(decl)); decl.struct_decl_idx = (unsigned) -1; decl.enum_decl_idx = (unsigned) -1; rec.data.td_decl = &decl; clang_visitChildren(cursor, callback, &rec); register_typedef(clang_getCString(str), tokens, n_tokens, &decl, cursor); break; } case CXCursor_StructDecl: case CXCursor_UnionDecl: is_union = cursor.kind == CXCursor_UnionDecl; if (parent.kind == CXCursor_TypedefDecl) { register_struct(clang_getCString(str), cursor, rec.parent->data.td_decl, is_union); } else if (parent.kind == CXCursor_VarDecl) { TypedefDeclaration td; memset(&td, 0, sizeof(td)); td.struct_decl_idx = (unsigned) -1; register_struct(clang_getCString(str), cursor, &td, is_union); rec.parent->data.var_decl_data.struct_decl_idx = td.struct_decl_idx; } else { register_struct(clang_getCString(str), cursor, NULL, is_union); } break; case CXCursor_EnumDecl: register_enum(clang_getCString(str), cursor, parent.kind == CXCursor_TypedefDecl ? rec.parent->data.td_decl : NULL); break; case CXCursor_TypeRef: { if (parent.kind == CXCursor_VarDecl && rec.parent->data.var_decl_data.struct_decl_idx == (unsigned) -1) { const char *cstr = clang_getCString(str); unsigned idx = find_struct_decl_idx_for_type_name(cstr); rec.parent->data.var_decl_data.struct_decl_idx = idx; } break; } case CXCursor_DeclStmt: if (parent.kind != CXCursor_CompoundStmt || !rec.parent->allow_var_decls) { // e.g. void function() { int x; function(); int y; ... } // ^^^^^^ CompoundLiteralList *l; if (n_comp_literal_lists == n_allocated_comp_literal_lists) { unsigned num = n_allocated_comp_literal_lists + 16; void *mem = realloc(comp_literal_lists, sizeof(*comp_literal_lists) * num); if (!mem) { fprintf(stderr, "Failed to allocate memory for complitlist\n"); exit(1); } comp_literal_lists = (CompoundLiteralList *) mem; n_allocated_comp_literal_lists = num; } l = &comp_literal_lists[n_comp_literal_lists++]; memset(l, 0, sizeof(*l)); clang_visitChildren(cursor, callback, &rec); analyze_decl_context(l, &rec); } else { clang_visitChildren(cursor, callback, &rec); } break; case CXCursor_VarDecl: { // e.g. static const struct <type> name { val } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsigned idx = find_struct_decl_idx(clang_getCString(str), tokens, n_tokens, &rec.data.var_decl_data.array_depth); rec.data.var_decl_data.struct_decl_idx = idx; clang_visitChildren(cursor, callback, &rec); break; } case CXCursor_CompoundLiteralExpr: { CompoundLiteralList *l; if (n_comp_literal_lists == n_allocated_comp_literal_lists) { unsigned num = n_allocated_comp_literal_lists + 16; void *mem = realloc(comp_literal_lists, sizeof(*comp_literal_lists) * num); if (!mem) { fprintf(stderr, "Failed to allocate memory for complitlist\n"); exit(1); } comp_literal_lists = (CompoundLiteralList *) mem; n_allocated_comp_literal_lists = num; } l = &comp_literal_lists[n_comp_literal_lists++]; memset(l, 0, sizeof(*l)); rec.data.cl_idx = n_comp_literal_lists - 1; l->cast_token.start = get_token_offset(tokens[0]); l->struct_decl_idx = (unsigned) -1; clang_visitChildren(cursor, callback, &rec); analyze_compound_literal_lineage(l, &rec); break; } case CXCursor_InitListExpr: if (parent.kind == CXCursor_CompoundLiteralExpr) { CompoundLiteralList *l = &comp_literal_lists[rec.parent->data.cl_idx]; // (type) { val } // ^^^^^^^ l->value_token.start = get_token_offset(tokens[0]); l->value_token.end = get_token_offset(tokens[n_tokens - 2]); if (!l->cast_token.end) { for (i = 0; i < rec.parent->n_tokens - 1; i++) { CXString spelling = clang_getTokenSpelling(TU, rec.parent->tokens[i]); unsigned off = get_token_offset(rec.parent->tokens[i]); int res = strcmp(clang_getCString(spelling), "["); clang_disposeString(spelling); if (!res) l->cast_token_array_start = off; if (off == l->value_token.start) break; else l->cast_token.end = off; } if (!l->cast_token_array_start) l->cast_token_array_start = l->cast_token.end; } } { // another { val } or { .member = val } or { [index] = val } StructArrayList *l; unsigned parent_idx = (unsigned) -1; if (n_struct_array_lists == n_allocated_struct_array_lists) { unsigned num = n_allocated_struct_array_lists + 16; void *mem = realloc(struct_array_lists, sizeof(*struct_array_lists) * num); if (!mem) { fprintf(stderr, "Failed to allocate memory for str/arr\n"); exit(1); } struct_array_lists = (StructArrayList *) mem; n_allocated_struct_array_lists = num; } l = &struct_array_lists[n_struct_array_lists++]; l->type = TYPE_IRRELEVANT; l->n_entries = l->n_allocated_entries = 0; l->entries = NULL; l->name = NULL; l->convert_to_assignment = 0; l->value_offset.start = get_token_offset(tokens[0]); l->value_offset.end = get_token_offset(tokens[n_tokens - 2]); if (rec.parent->kind == CXCursor_VarDecl) { l->struct_decl_idx = rec.parent->data.var_decl_data.struct_decl_idx; l->array_depth = rec.parent->data.var_decl_data.array_depth; l->level = 0; } else if (rec.parent->kind == CXCursor_CompoundLiteralExpr) { CompoundLiteralList *cl = &comp_literal_lists[rec.parent->data.cl_idx]; get_comp_literal_type_info(l, cl, rec.parent->tokens, rec.parent->n_tokens, l->value_offset.start, l->value_offset.end); } else { StructArrayList *parent; unsigned depth; unsigned idx = find_encompassing_struct_decl(l->value_offset.start, l->value_offset.end, &parent, &rec, &depth); l->level = parent ? parent->level + 1 : 0; l->struct_decl_idx = idx; l->array_depth = depth; // If the parent is an InitListExpr also, we increment the // parent l->n_entries to keep track of the number (and thus // in case of a struct: the type) of each child node. // // E.g. { var, { var2, var3 }, var4 } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <- parent // ^^^^^^^^^^^^^^ <- cursor if (rec.parent->kind == CXCursor_InitListExpr && parent) { unsigned s = l->value_offset.start; unsigned e = l->value_offset.end; StructArrayItem *sai; if (parent->n_entries == parent->n_allocated_entries) { unsigned num = parent->n_allocated_entries + 16; void *mem = realloc(parent->entries, sizeof(*parent->entries) * num); if (!mem) { fprintf(stderr, "Failed to allocate str/arr entry mem\n"); exit(1); } parent->entries = (StructArrayItem *) mem; parent->n_allocated_entries = num; } sai = &parent->entries[parent->n_entries]; sai->value_offset.start = s; sai->value_offset.end = e; sai->expression_offset.start = s; sai->expression_offset.end = e; sai->index = parent->n_entries > 0 ? parent->entries[parent->n_entries - 1].index + 1 : rec.parent->child_cntr - 1; parent_idx = parent - struct_array_lists; } } rec.data.sal_idx = n_struct_array_lists - 1; clang_visitChildren(cursor, callback, &rec); if (rec.parent->kind == CXCursor_InitListExpr && parent_idx != (unsigned) -1) { struct_array_lists[parent_idx].n_entries++; } l = &struct_array_lists[rec.data.sal_idx]; if (l->convert_to_assignment && rec.parent->kind == CXCursor_VarDecl) { l->value_offset.start -= 2; // Swallow the assignment character l->value_offset.end += 1; // Swallow the final semicolon free(l->name); l->name = find_variable_name(rec.parent); rec_ptr = (CursorRecursion *) client_data; while (rec_ptr->kind != CXCursor_CompoundStmt) rec_ptr = rec_ptr->parent; if (rec_ptr->kind != CXCursor_CompoundStmt) { fprintf(stderr, "Unable to find enclosing compound statement\n"); exit(1); } rec_ptr->end_scopes++; } else l->convert_to_assignment = 0; } break; case CXCursor_UnexposedExpr: if (parent.kind == CXCursor_InitListExpr) { CXString spelling = clang_getTokenSpelling(TU, tokens[0]); CXString spelling2 = clang_getTokenSpelling(TU, tokens[1]); const char *istr = clang_getCString(spelling); const char *istr2 = clang_getCString(spelling2); StructArrayList *l = &struct_array_lists[rec.parent->data.sal_idx]; StructArrayItem *sai; if (!strcmp(istr, "[") || !strcmp(istr, ".") || !strcmp(istr2, ":")) { enum StructArrayType exp_type = (istr[0] == '.' || istr2[0] == ':') ? TYPE_STRUCT : TYPE_ARRAY; // [index] = val or .member = val or member: val // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^ if (l->type == TYPE_IRRELEVANT) { l->type = exp_type; } else if (l->type != exp_type) { fprintf(stderr, "Mixed struct/array!\n"); exit(1); } } if (l->n_entries == l->n_allocated_entries) { unsigned num = l->n_allocated_entries + 16; void *mem = realloc(l->entries, sizeof(*l->entries) * num); if (!mem) { fprintf(stderr, "Failed to allocate str/arr entry mem\n"); exit(1); } l->entries = (StructArrayItem *) mem; l->n_allocated_entries = num; } sai = &l->entries[l->n_entries]; sai->index = l->n_entries ? l->entries[l->n_entries - 1].index + 1 : 0; sai->expression_offset.start = get_token_offset(tokens[0]); sai->expression_offset.end = get_token_offset(tokens[n_tokens - 2]); if (!strcmp(istr, ".")) { sai->value_offset.start = get_token_offset(tokens[3]); } else if (!strcmp(istr2, ":")) { sai->value_offset.start = get_token_offset(tokens[2]); } else if (!strcmp(istr, "[")) { unsigned n; for (n = 2; n < n_tokens - 2; n++) { CXString spelling = clang_getTokenSpelling(TU, tokens[n]); int res = strcmp(clang_getCString(spelling), "]"); clang_disposeString(spelling); if (!res) break; } assert(n < n_tokens - 2); sai->value_offset.start = get_token_offset(tokens[n + 2]); } else { sai->value_offset.start = get_token_offset(tokens[0]); } sai->value_offset.end = get_token_offset(tokens[n_tokens - 2]); rec.data.sal_idx = rec.parent->data.sal_idx; clang_visitChildren(cursor, callback, &rec); assert(index_is_unique(&struct_array_lists[rec.parent->data.sal_idx], sai->index)); struct_array_lists[rec.parent->data.sal_idx].n_entries++; clang_disposeString(spelling); clang_disposeString(spelling2); } else { clang_visitChildren(cursor, callback, &rec); } break; case CXCursor_MemberRef: if (parent.kind == CXCursor_UnexposedExpr && rec.parent->parent->kind == CXCursor_InitListExpr) { // designated initializer (struct) // .member = val // ^^^^^^ StructArrayList *l = &struct_array_lists[rec.parent->data.sal_idx]; StructArrayItem *sai = &l->entries[l->n_entries]; const char *member = clang_getCString(str); assert(sai); assert(l->type == TYPE_STRUCT); assert(l->struct_decl_idx != (unsigned) -1); sai->index = find_member_index_in_struct(&structs[l->struct_decl_idx], member); if (structs[l->struct_decl_idx].is_union && is_in_function) l->convert_to_assignment = 1; } break; case CXCursor_CompoundStmt: rec.allow_var_decls = 1; clang_visitChildren(cursor, callback, &rec); if (rec.end_scopes) { EndScope *e; if (n_end_scopes == n_allocated_end_scopes) { unsigned num = n_allocated_end_scopes + 16; void *mem = realloc(end_scopes, sizeof(*end_scopes) * num); if (!mem) { fprintf(stderr, "Failed to allocate memory for str/arr\n"); exit(1); } end_scopes = (EndScope *) mem; n_allocated_end_scopes = num; } e = &end_scopes[n_end_scopes++]; e->end = get_token_offset(tokens[n_tokens - 2]); e->n_scopes = rec.end_scopes; } break; case CXCursor_IntegerLiteral: case CXCursor_DeclRefExpr: case CXCursor_BinaryOperator: if (parent.kind == CXCursor_UnexposedExpr && rec.parent->parent->kind == CXCursor_InitListExpr) { CXString spelling = clang_getTokenSpelling(TU, tokens[n_tokens - 1]); if (!strcmp(clang_getCString(spelling), "]")) { // [index] = { val } // ^^^^^ FillEnumMemberCache cache; StructArrayList *l = &struct_array_lists[rec.parent->data.sal_idx]; StructArrayItem *sai = &l->entries[l->n_entries]; memset(&cache, 0, sizeof(cache)); fill_enum_value(cursor, parent, &cache); assert(cache.n[0] == 1); assert(sai); assert(l->type == TYPE_ARRAY); sai->index = cache.n[1]; } clang_disposeString(spelling); } else if (cursor.kind != CXCursor_BinaryOperator) break; default: clang_visitChildren(cursor, callback, &rec); break; } // default list filler for scalar (non-list) value types if (rec.parent->kind == CXCursor_InitListExpr && cursor.kind != CXCursor_InitListExpr && cursor.kind != CXCursor_UnexposedExpr) { unsigned s = get_token_offset(tokens[0]); StructArrayItem *sai; StructArrayList *parent = &struct_array_lists[rec.parent->data.sal_idx]; if (parent != NULL) { if (parent->n_entries == parent->n_allocated_entries) { unsigned num = parent->n_allocated_entries + 16; void *mem = realloc(parent->entries, sizeof(*parent->entries) * num); if (!mem) { fprintf(stderr, "Failed to allocate str/arr entry mem\n"); exit(1); } parent->entries = (StructArrayItem *) mem; parent->n_allocated_entries = num; } sai = &parent->entries[parent->n_entries]; sai->value_offset.start = s; sai->value_offset.end = s; sai->expression_offset.start = s; sai->expression_offset.end = s; sai->index = parent->n_entries > 0 ? parent->entries[parent->n_entries - 1].index + 1 : rec.parent->child_cntr - 1; assert(index_is_unique(parent, sai->index)); parent->n_entries++; } } clang_disposeString(str); clang_disposeTokens(TU, tokens, n_tokens); clang_disposeString(filename); return CXChildVisit_Continue; } static double eval_expr(CXToken *tokens, unsigned *n, unsigned last); static double eval_prim(CXToken *tokens, unsigned *n, unsigned last) { CXString s; const char *str; if (*n > last) { fprintf(stderr, "Unable to parse an expression primary, no more tokens\n"); exit(1); } s = clang_getTokenSpelling(TU, tokens[*n]); str = clang_getCString(s); if (!strcmp(str, "-")) { (*n)++; clang_disposeString(s); return -eval_prim(tokens, n, last); } else if (!strcmp(str, "(")) { double d; (*n)++; clang_disposeString(s); d = eval_expr(tokens, n, last); if (*n >= last) { fprintf(stderr, "No right parenthesis found\n"); exit(1); } s = clang_getTokenSpelling(TU, tokens[*n]); str = clang_getCString(s); if (!strcmp(str, ")")) { clang_disposeString(s); (*n)++; } else { fprintf(stderr, "No right parenthesis found\n"); exit(1); } return d; } else { char *end; double d = strtod(str, &end); // Handle a possible f suffix for float constants if (end != str && (*end == 'f' || *end == 'F')) end++; if (*end != '\0') { fprintf(stderr, "Unable to parse %s as expression primary\n", str); exit(1); } (*n)++; clang_disposeString(s); return d; } } static double eval_term(CXToken *tokens, unsigned *n, unsigned last) { double left = eval_prim(tokens, n, last); while (*n <= last) { CXString s = clang_getTokenSpelling(TU, tokens[*n]); const char *str = clang_getCString(s); if (!strcmp(str, "*")) { (*n)++; left *= eval_prim(tokens, n, last); } else if (!strcmp(str, "/")) { (*n)++; left /= eval_prim(tokens, n, last); } else { clang_disposeString(s); return left; } clang_disposeString(s); } return left; } static double eval_expr(CXToken *tokens, unsigned *n, unsigned last) { double left = eval_term(tokens, n, last); while (*n <= last) { CXString s = clang_getTokenSpelling(TU, tokens[*n]); const char *str = clang_getCString(s); if (!strcmp(str, "-")) { (*n)++; left -= eval_term(tokens, n, last); } else if (!strcmp(str, "+")) { (*n)++; left += eval_term(tokens, n, last); } else { clang_disposeString(s); return left; } clang_disposeString(s); } return left; } static double eval_tokens(CXToken *tokens, unsigned first, unsigned last) { unsigned n = first; double d = eval_expr(tokens, &n, last); if (n <= last) { fprintf(stderr, "Unable to parse tokens as expression\n"); exit(1); } return d; } static void get_token_position(CXToken token, unsigned *lnum, unsigned *pos, unsigned *off) { CXFile file; CXSourceLocation l = clang_getTokenLocation(TU, token); clang_getSpellingLocation(l, &file, lnum, pos, off); // clang starts counting at 1 for some reason (*lnum)--; (*pos)--; } static void indent_for_token(CXToken token, unsigned *lnum, unsigned *pos, unsigned *off) { unsigned l, p; get_token_position(token, &l, &p, off); for (; *lnum < l; (*lnum)++, *pos = 0) fprintf(out, "\n"); for (; *pos < p; (*pos)++) fprintf(out, " "); } static void print_literal_text(const char *str, unsigned *lnum, unsigned *pos) { fprintf(out, "%s", str); (*pos) += strlen(str); } static void print_token(CXToken token, unsigned *lnum, unsigned *pos) { CXString s = clang_getTokenSpelling(TU, token); print_literal_text(clang_getCString(s), lnum, pos); clang_disposeString(s); } static unsigned find_token_for_offset(CXToken *tokens, unsigned n_tokens, unsigned n, unsigned off) { for (; n < n_tokens; n++) { unsigned l, p, o; get_token_position(tokens[n], &l, &p, &o); if (o == off) return n; } abort(); } static unsigned find_value_index(StructArrayList *l, unsigned i) { unsigned n; if (l->type == TYPE_IRRELEVANT) { return i; } else { for (n = 0; n < l->n_entries; n++) { if (l->entries[n].index == i) return n; } } return -1; } static unsigned find_index_for_level(unsigned level, unsigned index, unsigned start) { unsigned n, cnt = 0; for (n = start; n < n_struct_array_lists; n++) { if (struct_array_lists[n].level < level) { return n; } else if (struct_array_lists[n].level == level) { if (cnt++ == index) return n; } } return n_struct_array_lists; } static void reorder_compound_literal_list(unsigned n) { if (!n_comp_literal_lists) return; // FIXME probably slow - quicksort? for (; n < n_comp_literal_lists - 1; n++) { unsigned l, lowest = n; // find the lowest for (l = n + 1; l < n_comp_literal_lists; l++) { if (comp_literal_lists[l].context.start < comp_literal_lists[lowest].context.start) { lowest = l; } } // move it in place if (lowest != n) { CompoundLiteralList bak = comp_literal_lists[lowest]; memmove(&comp_literal_lists[n + 1], &comp_literal_lists[n], sizeof(comp_literal_lists[0]) * (lowest - n)); comp_literal_lists[n] = bak; } } } static void print_token_wrapper(CXToken *tokens, unsigned n_tokens, unsigned *n, unsigned *lnum, unsigned *cpos, unsigned *saidx, unsigned *clidx, unsigned *esidx, unsigned off); static void declare_variable(CompoundLiteralList *l, unsigned cur_tok_off, unsigned *clidx, unsigned *_saidx, unsigned *esidx, CXToken *tokens, unsigned n_tokens, const char *var_name, unsigned *lnum, unsigned *cpos) { unsigned idx1, idx2, off, n, saidx = *_saidx; /* type information, e.g. 'int' or 'struct AVRational' */ idx1 = find_token_for_offset(tokens, n_tokens, cur_tok_off, l->cast_token.start); idx2 = find_token_for_offset(tokens, n_tokens, cur_tok_off, l->cast_token_array_start); get_token_position(tokens[idx1 + 1], lnum, cpos, &off); for (n = idx1 + 1; n <= idx2 - 1; n++) { indent_for_token(tokens[n], lnum, cpos, &off); print_token(tokens[n], lnum, cpos); } /* variable name and array tokens, e.g. 'tmp[]' */ print_literal_text(" ", lnum, cpos); print_literal_text(var_name, lnum, cpos); idx1 = find_token_for_offset(tokens, n_tokens, cur_tok_off, l->cast_token.end); for (n = idx2; n <= idx1 - 1; n++) { indent_for_token(tokens[n], lnum, cpos, &off); print_token(tokens[n], lnum, cpos); } print_literal_text(" = ", lnum, cpos); /* value */ idx1 = find_token_for_offset(tokens, n_tokens, cur_tok_off, l->value_token.start); idx2 = find_token_for_offset(tokens, n_tokens, cur_tok_off, l->value_token.end); get_token_position(tokens[idx1], lnum, cpos, &off); while (saidx < n_struct_array_lists && struct_array_lists[saidx].value_offset.start < off) saidx++; for (n = idx1; n <= idx2; n++) { indent_for_token(tokens[n], lnum, cpos, &off); print_token_wrapper(tokens, n_tokens, &n, lnum, cpos, &saidx, clidx, esidx, off); } } static void replace_comp_literal(CompoundLiteralList *l, unsigned *clidx, unsigned *saidx, unsigned *esidx, unsigned *lnum, unsigned *cpos, unsigned *_n, CXToken *tokens, unsigned n_tokens) { static unsigned unique_cntr = 0; if (l->type == TYPE_OMIT_CAST) { unsigned off; *_n = find_token_for_offset(tokens, n_tokens, *_n, l->cast_token.end); get_token_position(tokens[*_n + 1], lnum, cpos, &off); (*clidx)++; } else if (l->type == TYPE_TEMP_ASSIGN) { if (l->context.start < l->cast_token.start) { unsigned n, idx1, idx2, off; char tmp[256]; // open a new context, so we can declare a new variable print_literal_text("{ ", lnum, cpos); snprintf(tmp, sizeof(tmp), "tmp__%u", unique_cntr++); l->data.t_c_d.tmp_var_name = strdup(tmp); declare_variable(l, *_n, clidx, saidx, esidx, tokens, n_tokens, tmp, lnum, cpos); print_literal_text("; ", lnum, cpos); // re-insert in list now for replacement of the variable // reference (instead of the actual CL) l->context.start = l->cast_token.start; reorder_compound_literal_list(l - comp_literal_lists); get_token_position(tokens[*_n], lnum, cpos, &off); (*_n)--; } else if (l->context.start == l->cast_token.start) { // FIXME duplicate of code in TYPE_CONST_DECL unsigned off; char *tmp_var_name = l->data.t_c_d.tmp_var_name; // replace original CL with a reference to the // newly declared static const variable print_literal_text(tmp_var_name, lnum, cpos); l->data.t_c_d.tmp_var_name = NULL; free(tmp_var_name); *_n = find_token_for_offset(tokens, n_tokens, *_n, l->value_token.end); get_token_position(tokens[*_n + 1], lnum, cpos, &off); l->context.start = l->context.end; reorder_compound_literal_list(l - comp_literal_lists); } else { print_token(tokens[*_n], lnum, cpos); // multiple contexts may want to close here - close all at once do { print_literal_text(" }", lnum, cpos); (*clidx)++; } while (*clidx < n_comp_literal_lists && comp_literal_lists[*clidx].context.start == l->context.start); } } else if (l->type == TYPE_CONST_DECL) { if (l->context.start < l->cast_token.start) { unsigned idx1, idx2, n, off; char tmp[256]; // declare static const variable print_literal_text("static ", lnum, cpos); snprintf(tmp, sizeof(tmp), "tmp__%u", unique_cntr++); l->data.t_c_d.tmp_var_name = strdup(tmp); declare_variable(l, *_n, clidx, saidx, esidx, tokens, n_tokens, tmp, lnum, cpos); print_literal_text(";", lnum, cpos); // re-insert in list now for replacement of the variable // reference (instead of the actual CL) l->context.start = l->cast_token.start; reorder_compound_literal_list(l - comp_literal_lists); (*_n)--; get_token_position(tokens[*_n], lnum, cpos, &off); } else { // FIXME duplicate of code in TYPE_TEMP_ASSIGN unsigned off; char *tmp_var_name = l->data.t_c_d.tmp_var_name; // replace original CL with a reference to the // newly declared static const variable print_literal_text(tmp_var_name, lnum, cpos); l->data.t_c_d.tmp_var_name = NULL; free(tmp_var_name); *_n = find_token_for_offset(tokens, n_tokens, *_n, l->value_token.end); get_token_position(tokens[*_n + 1], lnum, cpos, &off); (*clidx)++; } } else if (l->type == TYPE_NEW_CONTEXT) { if (l->context.start == l->cast_token.start) { unsigned off; print_literal_text("{ ", lnum, cpos); // FIXME it may be easier to replicate the variable declaration // and initialization here, and then to actually empty out the // original location where the variable initialization/declaration // happened l->context.start = l->context.end; l->type = TYPE_TEMP_ASSIGN; reorder_compound_literal_list(l - comp_literal_lists); get_token_position(tokens[*_n], lnum, cpos, &off); (*_n)--; } } else if (l->type == TYPE_LOOP_CONTEXT) { if (l->context.start < l->cast_token.start) { unsigned off, idx1, idx2, n; // add variable declaration/init, add terminating ';' print_literal_text("{ ", lnum, cpos); l->context.start = l->cast_token.start; idx1 = find_token_for_offset(tokens, n_tokens, *_n, l->cast_token.start); idx2 = find_token_for_offset(tokens, n_tokens, *_n, l->cast_token.end); get_token_position(tokens[idx1], lnum, cpos, &off); for (n = idx1; n <= idx2; n++) { indent_for_token(tokens[n], lnum, cpos, &off); print_token(tokens[n], lnum, cpos); } print_literal_text("; ", lnum, cpos); get_token_position(tokens[*_n], lnum, cpos, &off); (*_n)--; } else if (l->context.start == l->cast_token.start) { unsigned off; // remove variable declaration/init, remove ',' if present l->context.start = l->context.end; l->type = TYPE_TEMP_ASSIGN; reorder_compound_literal_list(l - comp_literal_lists); (*_n)--; do { (*_n)++; get_token_position(tokens[*_n], lnum, cpos, &off); } while (off < l->cast_token.end); } } } static void replace_struct_array(unsigned *_saidx, unsigned *_clidx, unsigned *esidx, unsigned *lnum, unsigned *cpos, unsigned *_n, CXToken *tokens, unsigned n_tokens) { unsigned saidx = *_saidx, off, i, n = *_n, j; StructArrayList *sal = &struct_array_lists[saidx]; StructDeclaration *decl = sal->struct_decl_idx != (unsigned) -1 ? &structs[sal->struct_decl_idx] : NULL; int is_union = decl ? decl->is_union : 0; if (sal->convert_to_assignment) { CXString spelling; print_literal_text(";", lnum, cpos); for (i = 0; i < sal->n_entries; i++) { StructArrayItem *sai = &sal->entries[i]; unsigned token_start = find_token_for_offset(tokens, n_tokens, *_n, sai->value_offset.start); unsigned token_end = find_token_for_offset(tokens, n_tokens, *_n, sai->value_offset.end); unsigned saidx2 = 0; print_literal_text(sal->name, lnum, cpos); print_literal_text(".", lnum, cpos); print_literal_text(structs[sal->struct_decl_idx].entries[sai->index].name, lnum, cpos); print_literal_text("=", lnum, cpos); get_token_position(tokens[token_start], lnum, cpos, &off); for (n = token_start; n <= token_end; n++) print_token_wrapper(tokens, n_tokens, &n, lnum, cpos, &saidx2, _clidx, esidx, off); print_literal_text(";", lnum, cpos); } n = find_token_for_offset(tokens, n_tokens, *_n, struct_array_lists[saidx].value_offset.end); *_n = n; print_literal_text("{", lnum, cpos); // adjust token index and position back get_token_position(tokens[n], lnum, cpos, &off); spelling = clang_getTokenSpelling(TU, tokens[n]); (*cpos) += strlen(clang_getCString(spelling)); clang_disposeString(spelling); return; } // we assume here the indenting for the first opening token, // i.e. the '{', is already taken care of print_token(tokens[n++], lnum, cpos); indent_for_token(tokens[n], lnum, cpos, &off); for (i = 0; i < struct_array_lists[saidx].n_entries; i++) assert(struct_array_lists[saidx].entries[i].index != (unsigned) -1); for (j = 0, i = 0; i < struct_array_lists[saidx].n_entries; j++) { unsigned expr_off_s, expr_off_e, val_idx, val_off_s, val_off_e, saidx2, indent_token_end, next_indent_token_start, val_token_start, val_token_end; int print_normal = 1; CXString spelling; StructMember *member = decl ? &decl->entries[j] : NULL; val_idx = find_value_index(&struct_array_lists[saidx], j); assert(struct_array_lists[saidx].array_depth > 0 || j < structs[struct_array_lists[saidx].struct_decl_idx].n_entries); if (val_idx == (unsigned) -1) { unsigned depth = struct_array_lists[saidx].array_depth; unsigned idx = struct_array_lists[saidx].struct_decl_idx; if (is_union) // Don't print the filler zeros for unions continue; if (depth > 1) { print_literal_text("{ 0 }", lnum, cpos); } else if (depth == 1) { if (idx != (unsigned) -1) { print_literal_text("{ 0 }", lnum, cpos); } else { print_literal_text("0", lnum, cpos); } } else if ((structs[idx].entries[j].struct_decl_idx != (unsigned) -1 && structs[idx].entries[j].n_ptrs == 0) || structs[idx].entries[j].array_depth) { print_literal_text("{ 0 }", lnum, cpos); } else { print_literal_text("0", lnum, cpos); } print_literal_text(", ", lnum, cpos); continue; // gap } expr_off_e = struct_array_lists[saidx].entries[i].expression_offset.end; next_indent_token_start = find_token_for_offset(tokens, n_tokens, *_n, expr_off_e); val_off_s = struct_array_lists[saidx].entries[val_idx].value_offset.start; val_token_start = find_token_for_offset(tokens, n_tokens, *_n, val_off_s); val_off_e = struct_array_lists[saidx].entries[val_idx].value_offset.end; val_token_end = find_token_for_offset(tokens, n_tokens, *_n, val_off_e); saidx2 = find_index_for_level(struct_array_lists[saidx].level + 1, val_idx, saidx + 1); if (saidx2 < n_struct_array_lists && struct_array_lists[saidx2].level < struct_array_lists[saidx].level) saidx2 = n_struct_array_lists; // adjust position get_token_position(tokens[val_token_start], lnum, cpos, &off); if (is_union && j != 0) { StructMember *first_member = &decl->entries[0]; if ((!strcmp(first_member->type, "double") || !strcmp(first_member->type, "float")) && !first_member->n_ptrs) { fprintf(stderr, "Can't convert type %s to %s for union\n", member->type, first_member->type); exit(1); } if (first_member->n_ptrs) print_literal_text("(void*) ", lnum, cpos); if (member->n_ptrs) print_literal_text("(intptr_t) ", lnum, cpos); if ((!strcmp(member->type, "double") || !strcmp(member->type, "float")) && !member->n_ptrs) { // Convert a literal floating pointer number (not a pointer to // one of them) to its binary representation union { uint64_t i; double f; } if64; char buf[20]; if64.f = eval_tokens(tokens, val_token_start, val_token_end); if (!strcmp(member->type, "float")) { union { uint32_t i; float f; } if32; if32.f = if64.f; if64.i = if32.i; } snprintf(buf, sizeof(buf), "%#"PRIx64, if64.i); print_literal_text(buf, lnum, cpos); print_normal = 0; } } // print values out of order for (n = val_token_start; n <= val_token_end && print_normal; n++) { print_token_wrapper(tokens, n_tokens, &n, lnum, cpos, &saidx2, _clidx, esidx, off); if (n != val_token_end) indent_for_token(tokens[n + 1], lnum, cpos, &off); } // adjust token index and position back n = next_indent_token_start; get_token_position(tokens[n], lnum, cpos, &off); spelling = clang_getTokenSpelling(TU, tokens[n]); (*cpos) += strlen(clang_getCString(spelling)); clang_disposeString(spelling); n++; if (++i < struct_array_lists[saidx].n_entries) { expr_off_s = struct_array_lists[saidx].entries[i].expression_offset.start; indent_token_end = find_token_for_offset(tokens, n_tokens, *_n, expr_off_s); } else { indent_token_end = find_token_for_offset(tokens, n_tokens, *_n, struct_array_lists[saidx].value_offset.end); } if (is_union) // Unions should be initialized by only one element break; if (n < indent_token_end) indent_for_token(tokens[n], lnum, cpos, &off); for (; n < indent_token_end; n++) { print_token(tokens[n], lnum, cpos); indent_for_token(tokens[n + 1], lnum, cpos, &off); } } // update *saidx *_saidx = find_index_for_level(struct_array_lists[saidx].level, 1, saidx); // print '}' closing token n = find_token_for_offset(tokens, n_tokens, *_n, struct_array_lists[saidx].value_offset.end); indent_for_token(tokens[n], lnum, cpos, &off); print_token(tokens[n], lnum, cpos); *_n = n; } static void print_token_wrapper(CXToken *tokens, unsigned n_tokens, unsigned *n, unsigned *lnum, unsigned *cpos, unsigned *saidx, unsigned *clidx, unsigned *esidx, unsigned off) { *saidx = 0; while (*saidx < n_struct_array_lists && struct_array_lists[*saidx].value_offset.start < off) (*saidx)++; *clidx = 0; while (*clidx < n_comp_literal_lists && (comp_literal_lists[*clidx].type == TYPE_UNKNOWN || comp_literal_lists[*clidx].context.start < off)) (*clidx)++; if (*saidx < n_struct_array_lists && off == struct_array_lists[*saidx].value_offset.start) { if (struct_array_lists[*saidx].type == TYPE_IRRELEVANT || struct_array_lists[*saidx].n_entries == 0) { (*saidx)++; print_token(tokens[*n], lnum, cpos); } else { replace_struct_array(saidx, clidx, esidx, lnum, cpos, n, tokens, n_tokens); } } else if (*clidx < n_comp_literal_lists && off == comp_literal_lists[*clidx].context.start) { if (comp_literal_lists[*clidx].type == TYPE_UNKNOWN) { print_token(tokens[*n], lnum, cpos); } else { replace_comp_literal(&comp_literal_lists[*clidx], clidx, saidx, esidx, lnum, cpos, n, tokens, n_tokens); } while (*clidx < n_comp_literal_lists && comp_literal_lists[*clidx].type == TYPE_UNKNOWN) (*clidx)++; } else { print_token(tokens[*n], lnum, cpos); } while (*esidx < n_end_scopes && off >= end_scopes[*esidx].end - 1) { unsigned i; for (i = 0; i < end_scopes[*esidx].n_scopes; i++) print_literal_text("}", lnum, cpos); (*cpos) -= end_scopes[*esidx].n_scopes; (*esidx)++; } } static void print_tokens(CXToken *tokens, unsigned n_tokens) { unsigned cpos = 0, lnum = 0, n, saidx = 0, clidx = 0, esidx = 0, off; reorder_compound_literal_list(0); for (n = 0; n < n_tokens; n++) { indent_for_token(tokens[n], &lnum, &cpos, &off); print_token_wrapper(tokens, n_tokens, &n, &lnum, &cpos, &saidx, &clidx, &esidx, off); } // each file ends with a newline fprintf(out, "\n"); } static void cleanup(void) { unsigned n, m; #define DEBUG 0 dprintf("N compound literals: %d\n", n_comp_literal_lists); for (n = 0; n < n_comp_literal_lists; n++) { dprintf("[%d]: type=%d, struct=%d (%s), variable range=%u-%u\n", n, comp_literal_lists[n].type, comp_literal_lists[n].struct_decl_idx, comp_literal_lists[n].struct_decl_idx != (unsigned) -1 ? structs[comp_literal_lists[n].struct_decl_idx].name : "<none>", comp_literal_lists[n].value_token.start, comp_literal_lists[n].value_token.end); } free(comp_literal_lists); dprintf("N array/struct variables: %d\n", n_struct_array_lists); for (n = 0; n < n_struct_array_lists; n++) { dprintf("[%d]: type=%d, struct=%d (%s), level=%d, n_entries=%d, range=%u-%u, depth=%u\n", n, struct_array_lists[n].type, struct_array_lists[n].struct_decl_idx, struct_array_lists[n].struct_decl_idx != (unsigned) -1 ? (structs[struct_array_lists[n].struct_decl_idx].name[0] ? structs[struct_array_lists[n].struct_decl_idx].name : "<anonymous>") : "<none>", struct_array_lists[n].level, struct_array_lists[n].n_entries, struct_array_lists[n].value_offset.start, struct_array_lists[n].value_offset.end, struct_array_lists[n].array_depth); for (m = 0; m < struct_array_lists[n].n_entries; m++) { dprintf(" [%d]: idx=%d, range=%u-%u\n", m, struct_array_lists[n].entries[m].index, struct_array_lists[n].entries[m].value_offset.start, struct_array_lists[n].entries[m].value_offset.end); } free(struct_array_lists[n].entries); free(struct_array_lists[n].name); } free(struct_array_lists); dprintf("N extra scope ends: %d\n", n_end_scopes); for (n = 0; n < n_end_scopes; n++) { dprintf("[%d]: end=%u n_scopes=%u\n", n, end_scopes[n].end, end_scopes[n].n_scopes); } free(end_scopes); dprintf("N typedef entries: %d\n", n_typedefs); for (n = 0; n < n_typedefs; n++) { if (typedefs[n].struct_decl_idx != (unsigned) -1) { if (structs[typedefs[n].struct_decl_idx].name[0]) { dprintf("[%d]: %s (struct %s = %d)\n", n, typedefs[n].name, structs[typedefs[n].struct_decl_idx].name, typedefs[n].struct_decl_idx); } else { dprintf("[%d]: %s (<anonymous> struct = %d)\n", n, typedefs[n].name, typedefs[n].struct_decl_idx); } } else if (typedefs[n].enum_decl_idx != (unsigned) -1) { if (structs[typedefs[n].enum_decl_idx].name[0]) { dprintf("[%d]: %s (enum %s = %d)\n", n, typedefs[n].name, enums[typedefs[n].enum_decl_idx].name, typedefs[n].enum_decl_idx); } else { dprintf("[%d]: %s (<anonymous> enum = %d)\n", n, typedefs[n].name, typedefs[n].enum_decl_idx); } } else { dprintf("[%d]: %s (%s)\n", n, typedefs[n].name, typedefs[n].proxy); } if (typedefs[n].proxy) free(typedefs[n].proxy); free(typedefs[n].name); } free(typedefs); // free memory dprintf("N struct entries: %d\n", n_structs); for (n = 0; n < n_structs; n++) { if (structs[n].name[0]) { dprintf("[%d]: %s (%p)\n", n, structs[n].name, &structs[n]); } else { dprintf("[%d]: <anonymous> (%p)\n", n, &structs[n]); } for (m = 0; m < structs[n].n_entries; m++) { dprintf(" [%d]: %s (%s/%d/%d/%u)\n", m, structs[n].entries[m].name, structs[n].entries[m].type, structs[n].entries[m].n_ptrs, structs[n].entries[m].array_depth, structs[n].entries[m].struct_decl_idx); free(structs[n].entries[m].type); free(structs[n].entries[m].name); } free(structs[n].entries); free(structs[n].name); } free(structs); dprintf("N enum entries: %d\n", n_enums); for (n = 0; n < n_enums; n++) { if (enums[n].name[0]) { dprintf("[%d]: %s (%p)\n", n, enums[n].name, &enums[n]); } else { dprintf("[%d]: <anonymous> (%p)\n", n, &enums[n]); } for (m = 0; m < enums[n].n_entries; m++) { dprintf(" [%d]: %s = %d\n", m, enums[n].entries[m].name, enums[n].entries[m].value); free(enums[n].entries[m].name); } free(enums[n].entries); free(enums[n].name); } free(enums); #define DEBUG 0 } int convert(const char *infile, const char *outfile) { CXIndex index; unsigned n_tokens; CXToken *tokens; CXSourceRange range; CXCursor cursor; CursorRecursion rec; out = fopen(outfile, "w"); if (!out) { fprintf(stderr, "Unable to open output file %s\n", outfile); return 1; } index = clang_createIndex(1, 1); TU = clang_createTranslationUnitFromSourceFile(index, infile, 0, NULL, 0, NULL); cursor = clang_getTranslationUnitCursor(TU); range = clang_getCursorExtent(cursor); clang_tokenize(TU, range, &tokens, &n_tokens); memset(&rec, 0, sizeof(rec)); rec.tokens = tokens; rec.n_tokens = n_tokens; rec.kind = CXCursor_TranslationUnit; clang_visitChildren(cursor, callback, &rec); print_tokens(tokens, n_tokens); clang_disposeTokens(TU, tokens, n_tokens); clang_disposeTranslationUnit(TU); clang_disposeIndex(index); cleanup(); fclose(out); return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "%s <in> <out>\n", argv[0]); return 1; } return convert(argv[1], argv[2]); }
36.648723
105
0.545754
12b85e99aae150f7cdc373348559b3ccad725964
9,340
h
C
Moco/Moco/MocoGoal/MocoOrientationTrackingGoal.h
zhengsizehrb/opensim-moco
9844abc640a34d818a4bb21ef4fea3c3cb0f34ed
[ "Apache-2.0" ]
41
2019-11-13T10:29:20.000Z
2022-03-10T17:42:30.000Z
Moco/Moco/MocoGoal/MocoOrientationTrackingGoal.h
zhengsizehrb/opensim-moco
9844abc640a34d818a4bb21ef4fea3c3cb0f34ed
[ "Apache-2.0" ]
165
2019-11-13T00:55:57.000Z
2022-03-04T19:02:26.000Z
Moco/Moco/MocoGoal/MocoOrientationTrackingGoal.h
zhengsizehrb/opensim-moco
9844abc640a34d818a4bb21ef4fea3c3cb0f34ed
[ "Apache-2.0" ]
15
2020-01-24T23:57:57.000Z
2021-12-10T21:59:46.000Z
#ifndef MOCO_MOCOORIENTATIONTRACKINGGOAL_H #define MOCO_MOCOORIENTATIONTRACKINGGOAL_H /* -------------------------------------------------------------------------- * * OpenSim Moco: MocoOrientationTrackingGoal.h * * -------------------------------------------------------------------------- * * Copyright (c) 2019 Stanford University and the Authors * * * * Author(s): Nicholas Bianco * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "../Common/TableProcessor.h" #include "../MocoWeightSet.h" #include "MocoGoal.h" #include <OpenSim/Common/GCVSplineSet.h> #include <OpenSim/Common/TimeSeriesTable.h> #include <OpenSim/Simulation/Model/Frame.h> namespace OpenSim { using SimTK::Rotation; /// The squared difference between a model frame's orientation and a reference /// orientation value, summed over the frames for which a reference is provided, /// and integrated over the phase. This can be used to track orientation /// quantities in the model that don't correspond to model degrees of freedom. /// The reference can be provided as a trajectory of SimTK::Rotation%s /// representing the orientation reference data, or as a states trajectory from /// which the tracked rotation reference is computed. Both rotation and states /// references can be provided as a file name to a STO or CSV file (or other /// file types for which there is a FileAdapter), or programmatically as a /// TimeSeriesTable_<SimTK::Rotation> (for the rotation reference) or as a /// scalar TimeSeriesTable (for the states reference). /// /// This cost requires realization to SimTK::Stage::Position. The cost is /// computed by creating a SimTK::Rotation between the model frame and the /// reference data, and then converting the rotation to an angle-axis /// representation and minimizing the angle value. The angle value is /// equivalent to the orientation error between the model frame and the /// reference data, so we only need to minimize this single scalar value per /// tracked frame, compared to other more complicated approaches which could /// require multiple minimized error values (e.g. Euler angle errors, etc). /// /// @ingroup mocogoal class OSIMMOCO_API MocoOrientationTrackingGoal : public MocoGoal { OpenSim_DECLARE_CONCRETE_OBJECT(MocoOrientationTrackingGoal, MocoGoal); public: MocoOrientationTrackingGoal() { constructProperties(); } MocoOrientationTrackingGoal(std::string name) : MocoGoal(std::move(name)) { constructProperties(); } MocoOrientationTrackingGoal(std::string name, double weight) : MocoGoal(std::move(name), weight) { constructProperties(); } /// Set the rotations of individual frames in ground to be tracked /// in the cost. The column labels of the provided reference must /// be paths to frames in the model, e.g. `/bodyset/torso`. If the /// frame_paths property is empty, all frames with data in this reference /// will be tracked. Otherwise, only the frames specified via /// setFramePaths() will be tracked. Calling this function clears the values /// provided via setStatesReference(), setRotationReference(), or the /// `states_reference_file` property, if any. void setRotationReferenceFile(const std::string& filepath) { set_states_reference(TableProcessor()); m_rotation_table = TimeSeriesTable_<Rotation>(); set_rotation_reference_file(filepath); } /// Each column label must be the path of a valid frame path (see /// seeRotationReferenceFile()). Calling this function clears the /// `states_reference_file` and `rotation_reference_file` properties or the /// table provided via setStatesReference(), if any. void setRotationReference(const TimeSeriesTable_<Rotation>& ref) { set_states_reference(TableProcessor()); set_rotation_reference_file(""); m_rotation_table = ref; } /// Provide a table containing values of model state variables. These data /// are used to create a StatesTrajectory internally, from which the /// rotation data for the frames specified in setFramePaths() are computed. /// Each column label in the reference must be the path of a state variable, /// e.g., `/jointset/ankle_angle_r/value`. Calling this function clears the /// table provided via setRotationReference(), or the /// `rotation_reference_file` property, if any. The table is not loaded /// until the MocoProblem is initialized. void setStatesReference(const TableProcessor& ref) { set_rotation_reference_file(""); m_rotation_table = TimeSeriesTable_<Rotation>(); set_states_reference(std::move(ref)); } /// Set the paths to frames in the model that this cost term will track. The /// names set here must correspond to OpenSim::Component%s that derive from /// OpenSim::Frame, which includes SimTK::Rotation as an output. /// Replaces the frame path set if it already exists. void setFramePaths(const std::vector<std::string>& paths) { updProperty_frame_paths().clear(); for (const auto& path : paths) { append_frame_paths(path); } } /// Set the weight for an individual frame's rotation tracking. If a weight /// is already set for the requested frame, then the provided weight /// replaces the previous weight. An exception is thrown if a weight /// for an unknown frame is provided. void setWeightForFrame(const std::string& frameName, const double& weight) { if (get_rotation_weights().contains(frameName)) { upd_rotation_weights().get(frameName).setWeight(weight); } else { upd_rotation_weights().cloneAndAppend({frameName, weight}); } } /// Provide a MocoWeightSet to weight frame rotation tracking in the cost. /// Replaces the weight set if it already exists. void setWeightSet(const MocoWeightSet& weightSet) { upd_rotation_weights() = weightSet; } /// If no states reference has been provided, this returns an empty /// processor. const TableProcessor& getStatesReference() const { return get_states_reference(); } /// If no rotation reference file has been provided, this returns an empty /// string. std::string getRotationReferenceFile() const { return get_rotation_reference_file(); } protected: void initializeOnModelImpl(const Model& model) const override; void calcIntegrandImpl( const IntegrandInput& input, SimTK::Real& integrand) const override; void calcGoalImpl( const GoalInput& input, SimTK::Vector& cost) const override { cost[0] = input.integral; } void printDescriptionImpl() const override; private: OpenSim_DECLARE_PROPERTY(states_reference, TableProcessor, "Trajectories of model state " "variables from which tracked rotation data is computed. Column " "labels should be model state paths, " "e.g., '/jointset/ankle_angle_r/value'"); OpenSim_DECLARE_PROPERTY(rotation_reference_file, std::string, "Path to file (.sto, .csv, ...) containing orientation reference " "data to track. Column labels should be paths to frames in the " "model, e.g. '/bodyset/torso'."); OpenSim_DECLARE_LIST_PROPERTY(frame_paths, std::string, "The frames in the model that this cost term will track. " "The names set here must correspond to Components that " "derive from class Frame."); OpenSim_DECLARE_PROPERTY(rotation_weights, MocoWeightSet, "Set of weight objects to weight the tracking of " "individual " "frames' rotations in the cost."); void constructProperties() { constructProperty_states_reference(TableProcessor()); constructProperty_rotation_reference_file(""); constructProperty_frame_paths(); constructProperty_rotation_weights(MocoWeightSet()); } TimeSeriesTable_<Rotation> m_rotation_table; mutable GCVSplineSet m_ref_splines; mutable std::vector<std::string> m_frame_paths; mutable std::vector<SimTK::ReferencePtr<const Frame>> m_model_frames; mutable std::vector<double> m_rotation_weights; }; } // namespace OpenSim #endif // MOCO_MOCOORIENTATIONTRACKINGGOAL_H
50.76087
80
0.664882
12eab57a26d7b53c7d2178c089b20d2272f23c5f
581
h
C
libop/background/Hook/InputHook.h
SZR521/op
75dc712fe78ec861988159198e38ec2b2fb988b2
[ "MIT" ]
1
2021-06-06T07:35:57.000Z
2021-06-06T07:35:57.000Z
libop/background/Hook/InputHook.h
SZR521/op
75dc712fe78ec861988159198e38ec2b2fb988b2
[ "MIT" ]
null
null
null
libop/background/Hook/InputHook.h
SZR521/op
75dc712fe78ec861988159198e38ec2b2fb988b2
[ "MIT" ]
null
null
null
#ifndef __INPUT_HOOK_H #define __INPUT_HOOK_H #include "../../core/globalVar.h" namespace InputHook { /*target window hwnd*/ extern HWND input_hwnd; extern int input_type; /*name of ...*/ extern wchar_t shared_res_name[256]; extern wchar_t mutex_name[256]; extern void* old_address; // int setup(HWND hwnd_, int input_type_); int release(); int x,y; }; //以下函数用于HOOK DX9 //此函数做以下工作 /* 1.hook相关函数 2.设置共享内存,互斥量 3.截图(hook)至共享内存 */ //返回值:1 成功,0失败 DLL_API long __stdcall SetInputHook(HWND hwnd_, int input_type_); DLL_API long __stdcall ReleaseInputHook(); #endif
16.138889
65
0.724613
751949700a1726928b4feb275f783105bd0aa504
2,131
h
C
usr/libexec/appstored/TFUploadFeedbackRequest.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
5
2021-04-29T04:31:43.000Z
2021-08-19T18:59:58.000Z
usr/libexec/appstored/TFUploadFeedbackRequest.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
null
null
null
usr/libexec/appstored/TFUploadFeedbackRequest.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
1
2022-03-19T11:16:23.000Z
2022-03-19T11:16:23.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <ProtocolBuffer/PBRequest.h> #import "NSCopying-Protocol.h" @class TFAppleWatch, TFApplication, TFDevice, TFFeedback; @interface TFUploadFeedbackRequest : PBRequest <NSCopying> { unsigned long long _dsid; // 8 = 0x8 unsigned long long _posixTimestampMillis; // 16 = 0x10 TFAppleWatch *_appleWatch; // 24 = 0x18 TFApplication *_application; // 32 = 0x20 TFDevice *_device; // 40 = 0x28 TFFeedback *_feedback; // 48 = 0x30 struct { unsigned int dsid:1; unsigned int posixTimestampMillis:1; } _has; // 56 = 0x38 } - (void).cxx_destruct; // IMP=0x00000001001ba6ec @property(retain, nonatomic) TFAppleWatch *appleWatch; // @synthesize appleWatch=_appleWatch; @property(retain, nonatomic) TFDevice *device; // @synthesize device=_device; @property(retain, nonatomic) TFApplication *application; // @synthesize application=_application; @property(retain, nonatomic) TFFeedback *feedback; // @synthesize feedback=_feedback; @property(nonatomic) unsigned long long dsid; // @synthesize dsid=_dsid; - (void)mergeFrom:(id)arg1; // IMP=0x00000001001ba4e8 - (unsigned long long)hash; // IMP=0x00000001001ba3ec - (_Bool)isEqual:(id)arg1; // IMP=0x00000001001ba25c - (id)copyWithZone:(struct _NSZone *)arg1; // IMP=0x00000001001ba10c - (void)copyTo:(id)arg1; // IMP=0x00000001001ba008 - (void)writeTo:(id)arg1; // IMP=0x00000001001b9f1c - (_Bool)readFrom:(id)arg1; // IMP=0x00000001001b9ae8 - (id)dictionaryRepresentation; // IMP=0x00000001001b98d0 - (id)description; // IMP=0x00000001001b981c @property(nonatomic) _Bool hasPosixTimestampMillis; @property(nonatomic) unsigned long long posixTimestampMillis; // @synthesize posixTimestampMillis=_posixTimestampMillis; @property(readonly, nonatomic) _Bool hasAppleWatch; @property(readonly, nonatomic) _Bool hasDevice; @property(readonly, nonatomic) _Bool hasApplication; @property(readonly, nonatomic) _Bool hasFeedback; @property(nonatomic) _Bool hasDsid; @end
40.980769
120
0.750352
8a531d4fa4f9da5989e259deebd51e61c904374c
4,415
h
C
src/kits/interface/layout/Layout.h
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/interface/layout/Layout.h
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/interface/layout/Layout.h
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* -------------------------------------------------------------------------- * * BHAPI++ Copyright (C) 2017, Stanislaw Stasiak, based on Haiku & ETK++, The Easy Toolkit for C++ programing * Copyright (C) 2004-2007, Anthony Lee, All Rights Reserved * * BHAPI++ library is a freeware; it may be used and distributed according to * the terms of The MIT License. * * 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. * * File: Layout.h * * --------------------------------------------------------------------------*/ #ifndef BHAPI_LAYOUT_H #define BHAPI_LAYOUT_H #include <kits/support/List.h> #include <kits/interface/InterfaceDefs.h> #include <kits/interface/Region.h> #ifdef __cplusplus /* Just for C++ */ class BLayoutItem; class BLayoutForm; class BHAPI_IMPEXP BLayoutContainer { public: BLayoutContainer(); virtual ~BLayoutContainer(); virtual bool AddItem(BLayoutItem *item, __be_int32 index = -1); virtual bool RemoveItem(BLayoutItem *item); BLayoutItem *RemoveItem(__be_int32 index); BLayoutItem *ItemAt(__be_int32 index) const; __be_int32 IndexOf(const BLayoutItem *item) const; __be_int32 CountItems() const; float UnitsPerPixel() const; void SetUnitsPerPixel(float value, bool deep = true); virtual void Invalidate(BRect rect); void SetPrivateData(void *data, void (*destroy_func)(void*) = NULL); void *PrivateData() const; private: friend class BLayoutItem; float fUnitsPerPixel; BList fItems; void *fPrivate[2]; }; class BHAPI_IMPEXP BLayoutItem : public BLayoutContainer { public: BLayoutItem(BRect frame, __be_uint32 resizingMode); virtual ~BLayoutItem(); BLayoutContainer *Container() const; BLayoutContainer *Ancestor() const; bool RemoveSelf(); BLayoutItem *PreviousSibling() const; BLayoutItem *NextSibling() const; virtual void SetResizingMode(__be_uint32 mode); __be_uint32 ResizingMode() const; virtual void Show(); virtual void Hide(); bool IsHidden(bool check_containers = true) const; virtual void SendBehind(BLayoutItem *item); virtual void MoveTo(BPoint where); virtual void ScrollTo(BPoint where); virtual void ResizeTo(float width, float height); void MoveAndResizeTo(BPoint where, float width, float height); virtual void GetPreferredSize(float *width, float *height); virtual void ResizeToPreferred(); BRect Bounds() const; // in it's coordinate system BRect Frame() const; // in container's coordinate system const BRegion *VisibleRegion() const; // in it's coordinate system BPoint LeftTop() const; float Width() const; float Height() const; void ConvertToContainer(BPoint *pt) const; BPoint ConvertToContainer(BPoint pt) const; void ConvertFromContainer(BPoint *pt) const; BPoint ConvertFromContainer(BPoint pt) const; virtual void UpdateVisibleRegion(); protected: void GetVisibleRegion(BRegion **region); private: friend class BLayoutContainer; friend class BLayoutForm; BLayoutContainer *fContainer; __be_int32 fIndex; BPoint fLocalOrigin; BRegion fVisibleRegion; BRect fFrame; __be_uint32 fResizingMode; bool fHidden; bool fUpdating; }; class BHAPI_IMPEXP BLayoutForm : public BLayoutItem { public: BLayoutForm(BRect frame, __be_uint32 resizingMode, __be_int32 rows, __be_int32 columns); virtual ~BLayoutForm(); private: void *fData; }; #endif /* __cplusplus */ #endif /* BHAPI_LAYOUT_H */
29.433333
109
0.725481
8a576552fd2fd82b25f27052a9e2eed8d8859d89
484
h
C
src/texture_wrapper.h
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
src/texture_wrapper.h
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
src/texture_wrapper.h
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
#pragma once #include <string.h> class texture_wrapper { public: texture_wrapper(); ~texture_wrapper(); //getters int get_height(); int get_width(); //other functions void free(); bool load_texture(std::string path); bool load_text(std::string text, SDL_Color colour, std::string font, int size); void render(int x, int y, double angle); void render(int x, int y); protected: int width, height; SDL_Texture* texture; }; #include "texture_wrapper.cpp"
18.615385
81
0.696281
e1e630f5a49c2969a172707b794947f394ed64a1
1,316
c
C
libnum/src/vec2/vec2__1.c
vasyekk67/RTv1
0c397598a4a2172ba8472e008da8b06f89f99c27
[ "MIT" ]
null
null
null
libnum/src/vec2/vec2__1.c
vasyekk67/RTv1
0c397598a4a2172ba8472e008da8b06f89f99c27
[ "MIT" ]
null
null
null
libnum/src/vec2/vec2__1.c
vasyekk67/RTv1
0c397598a4a2172ba8472e008da8b06f89f99c27
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* vec2__1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kcharla <kcharla@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/17 09:37:27 by kcharla #+# #+# */ /* Updated: 2020/07/19 15:18:09 by kcharla ### ########.fr */ /* */ /* ************************************************************************** */ #include "libnum.h" t_vec2 vec2_plus(t_vec2 a, t_vec2 b) { return (vec2_do_vec2(a, b, num_plus)); } t_vec2 vec2_minus(t_vec2 a, t_vec2 b) { return (vec2_do_vec2(a, b, num_minus)); } t_vec2 vec2_mult(t_vec2 a, t_vec2 b) { return (vec2_do_vec2(a, b, num_mult)); } t_vec2 vec2_div(t_vec2 a, t_vec2 b) { return (vec2_do_vec2(a, b, num_div)); } t_vec2 vec2_sqr(t_vec2 a) { return (vec2_do_vec2(a, a, num_mult)); }
33.74359
80
0.299392
07619960ab9dba2535f0e41382aa43790de7912e
1,615
h
C
B2G/gecko/content/canvas/src/CanvasImageCache.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/content/canvas/src/CanvasImageCache.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/content/canvas/src/CanvasImageCache.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef CANVASIMAGECACHE_H_ #define CANVASIMAGECACHE_H_ namespace mozilla { namespace dom { class Element; } // namespace dom } // namespace mozilla class nsHTMLCanvasElement; class imgIRequest; class gfxASurface; #include "gfxPoint.h" namespace mozilla { class CanvasImageCache { public: /** * Notify that image element aImage was (or is about to be) drawn to aCanvas * using the first frame of aRequest's image. The data for the surface is * in aSurface, and the image size is in aSize. */ static void NotifyDrawImage(dom::Element* aImage, nsHTMLCanvasElement* aCanvas, imgIRequest* aRequest, gfxASurface* aSurface, const gfxIntSize& aSize); /** * Check whether aImage has recently been drawn into aCanvas. If we return * a non-null surface, then the image was recently drawn into the canvas * (with the same image request) and the returned surface contains the image * data, and the image size will be returned in aSize. */ static gfxASurface* Lookup(dom::Element* aImage, nsHTMLCanvasElement* aCanvas, gfxIntSize* aSize); }; } #endif /* CANVASIMAGECACHE_H_ */
32.959184
79
0.627864
e09b527c4867ff70728974f465ed423cd03a763e
14,966
h
C
include/stats.h
prplfoundation/dwpal
d4cbfc5f4f313a1dea77ff8eb68159d1042fe02d
[ "BSD-2-Clause-Patent" ]
null
null
null
include/stats.h
prplfoundation/dwpal
d4cbfc5f4f313a1dea77ff8eb68159d1042fe02d
[ "BSD-2-Clause-Patent" ]
null
null
null
include/stats.h
prplfoundation/dwpal
d4cbfc5f4f313a1dea77ff8eb68159d1042fe02d
[ "BSD-2-Clause-Patent" ]
null
null
null
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2016-2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #ifndef __STATS_H__ #define __STATS_H__ #include "common.h" #include "vendor_cmds_copy.h" #define HAL_NUM_OF_ANTS (4) #define NL_ATTR_HDR 4 /* Length of IEEE address (bytes) */ #define IEEE_ADDR_LEN (6) /* This type is used for Source and Destination MAC addresses and also as */ /* unique identifiers for Stations and Networks. */ typedef struct _IEEE_ADDR { unsigned char au8Addr[IEEE_ADDR_LEN]; /* WARNING: Special case! No padding here! This structure must be padded externally! */ } IEEE_ADDR; #define MAC_PRINTF_FMT "%02X:%02X:%02X:%02X:%02X:%02X" #define __BYTE_ARG(b,i) (((unsigned char *)(b))[i]) #define __BYTE_ARG_TYPE(t,b,i) ((t)__BYTE_ARG((b),(i))) #define _BYTE_ARG_U(b,i) __BYTE_ARG_TYPE(unsigned int,(b),(i)) #define MAC_PRINTF_ARG(x) \ _BYTE_ARG_U((x), 0),_BYTE_ARG_U((x), 1),_BYTE_ARG_U((x), 2),_BYTE_ARG_U((x), 3),_BYTE_ARG_U((x), 4),_BYTE_ARG_U((x), 5) #define MAX_NL_REPLY 8192 #define MAX_LEN_VALID_VALUE 1024 #define MAX_USAGE_LEN 128 #define MAX_COMMAND_LEN 64 #define num_stats(X) (sizeof(X)/sizeof(stats)) #define PRINT_DESCRIPTION(x) printf("%s\n",x.description); #define INDENTATION(x) if(x>0)\ {while(x) { printf(" "); x--;}}; typedef struct peer_list{ IEEE_ADDR addr; unsigned int is_sta_auth; }peer_list_t; typedef enum { PEER_FLOW_STATS=0, PEER_TRAFFIC_STAT, RETRANS_STAT, TR181_PEER_STATS, NETWORK_BITFIELD, PEER_CAPABILITY, VENDOR_ENUM, PEER_RATE_INFO, PEER_RATE_INFO1, PHY_ENUM, RECOVERY_STAT, HW_TXM_STAT, TRAFFIC_STATS, MGMT_STATS, HW_FLOW_STATUS, TR181_ERROR_STATS, TR181_WLAN_STATS, TR181_HW_STATS, PEER_LIST }stat_id; typedef struct { char cmd[MAX_COMMAND_LEN]; //command name enum ltq_nl80211_vendor_subcmds id; //NL command int num_arg; // number of arguments expected char usage[MAX_USAGE_LEN]; stat_id c; //enum for each cmd }stats_cmd; typedef enum { UCHAR=0, CHAR, BYTE, UINT, INT, LONG, SLONG, SLONGARRAY, SBYTEARRAY, FLAG, BITFIELD, ENUM, TIMESTAMP, LONGFRACT, SLONGFRACT, HUGE, NONE }type; typedef struct { stat_id c; char description[MAX_LEN_VALID_VALUE]; type t; int element; }stats; struct print_struct { stat_id st; stats *sts; int size; }; stats network_bitfield[] = { {NETWORK_BITFIELD, "802.11a", BITFIELD, 0}, {NETWORK_BITFIELD, "802.11b", BITFIELD, 1}, {NETWORK_BITFIELD, "802.11g", BITFIELD, 2}, {NETWORK_BITFIELD, "802.11n", BITFIELD, 3}, {NETWORK_BITFIELD, "802.11ac", BITFIELD, 4}, {NETWORK_BITFIELD, "802.11ax", BITFIELD, 5} }; stats phy_enum[] = { {PHY_ENUM, "802.11a/g", ENUM, 0}, {PHY_ENUM, "802.11b", ENUM, 1}, {PHY_ENUM, "802.11n", ENUM, 2}, {PHY_ENUM, "802.11ac", ENUM, 3}, {PHY_ENUM, "802.11ax", ENUM, 4} }; stats vendor_enum[] = { {VENDOR_ENUM, "Unknown", ENUM, 0}, {VENDOR_ENUM, "Lantiq", ENUM, 1}, {VENDOR_ENUM, "W101", ENUM, 2} }; stats peer_traffic_stat[] = { {PEER_TRAFFIC_STAT, "Peer Traffic Statistics", NONE, 0}, {PEER_TRAFFIC_STAT, "BytesSent - Number of bytes sent successfully", LONG, 0}, {PEER_TRAFFIC_STAT, "BytesReceived - Number of bytes received", LONG, 0}, {PEER_TRAFFIC_STAT, "PacketsSent - Number of packets transmitted", LONG, 0}, {PEER_TRAFFIC_STAT, "PacketsReceived - Number of packets received", LONG, 0} }; stats peer_retrans_stat[] = { {RETRANS_STAT, "Retransmition Statistics", NONE, 0}, {RETRANS_STAT, "Retransmissions - Number of re-transmitted, from the last 100 packets sent", LONG, 0}, {RETRANS_STAT, "RetransCount - Total number of transmitted packets which were retransmissions", LONG, 0}, {RETRANS_STAT, "RetryCount - Number of Tx packets succeeded after one or more retransmissions", LONG, 0}, {RETRANS_STAT, "MultipleRetryCount - Number of Tx packets succeeded after more than one retransmission", LONG, 0}, {RETRANS_STAT, "FailedRetransCount - Number of Tx packets dropped because of retry limit exceeded", LONG, 0} }; stats tr181_peer_stat[] = { {TR181_PEER_STATS, "TR-181 Device.WiFi.AccessPoint.{i}.AssociatedDevice", NONE, 0}, {TR181_PEER_STATS, "StationID", LONG, 0}, {NETWORK_BITFIELD, "OperatingStandard - Supported network modes", NONE, 0}, {PEER_TRAFFIC_STAT, "Traffic statistics", NONE, 0}, {RETRANS_STAT, "Retransmission statistics", NONE, 0}, {TR181_PEER_STATS, "ErrorsSent - Number of Tx packets not transmitted because of errors", LONG, 0}, {TR181_PEER_STATS, "LastDataDownlinkRate - Last data transmit rate (to peer) [kbps]", LONG, 0}, {TR181_PEER_STATS, "LastDataUplinkRate - Last data receive rate (from peer) [kbps]", LONG, 0}, {TR181_PEER_STATS, "SignalStrength - Radio signal strength of the uplink [dBm]", SLONG, 0} }; stats peer_flow_stats[] = { {PEER_FLOW_STATS, "Peer packets flow statistics", NONE, 0}, {TR181_PEER_STATS, "TR-181 statistics", NONE, 0}, {PEER_FLOW_STATS, "ShortTermRSSI - Short-term RSSI average per antenna [dBm]", SLONGARRAY, 4}, {PEER_FLOW_STATS, "SNR - Signal to Noise ratio per antenna [dB]", SBYTEARRAY, 4}, {PEER_FLOW_STATS, "AirtimeEfficiency - Efficiency of used air time [bytes/sec]", LONG, 0}, {PEER_FLOW_STATS, "AirtimeUsage - Air Time Used by RX/TX to/from STA [%]", BYTE, 0} }; stats peer_rate_info1[] = { {PEER_RATE_INFO1, "Rate info is valid", FLAG, 0}, {PHY_ENUM, "Network (Phy) Mode", NONE, 0}, {PEER_RATE_INFO1, "BW index", SLONG, 0}, {PEER_RATE_INFO1, "BW [MHz]", SLONG, 0}, {PEER_RATE_INFO1, "SGI", SLONG, 0}, {PEER_RATE_INFO1, "MCS index", SLONG, 0}, {PEER_RATE_INFO1, "NSS", SLONG, 0} }; stats peer_rate_info[] = { {PEER_RATE_INFO, "Peer TX/RX info", NONE, 0}, {PEER_RATE_INFO1, "Mgmt uplink rate info", NONE, 0}, {PEER_RATE_INFO, "Last mgmt uplink rate [Mbps]", LONGFRACT, 1}, {PEER_RATE_INFO1, "Data uplink rate info", NONE, 0}, {PEER_RATE_INFO, "Last data uplink rate [Mbps]", LONGFRACT, 1}, {PEER_RATE_INFO1, "Data downlink rate info", NONE, 0}, {PEER_RATE_INFO, "Last data downlink rate [Mbps]", LONGFRACT, 1}, {PEER_RATE_INFO, "Beamforming mode", LONG, 0}, {PEER_RATE_INFO, "STBC mode", LONG, 0}, {PEER_RATE_INFO, "TX power for current rate [dBm]", LONGFRACT, 2}, {PEER_RATE_INFO, "TX management power [dBm]", LONGFRACT, 2} }; stats peer_capability[] = { {PEER_CAPABILITY, "Peer capabilities", NONE, 0}, {NETWORK_BITFIELD, "Supported network modes", NONE, 0}, {PEER_CAPABILITY, "WMM is supported", FLAG, 0}, {PEER_CAPABILITY, "Channel bonding supported", FLAG, 0}, {PEER_CAPABILITY, "SGI20 supported", FLAG, 0}, {PEER_CAPABILITY, "SGI40 supported", FLAG, 0}, {PEER_CAPABILITY, "STBC supported", FLAG, 0}, {PEER_CAPABILITY, "LDPC supported", FLAG, 0}, {PEER_CAPABILITY, "Explicit beam forming supported", FLAG, 0}, {PEER_CAPABILITY, "40MHz intolerant", FLAG, 0}, {VENDOR_ENUM, "Vendor", NONE, 0}, {PEER_CAPABILITY, "Max TX spatial streams", LONG, 0}, {PEER_CAPABILITY, "Max RX spatial streams", LONG, 0}, {PEER_CAPABILITY, "Maximum A-MPDU Length Exponent", LONG, 0}, {PEER_CAPABILITY, "Minimum MPDU Start Spacing", LONG, 0}, {PEER_CAPABILITY, "Timestamp of station association", TIMESTAMP, 0} }; stats recovery_stat[] = { {RECOVERY_STAT, "Recovery statistics", NONE, 0}, {RECOVERY_STAT, "Number of FAST recovery processed successfully", LONG, 0}, {RECOVERY_STAT, "Number of FULL recovery processed successfully", LONG, 0}, {RECOVERY_STAT, "Number of FAST recovery failed", LONG, 0}, {RECOVERY_STAT, "Number of FULL recovery failed", LONG, 0} }; stats hw_txm_stat[] = { {HW_TXM_STAT, "HW TXM Statistics", NONE, 0}, {HW_TXM_STAT, "Number of FW MAN messages sent", LONG, 0}, {HW_TXM_STAT, "Number of FW MAN messages confirmed", LONG, 0}, {HW_TXM_STAT, "Peak number of FW MAN messages sent simultaneously", LONG, 0}, {HW_TXM_STAT, "Number of FW DBG messages sent", LONG, 0}, {HW_TXM_STAT, "Number of FW DBG messages confirmed", LONG, 0}, {HW_TXM_STAT, "Peak number of FW DBG messages sent simultaneously", LONG, 0} }; stats traffic_stats[] = { {TRAFFIC_STATS, "Traffic Statistics", NONE, 0}, {TRAFFIC_STATS, "BytesSent - Number of bytes sent successfully (64-bit)", HUGE, 0}, {TRAFFIC_STATS, "BytesReceived - Number of bytes received (64-bit)", HUGE, 0}, {TRAFFIC_STATS, "PacketsSent - Number of packets transmitted (64-bit)", HUGE, 0}, {TRAFFIC_STATS, "PacketsReceived - Number of packets received (64-bit)", HUGE, 0}, {TRAFFIC_STATS, "UnicastPacketsSent - Number of unicast packets transmitted", LONG, 0}, {TRAFFIC_STATS, "UnicastPacketsReceived - Number of unicast packets received", LONG, 0}, {TRAFFIC_STATS, "MulticastPacketsSent - Number of multicast packets transmitted", LONG, 0}, {TRAFFIC_STATS, "MulticastPacketsReceived - Number of multicast packets received", LONG, 0}, {TRAFFIC_STATS, "BroadcastPacketsSent - Number of broadcast packets transmitted", LONG, 0}, {TRAFFIC_STATS, "BroadcastPacketsReceived - Number of broadcast packets received", LONG, 0} }; stats mgmt_stats[] = { {MGMT_STATS, "Management frames statistics", NONE, 0}, {MGMT_STATS, "Number of management frames in reserved queue", LONG, 0}, {MGMT_STATS, "Number of management frames sent", LONG, 0}, {MGMT_STATS, "Number of management frames confirmed", LONG, 0}, {MGMT_STATS, "Number of management frames received", LONG, 0}, {MGMT_STATS, "Number of management frames dropped due to retries", LONG, 0}, {MGMT_STATS, "Number of management frames dropped due to TX que full", LONG, 0}, {MGMT_STATS, "Number of probe responses sent", LONG,0}, {MGMT_STATS, "Number of probe responses dropped", LONG,0} }; stats hw_flow_status[] = { {RECOVERY_STAT, "HW Recovery Statistics", NONE, 0}, {HW_TXM_STAT, "HW TXM statistics", NONE, 0}, {TRAFFIC_STATS, "Radio Traffic statistics", NONE, 0}, {MGMT_STATS, "Radio MGMT statistics", NONE, 0}, {HW_FLOW_STATUS, "Radars detected", LONG, 0}, {HW_FLOW_STATUS, "Channel Load [%]", BYTE, 0}, {HW_FLOW_STATUS, "Channel Utilization [%]", BYTE, 0}, {HW_FLOW_STATUS, "Total Airtime [%]", BYTE, 0}, {HW_FLOW_STATUS, "Total Airtime Efficiency [bytes/sec]", LONG, 0} }; stats tr181_error_stats[] = { {TR181_ERROR_STATS, "TR-181 Errors", NONE, 0}, {TR181_ERROR_STATS, "ErrorsSent - Number of Tx packets not transmitted because of errors", LONG, 0}, {TR181_ERROR_STATS, "ErrorsReceived - Number of Rx packets that contained errors", LONG, 0}, {TR181_ERROR_STATS, "DiscardPacketsSent - Number of Tx packets discarded", LONG, 0}, {TR181_ERROR_STATS, "DiscardPacketsReceived - Number of Rx packets discarded", LONG, 0} }; stats tr181_wlan_stats[] = { {TR181_WLAN_STATS, "TR-181 Device.WiFi.SSID.{i}.Stats", NONE, 0}, {TRAFFIC_STATS, "Traffic Statistics", NONE, 0}, {TR181_ERROR_STATS, "Erros Statistics", NONE, 0}, {RETRANS_STAT, "Retransmission statistics", NONE, 0}, {TR181_WLAN_STATS, "ACKFailureCount - Number of expected ACKs never received", LONG, 0}, {TR181_WLAN_STATS, "AggregatedPacketCount - Number of aggregated packets transmitted", LONG, 0}, {TR181_WLAN_STATS, "UnknownProtoPacketsReceived - Number of Rx packets unknown or unsupported protocol", LONG, 0} }; stats tr181_hw_stats[] = { {TR181_HW_STATS, "TR-181 Device.WiFi.Radio.{i}.Stats", NONE, 0}, {TRAFFIC_STATS, "Traffic Statistics", NONE, 0}, {TR181_ERROR_STATS, "Erros Statistics", NONE, 0}, {TR181_HW_STATS, "FCSErrorCount - Number of Rx packets with detected FCS error", LONG, 0}, {TR181_HW_STATS, "Noise - Average noise strength received [dBm]", SLONG, 0} }; struct print_struct gStat[] = { {PEER_FLOW_STATS, peer_flow_stats, num_stats(peer_flow_stats)}, {PEER_TRAFFIC_STAT, peer_traffic_stat, num_stats(peer_traffic_stat)}, {RETRANS_STAT, peer_retrans_stat, num_stats(peer_retrans_stat)}, {TR181_PEER_STATS, tr181_peer_stat, num_stats(tr181_peer_stat)}, {NETWORK_BITFIELD, network_bitfield, num_stats(network_bitfield)}, {PEER_CAPABILITY, peer_capability, num_stats(peer_capability)}, {VENDOR_ENUM, vendor_enum, num_stats(vendor_enum)}, {PEER_RATE_INFO, peer_rate_info, num_stats(peer_rate_info)}, {PEER_RATE_INFO1, peer_rate_info1, num_stats(peer_rate_info1)}, {PHY_ENUM, phy_enum, num_stats(phy_enum)}, {RECOVERY_STAT, recovery_stat, num_stats(recovery_stat)}, {HW_TXM_STAT, hw_txm_stat, num_stats(hw_txm_stat)}, {TRAFFIC_STATS, traffic_stats, num_stats(traffic_stats)}, {MGMT_STATS, mgmt_stats, num_stats(mgmt_stats)}, {HW_FLOW_STATUS, hw_flow_status, num_stats(hw_flow_status)}, {TR181_ERROR_STATS, tr181_error_stats, num_stats(tr181_error_stats)}, {TR181_WLAN_STATS, tr181_wlan_stats, num_stats(tr181_wlan_stats)}, {TR181_HW_STATS, tr181_hw_stats, num_stats(tr181_hw_stats)} }; stats_cmd gCmd[] = { {"PeerList", LTQ_NL80211_VENDOR_SUBCMD_GET_PEER_LIST, 1, "usage: dwpal_cli [INTERFACENAME] PeerList",PEER_LIST}, {"PeerFlowStatus", LTQ_NL80211_VENDOR_SUBCMD_GET_PEER_FLOW_STATUS, 2, "usage: dwpal_cli [INTERFACENAME] PeerFlowStatus [MACADDR]", PEER_FLOW_STATS}, {"PeerCapabilities", LTQ_NL80211_VENDOR_SUBCMD_GET_PEER_CAPABILITIES, 2, "usage: dwpal_cli [INTERFACENAME] PeerCapabilities [MACADDR]", PEER_CAPABILITY}, {"PeerRatesInfo", LTQ_NL80211_VENDOR_SUBCMD_GET_PEER_RATE_INFO, 2, "usage: dwpal_cli [INTERFACENAME] PeerRatesInfo [MACADDR]", PEER_RATE_INFO}, {"RecoveryStats", LTQ_NL80211_VENDOR_SUBCMD_GET_RECOVERY_STATS, 1, "usage: dwpal_cli [INTERFACENAME] RecoveryStats", RECOVERY_STAT}, {"HWFlowStatus", LTQ_NL80211_VENDOR_SUBCMD_GET_HW_FLOW_STATUS, 1, "usage: dwpal_cli [INTERFACENAME] HWFlowStatus", HW_FLOW_STATUS}, {"TR181WLANStat", LTQ_NL80211_VENDOR_SUBCMD_GET_TR181_WLAN_STATS, 1, "usage: dwpal_cli [INTERFACENAME] TR181WLANStat", TR181_WLAN_STATS}, {"TR181HWStat", LTQ_NL80211_VENDOR_SUBCMD_GET_TR181_HW_STATS, 1, "usage: dwpal_cli [INTERFACENAME] TR181HWStat", TR181_HW_STATS}, {"TR181PeerStat", LTQ_NL80211_VENDOR_SUBCMD_GET_TR181_PEER_STATS, 2, "usage: dwpal_cli [INTERFACENAME] TR181PeerStat [MACADDR]", TR181_PEER_STATS} }; int check_stats_cmd(int argc,char *argv[]); #endif
42.882521
129
0.687492
b8e092be60dd689ed660485ad6066114cf1b103a
1,246
h
C
src/helpers/ConfigHelper.h
anupam-git/random-wallpaper-cli
d5145dfccb00079ab18723dcd98ef1299c7e0c98
[ "MIT" ]
4
2017-06-28T10:38:13.000Z
2018-04-01T16:57:27.000Z
src/helpers/ConfigHelper.h
anupam-git/random-wallpaper-cli
d5145dfccb00079ab18723dcd98ef1299c7e0c98
[ "MIT" ]
null
null
null
src/helpers/ConfigHelper.h
anupam-git/random-wallpaper-cli
d5145dfccb00079ab18723dcd98ef1299c7e0c98
[ "MIT" ]
null
null
null
#ifndef PARSERS_CONFIGHELPER_H #define PARSERS_CONFIGHELPER_H #include <utils/CommonUtils.h> #include <QObject> #include <QSettings> #include <QMap> #include <QString> #include <QStringList> #include <QStandardPaths> enum class ConfigEnum { DIR, TAGS, RESOLUTION, REFRESH_RATE, DOWNLOAD, WALLPAPER }; class ConfigHelper : public QObject { public: ConfigHelper(QCoreApplication* app, QObject* parent = nullptr); QString get(ConfigEnum key); QStringList getRefreshRate(); void set(ConfigEnum key, QString value); void setWallpaper(QString wallpaper); void save(); private: QCoreApplication* app; CommonUtils* commonUtils; QSettings* settings; /** * Key : ConfigEnum * Value : [Conf Key, Default Value, Should Save to Conf] */ QMap<ConfigEnum, QVariantList> configKeys = { {ConfigEnum::DIR, {"dir", QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), true}}, {ConfigEnum::REFRESH_RATE, {"refresh_rate", "", false}}, {ConfigEnum::RESOLUTION, {"resolution", "1920x1080", true}}, {ConfigEnum::TAGS, {"tags", "", true}}, {ConfigEnum::WALLPAPER, {"wallpaper", "", false}}, }; QMap<ConfigEnum, QString>* configValues; }; #endif
23.074074
74
0.685393
d47cad00f98a12d127c170cd34e38edc91067153
197
h
C
Pods/Target Support Files/Pods-Instagram_StefUITests/Pods-Instagram_StefUITests-umbrella.h
StefanyGo/Instagram_Stef
e9d9f212b43d8fb4e7da8682969bfeb91b3905d4
[ "Apache-2.0" ]
null
null
null
Pods/Target Support Files/Pods-Instagram_StefUITests/Pods-Instagram_StefUITests-umbrella.h
StefanyGo/Instagram_Stef
e9d9f212b43d8fb4e7da8682969bfeb91b3905d4
[ "Apache-2.0" ]
1
2017-03-21T14:51:19.000Z
2017-03-21T14:51:19.000Z
Pods/Target Support Files/Pods-Instagram_StefUITests/Pods-Instagram_StefUITests-umbrella.h
StefanyGo/Instagram_Stef
e9d9f212b43d8fb4e7da8682969bfeb91b3905d4
[ "Apache-2.0" ]
null
null
null
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_Instagram_StefUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Instagram_StefUITestsVersionString[];
21.888889
80
0.862944
770981459982d3b34f72e3da1a97c9df6b0f02a0
15,030
c
C
thirdparty/glut/progs/contrib/steam.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
1
2019-01-11T13:55:53.000Z
2019-01-11T13:55:53.000Z
thirdparty/glut/progs/contrib/steam.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
1
2018-08-10T19:11:58.000Z
2018-08-10T19:12:17.000Z
thirdparty/glut/progs/contrib/steam.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
null
null
null
/** Description: Interactive 3D graphics, Assignment #1 Miniature Steam Engine Simulation. Author: Troy Robinette Date: 29/9/95 Email: troyr@yallara.cs.rmit.edu.au Notes: - Transparence doesn't quite work. The color of the underlying object doesn't show through. - Also only the front side of the transparent objects are transparent. **/ #include <stdio.h> #include <GL/glut.h> #include <math.h> #define TRUE 1 #define FALSE 0 /* Dimensions of texture image. */ #define IMAGE_WIDTH 64 #define IMAGE_HEIGHT 64 /* Step to be taken for each rotation. */ #define ANGLE_STEP 10 /* Magic numbers for relationship b/w cylinder head and crankshaft. */ #define MAGNITUDE 120 #define PHASE 270.112 #define FREQ_DIV 58 #define ARC_LENGHT 2.7 #define ARC_RADIUS 0.15 /* Rotation angles */ GLdouble view_h = 270, view_v = 0, head_angle = 0; GLint crank_angle = 0; /* Crank rotation step. */ GLdouble crank_step = 5; /* Toggles */ GLshort shaded = TRUE, anim = FALSE; GLshort texture = FALSE, transparent = FALSE; GLshort light1 = TRUE, light2 = FALSE; /* Storage for the angle look up table and the texture map */ GLdouble head_look_up_table[361]; GLubyte image[IMAGE_WIDTH][IMAGE_HEIGHT][3]; /* Indentifiers for each Display list */ GLint list_piston_shaded = 1; GLint list_piston_texture = 2; GLint list_flywheel_shaded = 4; GLint list_flywheel_texture = 8; /* Variable used in the creaton of glu objects */ GLUquadricObj *obj; /* Draws a box by scaling a glut cube of size 1. Also checks the shaded toggle to see which rendering style to use. NB Texture doesn't work correctly due to the cube being scaled. */ void myBox(GLdouble x, GLdouble y, GLdouble z) { glPushMatrix(); glScalef(x, y, z); if (shaded) glutSolidCube(1); else glutWireCube(1); glPopMatrix(); } /* Draws a cylinder using glu function, drawing flat disc's at each end, to give the appearence of it being solid. */ void myCylinder(GLUquadricObj * object, GLdouble outerRadius, GLdouble innerRadius, GLdouble lenght) { glPushMatrix(); gluCylinder(object, outerRadius, outerRadius, lenght, 20, 1); glPushMatrix(); glRotatef(180, 0.0, 1.0, 0.0); gluDisk(object, innerRadius, outerRadius, 20, 1); glPopMatrix(); glTranslatef(0.0, 0.0, lenght); gluDisk(object, innerRadius, outerRadius, 20, 1); glPopMatrix(); } /* Draws a piston. */ void draw_piston(void) { glPushMatrix(); glColor4f(0.3, 0.6, 0.9, 1.0); glPushMatrix(); glRotatef(90, 0.0, 1.0, 0.0); glTranslatef(0.0, 0.0, -0.07); myCylinder(obj, 0.125, 0.06, 0.12); glPopMatrix(); glRotatef(-90, 1.0, 0.0, 0.0); glTranslatef(0.0, 0.0, 0.05); myCylinder(obj, 0.06, 0.0, 0.6); glTranslatef(0.0, 0.0, 0.6); myCylinder(obj, 0.2, 0.0, 0.5); glPopMatrix(); } /* Draws the engine pole and the pivot pole for the cylinder head. */ void draw_engine_pole(void) { glPushMatrix(); glColor4f(0.9, 0.9, 0.9, 1.0); myBox(0.5, 3.0, 0.5); glColor3f(0.5, 0.1, 0.5); glRotatef(90, 0.0, 1.0, 0.0); glTranslatef(0.0, 0.9, -0.4); myCylinder(obj, 0.1, 0.0, 2); glPopMatrix(); } /* Draws the cylinder head at the appropreate angle, doing the necesary translations for the rotation. */ void draw_cylinder_head(void) { glPushMatrix(); glColor4f(0.5, 1.0, 0.5, 0.1); glRotatef(90, 1.0, 0.0, 0.0); glTranslatef(0, 0.0, 0.4); glRotatef(head_angle, 1, 0, 0); glTranslatef(0, 0.0, -0.4); myCylinder(obj, 0.23, 0.21, 1.6); glRotatef(180, 1.0, 0.0, 0.0); gluDisk(obj, 0, 0.23, 20, 1); glPopMatrix(); } /* Draws the flywheel. */ void draw_flywheel(void) { glPushMatrix(); glColor4f(0.5, 0.5, 1.0, 1.0); glRotatef(90, 0.0, 1.0, 0.0); myCylinder(obj, 0.625, 0.08, 0.5); glPopMatrix(); } /* Draws the crank bell, and the pivot pin for the piston. Also calls the appropreate display list of a piston doing the nesacary rotations before hand. */ void draw_crankbell(void) { glPushMatrix(); glColor4f(1.0, 0.5, 0.5, 1.0); glRotatef(90, 0.0, 1.0, 0.0); myCylinder(obj, 0.3, 0.08, 0.12); glColor4f(0.5, 0.1, 0.5, 1.0); glTranslatef(0.0, 0.2, 0.0); myCylinder(obj, 0.06, 0.0, 0.34); glTranslatef(0.0, 0.0, 0.22); glRotatef(90, 0.0, 1.0, 0.0); glRotatef(crank_angle - head_angle, 1.0, 0.0, 0.0); if (shaded) { if (texture) glCallList(list_piston_texture); else glCallList(list_piston_shaded); } else draw_piston(); glPopMatrix(); } /* Draws the complete crank. Piston also gets drawn through the crank bell function. */ void draw_crank(void) { glPushMatrix(); glRotatef(crank_angle, 1.0, 0.0, 0.0); glPushMatrix(); glRotatef(90, 0.0, 1.0, 0.0); glTranslatef(0.0, 0.0, -1.0); myCylinder(obj, 0.08, 0.0, 1.4); glPopMatrix(); glPushMatrix(); glTranslatef(0.28, 0.0, 0.0); draw_crankbell(); glPopMatrix(); glPushMatrix(); glTranslatef(-0.77, 0.0, 0.0); if (shaded) { if (texture) glCallList(list_flywheel_texture); else glCallList(list_flywheel_shaded); } else draw_flywheel(); glPopMatrix(); glPopMatrix(); } /* Main display routine. Clears the drawing buffer and if transparency is set, displays the model twice, 1st time accepting those fragments with a ALPHA value of 1 only, then with DEPTH_BUFFER writing disabled for those with other values. */ void display(void) { int pass; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); if (transparent) { glEnable(GL_ALPHA_TEST); pass = 2; } else { glDisable(GL_ALPHA_TEST); pass = 0; } /* Rotate the whole model */ glRotatef(view_h, 0, 1, 0); glRotatef(view_v, 1, 0, 0); do { if (pass == 2) { glAlphaFunc(GL_EQUAL, 1); glDepthMask(GL_TRUE); pass--; } else if (pass != 0) { glAlphaFunc(GL_NOTEQUAL, 1); glDepthMask(GL_FALSE); pass--; } draw_engine_pole(); glPushMatrix(); glTranslatef(0.5, 1.4, 0.0); draw_cylinder_head(); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, -0.8, 0.0); draw_crank(); glPopMatrix(); } while (pass > 0); glDepthMask(GL_TRUE); glutSwapBuffers(); glPopMatrix(); } /* Called when the window is idle. When called increments the crank angle by ANGLE_STEP, updates the head angle and notifies the system that the screen needs to be updated. */ void animation(void) { if ((crank_angle += crank_step) >= 360) crank_angle = 0; head_angle = head_look_up_table[crank_angle]; glutPostRedisplay(); } /* Called when a key is pressed. Checks if it reconises the key and if so acts on it, updateing the screen. */ /* ARGSUSED1 */ void keyboard(unsigned char key, int x, int y) { switch (key) { case 's': if (shaded == FALSE) { shaded = TRUE; glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); gluQuadricNormals(obj, GLU_SMOOTH); gluQuadricDrawStyle(obj, GLU_FILL); } else { shaded = FALSE; glShadeModel(GL_FLAT); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); gluQuadricNormals(obj, GLU_NONE); gluQuadricDrawStyle(obj, GLU_LINE); gluQuadricTexture(obj, GL_FALSE); } if (texture && !shaded); else break; case 't': if (texture == FALSE) { texture = TRUE; glEnable(GL_TEXTURE_2D); gluQuadricTexture(obj, GL_TRUE); } else { texture = FALSE; glDisable(GL_TEXTURE_2D); gluQuadricTexture(obj, GL_FALSE); } break; case 'o': if (transparent == FALSE) { transparent = TRUE; } else { transparent = FALSE; } break; case 'a': if ((crank_angle += crank_step) >= 360) crank_angle = 0; head_angle = head_look_up_table[crank_angle]; break; case 'z': if ((crank_angle -= crank_step) <= 0) crank_angle = 360; head_angle = head_look_up_table[crank_angle]; break; case '0': if (light1) { glDisable(GL_LIGHT0); light1 = FALSE; } else { glEnable(GL_LIGHT0); light1 = TRUE; } break; case '1': if (light2) { glDisable(GL_LIGHT1); light2 = FALSE; } else { glEnable(GL_LIGHT1); light2 = TRUE; } break; case '4': if ((view_h -= ANGLE_STEP) <= 0) view_h = 360; break; case '6': if ((view_h += ANGLE_STEP) >= 360) view_h = 0; break; case '8': if ((view_v += ANGLE_STEP) >= 360) view_v = 0; break; case '2': if ((view_v -= ANGLE_STEP) <= 0) view_v = 360; break; case ' ': if (anim) { glutIdleFunc(0); anim = FALSE; } else { glutIdleFunc(animation); anim = TRUE; } break; case '+': if ((++crank_step) > 45) crank_step = 45; break; case '-': if ((--crank_step) <= 0) crank_step = 0; break; default: return; } glutPostRedisplay(); } /* ARGSUSED1 */ void special(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT: if ((view_h -= ANGLE_STEP) <= 0) view_h = 360; break; case GLUT_KEY_RIGHT: if ((view_h += ANGLE_STEP) >= 360) view_h = 0; break; case GLUT_KEY_UP: if ((view_v += ANGLE_STEP) >= 360) view_v = 0; break; case GLUT_KEY_DOWN: if ((view_v -= ANGLE_STEP) <= 0) view_v = 360; break; default: return; } glutPostRedisplay(); } /* Called when a menu option has been selected. Translates the menu item identifier into a keystroke, then call's the keyboard function. */ void menu(int val) { unsigned char key; switch (val) { case 1: key = 's'; break; case 2: key = ' '; break; case 3: key = 't'; break; case 4: key = 'o'; break; case 5: key = '0'; break; case 6: key = '1'; break; case 7: key = '+'; break; case 8: key = '-'; break; default: return; } keyboard(key, 0, 0); } /* Initialises the menu of toggles. */ void create_menu(void) { glutCreateMenu(menu); glutAttachMenu(GLUT_LEFT_BUTTON); glutAttachMenu(GLUT_RIGHT_BUTTON); glutAddMenuEntry("Shaded", 1); glutAddMenuEntry("Animation", 2); glutAddMenuEntry("Texture", 3); glutAddMenuEntry("Transparency", 4); glutAddMenuEntry("Right Light (0)", 5); glutAddMenuEntry("Left Light (1)", 6); glutAddMenuEntry("Speed UP", 7); glutAddMenuEntry("Slow Down", 8); } /* Makes a simple check pattern image. (Copied from the redbook example "checker.c".) */ void make_image(void) { int i, j, c; for (i = 0; i < IMAGE_WIDTH; i++) { for (j = 0; j < IMAGE_HEIGHT; j++) { c = (((i & 0x8) == 0) ^ ((j & 0x8) == 0)) * 255; image[i][j][0] = (GLubyte) c; image[i][j][1] = (GLubyte) c; image[i][j][2] = (GLubyte) c; } } } /* Makes the head look up table for all possible crank angles. */ void make_table(void) { GLint i; GLdouble k; for (i = 0, k = 0.0; i < 360; i++, k++) { head_look_up_table[i] = MAGNITUDE * atan( (ARC_RADIUS * sin(PHASE - k / FREQ_DIV)) / ((ARC_LENGHT - ARC_RADIUS * cos(PHASE - k / FREQ_DIV)))); } } /* Initialises texturing, lighting, display lists, and everything else associated with the model. */ void myinit(void) { GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat mat_shininess[] = {50.0}; GLfloat light_position1[] = {1.0, 1.0, 1.0, 0.0}; GLfloat light_position2[] = {-1.0, 1.0, 1.0, 0.0}; glClearColor(0.0, 0.0, 0.0, 0.0); obj = gluNewQuadric(); make_table(); make_image(); /* Set up Texturing */ glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 3, IMAGE_WIDTH, IMAGE_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); /* Set up Lighting */ glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position1); glLightfv(GL_LIGHT1, GL_POSITION, light_position2); /* Initial render mode is with full shading and LIGHT 0 enabled. */ glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); /* Initialise display lists */ glNewList(list_piston_shaded, GL_COMPILE); draw_piston(); glEndList(); glNewList(list_flywheel_shaded, GL_COMPILE); draw_flywheel(); glEndList(); gluQuadricTexture(obj, GL_TRUE); glNewList(list_piston_texture, GL_COMPILE); draw_piston(); glEndList(); glNewList(list_flywheel_texture, GL_COMPILE); draw_flywheel(); glEndList(); gluQuadricTexture(obj, GL_FALSE); } /* Called when the model's window has been reshaped. */ void myReshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.0, (GLfloat) w / (GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -5.0); /* viewing transform */ glScalef(1.5, 1.5, 1.5); } /* Main program. An interactive model of a miniture steam engine. Sets system in Double Buffered mode and initialises all the call-back functions. */ int main(int argc, char **argv) { puts("Miniature Steam Engine Troy Robinette\n"); puts("Keypad Arrow keys (with NUM_LOCK on) rotates object."); puts("Rotate crank: 'a' = anti-clock wise 'z' = clock wise"); puts("Crank Speed : '+' = Speed up by 1 '-' = Slow Down by 1"); puts("Toggle : 's' = Shading 't' = Texture"); puts(" : ' ' = Animation 'o' = Transparency"); puts(" : '0' = Right Light '1' = Left Light"); puts(" Alternatively a pop up menu with all toggles is attached"); puts(" to the left mouse button.\n"); glutInitWindowSize(400, 400); glutInit(&argc, argv); /* Transperancy won't work properly without GLUT_ALPHA */ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE); glutCreateWindow("Miniature Steam Engine by Troy Robinette"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutSpecialFunc(special); create_menu(); myinit(); glutReshapeFunc(myReshape); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
24.163987
79
0.626214
ccf06baf32b1e82e319f4b98272c92dc58272384
270
h
C
Example/CHTool/CHAppDelegate.h
coderchou/CHTool
536ec4d5e1a4e9257c405d0c4006bd1f64c01502
[ "MIT" ]
null
null
null
Example/CHTool/CHAppDelegate.h
coderchou/CHTool
536ec4d5e1a4e9257c405d0c4006bd1f64c01502
[ "MIT" ]
null
null
null
Example/CHTool/CHAppDelegate.h
coderchou/CHTool
536ec4d5e1a4e9257c405d0c4006bd1f64c01502
[ "MIT" ]
null
null
null
// // CHAppDelegate.h // CHTool // // Created by coderchou on 03/14/2020. // Copyright (c) 2020 coderchou. All rights reserved. // @import UIKit; @interface CHAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
16.875
62
0.714815
f864eef0ebab078abf6a1a88ed908ea9e2dbe4ea
178
h
C
config.def.h
edvb/nt
604040a64ddfc774acb06636c9e1ab5726997cd3
[ "Zlib" ]
null
null
null
config.def.h
edvb/nt
604040a64ddfc774acb06636c9e1ab5726997cd3
[ "Zlib" ]
null
null
null
config.def.h
edvb/nt
604040a64ddfc774acb06636c9e1ab5726997cd3
[ "Zlib" ]
null
null
null
char *fname = "todo"; /* default notes file name, overridden with -f */ int yes = 0; /* 0: prompt to confirm actions such as delete, 1: no prompt */ const char catdelim = ':';
29.666667
76
0.651685
502e59dcf13b42ebdb9463c7c772f800e4d37e98
12,443
h
C
litter_robot_3_led_sniffer/zigbee_3_0/core/zcl/clusters/Lighting/Source/ColourControl_internal.h
StevenGClinard/litter_robot_3_led_sniffer
c79d20ac658253b320f8f705f833a3b332616c92
[ "BSD-3-Clause" ]
null
null
null
litter_robot_3_led_sniffer/zigbee_3_0/core/zcl/clusters/Lighting/Source/ColourControl_internal.h
StevenGClinard/litter_robot_3_led_sniffer
c79d20ac658253b320f8f705f833a3b332616c92
[ "BSD-3-Clause" ]
null
null
null
litter_robot_3_led_sniffer/zigbee_3_0/core/zcl/clusters/Lighting/Source/ColourControl_internal.h
StevenGClinard/litter_robot_3_led_sniffer
c79d20ac658253b320f8f705f833a3b332616c92
[ "BSD-3-Clause" ]
null
null
null
/* * The Clear BSD License * Copyright 2016-2017 NXP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef COLOUR_CONTROL_INTERNAL_H_INCLUDED #define COLOUR_CONTROL_INTERNAL_H_INCLUDED /*! \file ColourControl_internal.h \brief The internal API for the Colour Control Cluster */ #if defined __cplusplus extern "C" { #endif /****************************************************************************/ /*** Include Files ***/ /****************************************************************************/ #include "jendefs.h" #include "zcl.h" #include "ColourControl.h" /****************************************************************************/ /*** Macro Definitions ***/ /****************************************************************************/ /****************************************************************************/ /*** Type Definitions ***/ /****************************************************************************/ /****************************************************************************/ /*** Exported Functions ***/ /****************************************************************************/ PUBLIC teZCL_Status eCLD_ColourControlCommandHandler( ZPS_tsAfEvent *pZPSevent, tsZCL_EndPointDefinition *psEndPointDefinition, tsZCL_ClusterInstance *psClusterInstance); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveToHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveToHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandStepHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_StepHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveToSaturationCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveToSaturationCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveSaturationCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveSaturationCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandStepSaturationCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_StepSaturationCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveToHueAndSaturationCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveToHueAndSaturationCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveToColourCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveToColourCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveColourCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveColourCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandStepColourCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_StepColourCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandMoveToColourTemperatureCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveToColourTemperatureCommandPayload *psPayload); #if (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_ENHANCE_HUE_SUPPORTED) PUBLIC teZCL_Status eCLD_ColourControlCommandEnhancedMoveToHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_EnhancedMoveToHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandEnhancedMoveHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_EnhancedMoveHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandEnhancedStepHueCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_EnhancedStepHueCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandEnhancedMoveToHueAndSaturationCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_EnhancedMoveToHueAndSaturationCommandPayload *psPayload); #endif //#if (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_ENHANCE_HUE_SUPPORTED) #if (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_COLOUR_LOOP_SUPPORTED) PUBLIC teZCL_Status eCLD_ColourControlCommandColourLoopSetCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_ColourLoopSetCommandPayload *psPayload); #endif #if ((CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_HUE_SATURATION_SUPPORTED) ||\ (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_ENHANCE_HUE_SUPPORTED) ||\ (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_XY_SUPPORTED) ||\ (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_COLOUR_TEMPERATURE_SUPPORTED)) PUBLIC teZCL_Status eCLD_ColourControlCommandStopMoveStepCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_StopMoveStepCommandPayload *psPayload); #endif #if (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_COLOUR_TEMPERATURE_SUPPORTED) PUBLIC teZCL_Status eCLD_ColourControlCommandMoveColourTemperatureCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_MoveColourTemperatureCommandPayload *psPayload); PUBLIC teZCL_Status eCLD_ColourControlCommandStepColourTemperatureCommandReceive( ZPS_tsAfEvent *pZPSevent, uint8 *pu8TransactionSequenceNumber, tsCLD_ColourControl_StepColourTemperatureCommandPayload *psPayload); #endif //#if (CLD_COLOURCONTROL_COLOUR_CAPABILITIES & COLOUR_CAPABILITY_COLOUR_TEMPERATURE_SUPPORTED) PUBLIC teZCL_Status eCLD_ColourControlUpdate(uint8 u8SourceEndPointId); PUBLIC teZCL_Status eCLD_ColourControl_HSV2xyY( uint8 u8SourceEndPointId, uint16 u16Hue, uint8 u8Saturation, uint8 u8Value, uint16 *pu16x, uint16 *pu16y, uint8 *pu8Y); PUBLIC teZCL_Status eCLD_ColourControl_xyY2HSV( tsCLD_ColourControlCustomDataStructure *psCustomDataStructPtr, uint16 u16x, uint16 u16y, uint8 u8Y, uint16 *pu16Hue, uint8 *pu8Saturation, uint8 *pu8Value); PUBLIC void vCLD_ColourControl_CCT2xyY( uint16 u16ColourTemperatureMired, uint16 *pu16x, uint16 *pu16y, uint8 *pu8Y); PUBLIC void vCLD_ColourControl_xyY2CCT( uint16 u16x, uint16 u16y, uint8 u8Y, uint16 *pu16ColourTemperature); PUBLIC teZCL_Status eCLD_ColourControlCalculateConversionMatrices( tsCLD_ColourControlCustomDataStructure *psCustomDataStructure, float fRedX, float fRedY, float fGreenX, float fGreenY, float fBlueX, float fBlueY, float fWhiteX, float fWhiteY); PUBLIC bool_t CS_bTransitionIsValid(uint16 u16X1, uint16 u16Y1, uint16 u16X2, uint16 u16Y2, uint16 *pu16X, uint16 *pu16Y); /****************************************************************************/ /*** Exported Variables ***/ /****************************************************************************/ #if defined __cplusplus } #endif #endif /* COLOUR_CONTROL_INTERNAL_H_INCLUDED */ /****************************************************************************/ /*** END OF FILE ***/ /****************************************************************************/
51.630705
101
0.562806
1338e5cc2c49a1d016e023b109f90a848b9fd577
2,269
h
C
PrivateFrameworks/Safari/ReaderContainerViewController.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/Safari/ReaderContainerViewController.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/Safari/ReaderContainerViewController.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSViewController.h" @class NSColor, NSView, ReaderContainerView, ReaderViewController; __attribute__((visibility("hidden"))) @interface ReaderContainerViewController : NSViewController { NSView *_backgroundView; double _amountOfContinuousReadingViewBannerThatIsVisible; long long _animationState; BOOL _deactivationIsAnimated; long long _theme; ReaderViewController *_readerViewController; CDUnknownBlockType _deactivationAnimationDidFinishBlock; } + (id)_animationWithKeyPath:(id)arg1; + (id)_moveAnimationWithStartingRect:(struct CGRect)arg1 endingRect:(struct CGRect)arg2; + (id)_fadeAnimationWithStartingOpacity:(double)arg1 endingOpacity:(double)arg2; @property(copy) CDUnknownBlockType deactivationAnimationDidFinishBlock; // @synthesize deactivationAnimationDidFinishBlock=_deactivationAnimationDidFinishBlock; @property(retain, nonatomic) ReaderViewController *readerViewController; // @synthesize readerViewController=_readerViewController; @property(nonatomic) long long theme; // @synthesize theme=_theme; - (void).cxx_destruct; @property(readonly) NSColor *backgroundColor; - (struct CGRect)_frameBelowTheViewFrame; - (double)_currentBackgroundViewOpacity; - (struct CGRect)_readerWKViewFrameForStartOfAnimationWhenInterruptingExistingAnimation; - (void)_updateReaderWKViewFromFrame:(struct CGRect)arg1 toFrame:(struct CGRect)arg2 backgroundViewFromOpacity:(double)arg3 toOpacity:(double)arg4 animated:(BOOL)arg5 completionHandler:(CDUnknownBlockType)arg6; - (void)finishAsynchronousDeactivation; - (void)deactivateWithAnimation:(BOOL)arg1 completionBlock:(CDUnknownBlockType)arg2; - (void)_didReplaceReaderViewController:(id)arg1; @property(readonly, getter=isAnimatingDeactivation) BOOL animatingDeactivation; @property(readonly, getter=isAnimatingActivation) BOOL animatingActivation; - (void)activateWithAnimation:(BOOL)arg1 verticalScrollOffsetOfBrowserPage:(double)arg2 completionBlock:(CDUnknownBlockType)arg3; - (void)viewDidDisappear; - (void)viewDidLoad; - (void)loadView; // Remaining properties @property(retain) ReaderContainerView *view; // @dynamic view; @end
45.38
210
0.821507
929be6fe52f6077bf4f173d7419d9e2cd3d9fc67
1,592
h
C
EBDownload.h
lassomedia/EBDownloadCaching
a0f7448051c3310950f19bbe534574286f590590
[ "MIT" ]
null
null
null
EBDownload.h
lassomedia/EBDownloadCaching
a0f7448051c3310950f19bbe534574286f590590
[ "MIT" ]
null
null
null
EBDownload.h
lassomedia/EBDownloadCaching
a0f7448051c3310950f19bbe534574286f590590
[ "MIT" ]
null
null
null
#import <Foundation/Foundation.h> @class EBDownload; typedef enum : NSUInteger { EBDownloadStateIdle, /* Transient (changes upon call to -start) */ EBDownloadStateActive, /* Transient (changes when the download finishes successfully, fails, or is invalidated) */ EBDownloadStateSucceeded, /* Permanent, data != nil */ EBDownloadStateFailed, /* Permanent, data == nil */ EBDownloadStateCancelled /* Permanent, data == nil; occurs when download is invalidated while in the Active state */ } EBDownloadState; typedef void (^EBDownloadHandler)(EBDownload *download); @interface EBDownload : NSObject /* ## Creation */ /* Designated initializer; -start must be called to initiate the download. */ - (id)initWithURL: (NSURL *)url handler: (EBDownloadHandler)handler; /* Convenience wrapper -- calls -initWithURL:handler:, followed by -start. */ + (id)downloadURL: (NSURL *)url handler: (EBDownloadHandler)handler; /* ## Properties */ @property(readonly) NSURL *url; @property(readonly) EBDownloadHandler handler; @property(readonly) EBDownloadState state; @property(readonly) NSData *data; /* Non-nil if state == Succeeded, nil otherwise. */ @property(readonly) BOOL valid; /* NO if -invalidate has been called, otherwise YES. */ /* ## Methods */ /* If -start is called, the handler block is guaranteed to be called. */ - (void)start; /* Simply sets the receiver's `valid` property to NO. If the receiver notices the invalidation before the download is complete, the receiver's state will transition to Cancelled. */ - (void)invalidate; @end
37.904762
123
0.72299
59aafd0cda2c9a071393be1d03d988d783850d95
2,701
h
C
MarkupsToModel/qSlicerMarkupsToModelModuleWidget.h
Sunderlandkyl/SlicerMarkupsToModel
632fc6ef2c7a4c25987b6e8f8b9da9249280bd3d
[ "BSD-3-Clause" ]
null
null
null
MarkupsToModel/qSlicerMarkupsToModelModuleWidget.h
Sunderlandkyl/SlicerMarkupsToModel
632fc6ef2c7a4c25987b6e8f8b9da9249280bd3d
[ "BSD-3-Clause" ]
null
null
null
MarkupsToModel/qSlicerMarkupsToModelModuleWidget.h
Sunderlandkyl/SlicerMarkupsToModel
632fc6ef2c7a4c25987b6e8f8b9da9249280bd3d
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================== Program: 3D Slicer Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef __qSlicerMarkupsToModelModuleWidget_h #define __qSlicerMarkupsToModelModuleWidget_h // Slicer MRML includes #include "vtkMRMLModelNode.h" #include "vtkMRMLMarkupsFiducialNode.h" #include "vtkMRMLModelDisplayNode.h" #include "vtkMRMLMarkupsDisplayNode.h" #include "vtkMRMLMarkupsToModelNode.h" // SlicerQt includes #include "qSlicerAbstractModuleWidget.h" #include "qSlicerMarkupsToModelModuleExport.h" class qSlicerMarkupsToModelModuleWidgetPrivate; class vtkMRMLNode; /// \ingroup Slicer_QtModules_ExtensionTemplate class Q_SLICER_QTMODULES_MARKUPSTOMODEL_EXPORT qSlicerMarkupsToModelModuleWidget : public qSlicerAbstractModuleWidget { Q_OBJECT public: typedef qSlicerAbstractModuleWidget Superclass; qSlicerMarkupsToModelModuleWidget(QWidget *parent=0); virtual ~qSlicerMarkupsToModelModuleWidget(); public slots: void setMRMLScene( vtkMRMLScene* scene ); protected slots: void onUpdateButtonClicked(); void onUpdateButtonCheckboxToggled(bool); void onMarkupsToModelNodeSelectionChanged(); void onOutputModelComboBoxSelectionChanged(vtkMRMLNode*); void onOutputModelComboBoxNodeAdded(vtkMRMLNode*); void onInputNodeComboBoxSelectionChanged(vtkMRMLNode*); void onInputNodeComboBoxNodeAdded(vtkMRMLNode*); void onSceneImportedEvent(); void updateMRMLFromGUI(); void updateGUIFromMRML(); void blockAllSignals(bool block); void enableAllWidgets(bool enable); void UpdateOutputModel(); protected: QScopedPointer<qSlicerMarkupsToModelModuleWidgetPrivate> d_ptr; virtual void setup(); virtual void enter(); virtual void exit(); // functions for manipulating other MRML nodes vtkMRMLModelNode* GetOutputModelNode(); vtkMRMLNode* GetInputNode(); bool GetOutputIntersectionVisibility(); bool GetOutputVisibility(); double GetOutputOpacity(); void GetOutputColor( double outputColor[ 3 ] ); double GetMarkupsTextScale(); private: Q_DECLARE_PRIVATE(qSlicerMarkupsToModelModuleWidget); Q_DISABLE_COPY(qSlicerMarkupsToModelModuleWidget); }; #endif
28.431579
82
0.76157
daa7e628128da0c6d63629b00199cf3480a0415a
1,645
h
C
src/game/luamap.h
MJavad/teeworlds
f3f48e294cdda1b0830ae4af2e3493a2404719ae
[ "Zlib" ]
1
2016-02-07T00:09:31.000Z
2016-02-07T00:09:31.000Z
src/game/luamap.h
MJavad/teeworlds
f3f48e294cdda1b0830ae4af2e3493a2404719ae
[ "Zlib" ]
null
null
null
src/game/luamap.h
MJavad/teeworlds
f3f48e294cdda1b0830ae4af2e3493a2404719ae
[ "Zlib" ]
null
null
null
#ifndef GAME_LUAMAP_H #define GAME_LUAMAP_H #include <game/luaevent.h> #include <game/mapitems.h> #include <base/tl/array.h> extern "C" { // lua #define LUA_CORE /* make sure that we don't try to import these functions */ #include <engine/external/lua/lua.h> #include <engine/external/lua/lualib.h> /* luaL_openlibs */ #include <engine/external/lua/lauxlib.h> /* luaL_loadfile */ } class CLuaMapFile { int StrIsInteger(const char *pStr); int StrIsFloat(const char *pStr); bool FunctionExist(const char *pFunctionName); int FunctionExec(const char *pFunctionName = 0); void FunctionPrepare(const char *pFunctionName); void PushString(const char *pString); void PushData(const char *pData, int Size); void PushInteger(int value); void PushFloat(float value); void PushBoolean(bool value); void PushParameter(const char *pString); int m_FunctionVarNum; public: CLuaMapFile(CTile *pTiles, const char *pCode, int Width, int Height); ~CLuaMapFile(); CTile *m_pTiles; int m_Width; int m_Height; lua_State *m_pLua; void Tick(int ServerTick); static int ErrorFunc(lua_State *L); static int GetTile(lua_State *L); static int SetTile(lua_State *L); static int GetFlag(lua_State *L); static int SetFlag(lua_State *L); static int GetWidth(lua_State *L); static int GetHeight(lua_State *L); }; class CLuaMap { public: CLuaMap(); ~CLuaMap(); void Tick(int ServerTick, CTile *pTiles = 0); void Clear(); array<CLuaMapFile *> m_lLuaMapFiles; class CLuaEventListener<CLuaMapFile> *m_pEventListener; }; #endif
25.703125
80
0.692401
97b4e8bb4ca6d0c46159a67658d5c11f589a60f1
121
h
C
SourceCode/DataStructs/Sources/Array.h
Language-C/DataStructs
45fe560e956fb44700c2ef19a99367524af44120
[ "MIT" ]
null
null
null
SourceCode/DataStructs/Sources/Array.h
Language-C/DataStructs
45fe560e956fb44700c2ef19a99367524af44120
[ "MIT" ]
null
null
null
SourceCode/DataStructs/Sources/Array.h
Language-C/DataStructs
45fe560e956fb44700c2ef19a99367524af44120
[ "MIT" ]
null
null
null
#pragma once #include "Array/Array.h" #ifndef WANT_TO_EXTEND_ARRAY typedef void Array; #endif // !WANT_TO_EXTEND_ARRAY
15.125
31
0.785124
97eb227a673ebaf59ad134bd785f6dd083036d8a
1,333
h
C
Bomberman_SDL/Core/Math/Coordinate.h
hovhannest/Bomberman_SDL
8c8680144987471beba47b79afca3980c01a11da
[ "MIT" ]
null
null
null
Bomberman_SDL/Core/Math/Coordinate.h
hovhannest/Bomberman_SDL
8c8680144987471beba47b79afca3980c01a11da
[ "MIT" ]
null
null
null
Bomberman_SDL/Core/Math/Coordinate.h
hovhannest/Bomberman_SDL
8c8680144987471beba47b79afca3980c01a11da
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <string> namespace Bomberman { struct Coordinate { Coordinate(); Coordinate(int val); Coordinate(int i, int j); int i, j; Coordinate absolute() const; Coordinate left() const; Coordinate right() const; Coordinate up() const; Coordinate down() const; Coordinate leftUp() const; Coordinate rightUp() const; Coordinate leftDown() const; Coordinate rightDown() const; Coordinate canonize() const; std::array<Coordinate, 4> cross() const; std::array<Coordinate, 8> adjacents() const; bool operator==(Coordinate other) const; bool operator!=(Coordinate other) const; Coordinate& operator+=(Coordinate other); Coordinate& operator-=(Coordinate other); Coordinate& operator*=(Coordinate other); Coordinate& operator/=(Coordinate other); std::string toString() const; static const Coordinate ZERO; static const Coordinate ONE; static const Coordinate RIGHT; static const Coordinate LEFT; static const Coordinate UP; static const Coordinate DOWN; }; Coordinate operator-(Coordinate coordinate); Coordinate operator+(Coordinate left, Coordinate right); Coordinate operator-(Coordinate left, Coordinate right); Coordinate operator*(Coordinate left, Coordinate right); Coordinate operator/(Coordinate left, Coordinate right); }
23.803571
57
0.737434
eefa6e1868f95a6ce405bd08cda741b8439564be
2,096
c
C
subprojects/d2tk/src/base_table.c
falkTX/notes.lv2
de1966b105fcd1fe4b9880b54ecc6c420e7bb5e0
[ "Artistic-2.0" ]
31
2015-04-03T05:17:59.000Z
2021-10-29T22:47:57.000Z
subprojects/d2tk/src/base_table.c
falkTX/notes.lv2
de1966b105fcd1fe4b9880b54ecc6c420e7bb5e0
[ "Artistic-2.0" ]
57
2015-09-26T09:19:59.000Z
2022-03-17T23:03:12.000Z
subprojects/d2tk/src/base_table.c
OpenMusicKontrollers/mephisto.lv2
99930c620165c853645f8f696add36592240442d
[ "Artistic-2.0" ]
3
2015-09-25T08:51:06.000Z
2020-07-04T09:58:57.000Z
/* * Copyright (c) 2018-2019 Hanspeter Portner (dev@open-music-kontrollers.ch) * * This is free software: you can redistribute it and/or modify * it under the terms of the Artistic License 2.0 as published by * The Perl Foundation. * * This source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Artistic License 2.0 for more details. * * You should have received a copy of the Artistic License 2.0 * along the source as a COPYING file. If not, obtain it from * http://www.perlfoundation.org/artistic_license_2_0. */ #include "base_internal.h" struct _d2tk_table_t { unsigned x; unsigned y; unsigned N; unsigned NM; unsigned k; unsigned x0; d2tk_rect_t rect; }; const size_t d2tk_table_sz = sizeof(d2tk_table_t); D2TK_API d2tk_table_t * d2tk_table_begin(const d2tk_rect_t *rect, unsigned N, unsigned M, d2tk_flag_t flag, d2tk_table_t *tab) { if( (N == 0) || (M == 0) ) { return NULL; } unsigned w; unsigned h; tab->x = 0; tab->y = 0; tab->k = 0; tab->x0 = rect->x; if(flag & D2TK_FLAG_TABLE_REL) { w = rect->w / N; h = rect->h / M; } else { w = N; h = M; N = rect->w / N; M = rect->h / M; } tab->N = N; tab->NM = N*M; tab->rect.x = rect->x; tab->rect.y = rect->y; tab->rect.w = w; tab->rect.h = h; return tab; } D2TK_API bool d2tk_table_not_end(d2tk_table_t *tab) { return tab && (tab->k < tab->NM); } D2TK_API d2tk_table_t * d2tk_table_next(d2tk_table_t *tab) { ++tab->k; if(++tab->x % tab->N) { tab->rect.x += tab->rect.w; } else // overflow { tab->x = 0; ++tab->y; tab->rect.x = tab->x0; tab->rect.y += tab->rect.h; } return tab; } D2TK_API unsigned d2tk_table_get_index(d2tk_table_t *tab) { return tab->k; } D2TK_API unsigned d2tk_table_get_index_x(d2tk_table_t *tab) { return tab->x; } D2TK_API unsigned d2tk_table_get_index_y(d2tk_table_t *tab) { return tab->y; } D2TK_API const d2tk_rect_t * d2tk_table_get_rect(d2tk_table_t *tab) { return &tab->rect; }
16.903226
76
0.666985
f51b4380974dab6c9e874329f7fa03063a8a106f
9,102
h
C
external/sce_vectormath/include/vectormath/spu/c/quat_soa_v.h
JoJo2nd/hart
c689649810a9e94290004ebe78483ec105b4bff5
[ "Zlib" ]
null
null
null
external/sce_vectormath/include/vectormath/spu/c/quat_soa_v.h
JoJo2nd/hart
c689649810a9e94290004ebe78483ec105b4bff5
[ "Zlib" ]
null
null
null
external/sce_vectormath/include/vectormath/spu/c/quat_soa_v.h
JoJo2nd/hart
c689649810a9e94290004ebe78483ec105b4bff5
[ "Zlib" ]
null
null
null
/* Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Sony Computer Entertainment Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _VECTORMATH_QUAT_SOA_V_C_H #define _VECTORMATH_QUAT_SOA_V_C_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /*----------------------------------------------------------------------------- * Definitions */ #ifndef _VECTORMATH_INTERNAL_FUNCTIONS #define _VECTORMATH_INTERNAL_FUNCTIONS #endif static inline VmathSoaQuat vmathSoaQMakeFromElems_V( vec_float4 _x, vec_float4 _y, vec_float4 _z, vec_float4 _w ) { VmathSoaQuat result; vmathSoaQMakeFromElems(&result, _x, _y, _z, _w); return result; } static inline VmathSoaQuat vmathSoaQMakeFromV3Scalar_V( VmathSoaVector3 xyz, vec_float4 _w ) { VmathSoaQuat result; vmathSoaQMakeFromV3Scalar(&result, &xyz, _w); return result; } static inline VmathSoaQuat vmathSoaQMakeFromV4_V( VmathSoaVector4 vec ) { VmathSoaQuat result; vmathSoaQMakeFromV4(&result, &vec); return result; } static inline VmathSoaQuat vmathSoaQMakeFromScalar_V( vec_float4 scalar ) { VmathSoaQuat result; vmathSoaQMakeFromScalar(&result, scalar); return result; } static inline VmathSoaQuat vmathSoaQMakeFromAos_V( VmathQuat quat ) { VmathSoaQuat result; vmathSoaQMakeFromAos(&result, &quat); return result; } static inline VmathSoaQuat vmathSoaQMakeFrom4Aos_V( VmathQuat quat0, VmathQuat quat1, VmathQuat quat2, VmathQuat quat3 ) { VmathSoaQuat result; vmathSoaQMakeFrom4Aos(&result, &quat0, &quat1, &quat2, &quat3); return result; } static inline VmathSoaQuat vmathSoaQMakeIdentity_V( ) { VmathSoaQuat result; vmathSoaQMakeIdentity(&result); return result; } static inline VmathSoaQuat vmathSoaQLerp_V( vec_float4 t, VmathSoaQuat quat0, VmathSoaQuat quat1 ) { VmathSoaQuat result; vmathSoaQLerp(&result, t, &quat0, &quat1); return result; } static inline VmathSoaQuat vmathSoaQSlerp_V( vec_float4 t, VmathSoaQuat unitQuat0, VmathSoaQuat unitQuat1 ) { VmathSoaQuat result; vmathSoaQSlerp(&result, t, &unitQuat0, &unitQuat1); return result; } static inline VmathSoaQuat vmathSoaQSquad_V( vec_float4 t, VmathSoaQuat unitQuat0, VmathSoaQuat unitQuat1, VmathSoaQuat unitQuat2, VmathSoaQuat unitQuat3 ) { VmathSoaQuat result; vmathSoaQSquad(&result, t, &unitQuat0, &unitQuat1, &unitQuat2, &unitQuat3); return result; } static inline void vmathSoaQGet4Aos_V( VmathSoaQuat quat, VmathQuat *result0, VmathQuat *result1, VmathQuat *result2, VmathQuat *result3 ) { vmathSoaQGet4Aos(&quat, result0, result1, result2, result3); } static inline void vmathSoaQSetXYZ_V( VmathSoaQuat *result, VmathSoaVector3 vec ) { vmathSoaQSetXYZ(result, &vec); } static inline VmathSoaVector3 vmathSoaQGetXYZ_V( VmathSoaQuat quat ) { VmathSoaVector3 result; vmathSoaQGetXYZ(&result, &quat); return result; } static inline void vmathSoaQSetX_V( VmathSoaQuat *result, vec_float4 _x ) { vmathSoaQSetX(result, _x); } static inline vec_float4 vmathSoaQGetX_V( VmathSoaQuat quat ) { return vmathSoaQGetX(&quat); } static inline void vmathSoaQSetY_V( VmathSoaQuat *result, vec_float4 _y ) { vmathSoaQSetY(result, _y); } static inline vec_float4 vmathSoaQGetY_V( VmathSoaQuat quat ) { return vmathSoaQGetY(&quat); } static inline void vmathSoaQSetZ_V( VmathSoaQuat *result, vec_float4 _z ) { vmathSoaQSetZ(result, _z); } static inline vec_float4 vmathSoaQGetZ_V( VmathSoaQuat quat ) { return vmathSoaQGetZ(&quat); } static inline void vmathSoaQSetW_V( VmathSoaQuat *result, vec_float4 _w ) { vmathSoaQSetW(result, _w); } static inline vec_float4 vmathSoaQGetW_V( VmathSoaQuat quat ) { return vmathSoaQGetW(&quat); } static inline void vmathSoaQSetElem_V( VmathSoaQuat *result, int idx, vec_float4 value ) { vmathSoaQSetElem(result, idx, value); } static inline vec_float4 vmathSoaQGetElem_V( VmathSoaQuat quat, int idx ) { return vmathSoaQGetElem(&quat, idx); } static inline VmathSoaQuat vmathSoaQAdd_V( VmathSoaQuat quat0, VmathSoaQuat quat1 ) { VmathSoaQuat result; vmathSoaQAdd(&result, &quat0, &quat1); return result; } static inline VmathSoaQuat vmathSoaQSub_V( VmathSoaQuat quat0, VmathSoaQuat quat1 ) { VmathSoaQuat result; vmathSoaQSub(&result, &quat0, &quat1); return result; } static inline VmathSoaQuat vmathSoaQScalarMul_V( VmathSoaQuat quat, vec_float4 scalar ) { VmathSoaQuat result; vmathSoaQScalarMul(&result, &quat, scalar); return result; } static inline VmathSoaQuat vmathSoaQScalarDiv_V( VmathSoaQuat quat, vec_float4 scalar ) { VmathSoaQuat result; vmathSoaQScalarDiv(&result, &quat, scalar); return result; } static inline VmathSoaQuat vmathSoaQNeg_V( VmathSoaQuat quat ) { VmathSoaQuat result; vmathSoaQNeg(&result, &quat); return result; } static inline vec_float4 vmathSoaQDot_V( VmathSoaQuat quat0, VmathSoaQuat quat1 ) { return vmathSoaQDot(&quat0, &quat1); } static inline vec_float4 vmathSoaQNorm_V( VmathSoaQuat quat ) { return vmathSoaQNorm(&quat); } static inline vec_float4 vmathSoaQLength_V( VmathSoaQuat quat ) { return vmathSoaQLength(&quat); } static inline VmathSoaQuat vmathSoaQNormalize_V( VmathSoaQuat quat ) { VmathSoaQuat result; vmathSoaQNormalize(&result, &quat); return result; } static inline VmathSoaQuat vmathSoaQMakeRotationArc_V( VmathSoaVector3 unitVec0, VmathSoaVector3 unitVec1 ) { VmathSoaQuat result; vmathSoaQMakeRotationArc(&result, &unitVec0, &unitVec1); return result; } static inline VmathSoaQuat vmathSoaQMakeRotationAxis_V( vec_float4 radians, VmathSoaVector3 unitVec ) { VmathSoaQuat result; vmathSoaQMakeRotationAxis(&result, radians, &unitVec); return result; } static inline VmathSoaQuat vmathSoaQMakeRotationX_V( vec_float4 radians ) { VmathSoaQuat result; vmathSoaQMakeRotationX(&result, radians); return result; } static inline VmathSoaQuat vmathSoaQMakeRotationY_V( vec_float4 radians ) { VmathSoaQuat result; vmathSoaQMakeRotationY(&result, radians); return result; } static inline VmathSoaQuat vmathSoaQMakeRotationZ_V( vec_float4 radians ) { VmathSoaQuat result; vmathSoaQMakeRotationZ(&result, radians); return result; } static inline VmathSoaQuat vmathSoaQMul_V( VmathSoaQuat quat0, VmathSoaQuat quat1 ) { VmathSoaQuat result; vmathSoaQMul(&result, &quat0, &quat1); return result; } static inline VmathSoaVector3 vmathSoaQRotate_V( VmathSoaQuat quat, VmathSoaVector3 vec ) { VmathSoaVector3 result; vmathSoaQRotate(&result, &quat, &vec); return result; } static inline VmathSoaQuat vmathSoaQConj_V( VmathSoaQuat quat ) { VmathSoaQuat result; vmathSoaQConj(&result, &quat); return result; } static inline VmathSoaQuat vmathSoaQSelect_V( VmathSoaQuat quat0, VmathSoaQuat quat1, vec_uint4 select1 ) { VmathSoaQuat result; vmathSoaQSelect(&result, &quat0, &quat1, select1); return result; } #ifdef _VECTORMATH_DEBUG static inline void vmathSoaQPrint_V( VmathSoaQuat quat ) { vmathSoaQPrint(&quat); } static inline void vmathSoaQPrints_V( VmathSoaQuat quat, const char *name ) { vmathSoaQPrints(&quat, name); } #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif
28.44375
156
0.727203
1057447f6c3ccfc0ccdadd9506311f5464389469
459
h
C
Classes/LYTFoundation/LYTCategore/LYTCategore.h
71sino/LYTSDK
b3da6a7d4d22a07934a4ee60207bebdcd8b97427
[ "MIT" ]
2
2018-01-17T00:40:39.000Z
2018-01-17T08:15:44.000Z
Classes/LYTFoundation/LYTCategore/LYTCategore.h
71sino/LYTSDK
b3da6a7d4d22a07934a4ee60207bebdcd8b97427
[ "MIT" ]
null
null
null
Classes/LYTFoundation/LYTCategore/LYTCategore.h
71sino/LYTSDK
b3da6a7d4d22a07934a4ee60207bebdcd8b97427
[ "MIT" ]
null
null
null
// // LYTCategore.h // LYTDemo // // Created by Shangen Zhang on 2017/8/17. // Copyright © 2017 深圳柒壹思诺科技有限公司. All rights reserved. // #ifndef LYTCategore_h #define LYTCategore_h #import "NSArray+LYTArrayFormSet.h" #import "NSMutableArray+LYTAddObject.h" #import "NSMutableDictionary+LYTSetObjc.h" #import "NSObject+LYTSelector.h" #import "NSString+LYTHash.h" #import "NSString+LYTRegex.h" #import "NSString+LYTRemoveSprit.h" #endif /* LYTCategore_h */
21.857143
55
0.751634
672eabbbebb40b13a78a3048442ddaad27c57334
454
h
C
Example/Pods/Target Support Files/TDFBaseInfoKit/TDFBaseInfoKit-umbrella.h
ny8080/MyRootOutSource
65b227b7ca3116ec0e437741888a88cd4ce741e1
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/TDFBaseInfoKit/TDFBaseInfoKit-umbrella.h
ny8080/MyRootOutSource
65b227b7ca3116ec0e437741888a88cd4ce741e1
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/TDFBaseInfoKit/TDFBaseInfoKit-umbrella.h
ny8080/MyRootOutSource
65b227b7ca3116ec0e437741888a88cd4ce741e1
[ "MIT" ]
null
null
null
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "TDFAppConfigurationMacro.h" #import "TDFBaseInfoDefaults.h" #import "TDFBaseInfoKit.h" #import "TDFProjectNetworkingMacro.h" FOUNDATION_EXPORT double TDFBaseInfoKitVersionNumber; FOUNDATION_EXPORT const unsigned char TDFBaseInfoKitVersionString[];
21.619048
68
0.828194
e56b9bf0eb29493a2ae967c07249b0216297cdaf
3,322
c
C
lib-src/libnyquist/nyquist/cmt/tempomap.c
Marcusz97/CILP_Facilitatore_Audacity
fe7f59365317ce425abbaa79c973e931232c8680
[ "CC-BY-3.0" ]
24
2015-01-22T13:55:17.000Z
2021-06-25T09:41:19.000Z
lib-src/libnyquist/nyquist/cmt/tempomap.c
Marcusz97/CILP_Facilitatore_Audacity
fe7f59365317ce425abbaa79c973e931232c8680
[ "CC-BY-3.0" ]
5
2016-05-22T17:44:06.000Z
2021-07-07T08:25:04.000Z
lib-src/libnyquist/nyquist/cmt/tempomap.c
Marcusz97/CILP_Facilitatore_Audacity
fe7f59365317ce425abbaa79c973e931232c8680
[ "CC-BY-3.0" ]
14
2015-01-12T23:13:35.000Z
2021-01-16T09:02:41.000Z
/* tempomap.c -- used by midifile reader to record and lookup time maps */ /* * This module is designed to provide tempo change list insert and * lookup facilities. The exact interpretation of beat and tempo are * defined in one function, elapsed_time, which takes a tempo and a * number of beats, and returns time. */ #include "cext.h" #include "midifns.h" #include "timebase.h" #include "moxc.h" #include "seq.h" #include "tempomap.h" static time_type elapsed_time(); /* tempomap_create -- create a tempomap */ /**/ tempomap_type tempomap_create() { tempochange_type tempochange = tempochange_alloc(); tempomap_type tempomap = tempomap_alloc(); tempomap->hint = tempomap->entries = tempochange; tempochange->beat = 0L; /* default tempo is 120 (= 50000microsec/beat) and 24 divisions/quarter */ /* this may be overridden by a tempomap_insert */ tempochange->tempo = 500000L / 24; tempochange->rtime = 0L; tempochange->next = NULL; return tempomap; } /* tempomap_free -- deallocate storage for tempo map */ /**/ void tempomap_free(tm) tempomap_type tm; { while (tm->entries) { tempochange_type tc = tm->entries; tm->entries = tc->next; tempochange_free(tc); } memfree(tm, sizeof(tempomap_node)); } /* tempomap_insert -- insert a tempo change into the map */ /**/ void tempomap_insert(tempomap, beat, tempo) tempomap_type tempomap; long beat; /* beat division number */ long tempo; /* microseconds per beat division */ { tempochange_type tempochange = tempochange_alloc(); register tempochange_type prev; register tempochange_type next; tempochange->tempo = tempo; tempochange->beat = beat; if ((!(tempomap->hint->next)) || (tempomap->hint->beat > beat)) tempomap->hint = tempomap->entries; /* find the insert point */ for (prev = tempomap->hint; (next = prev->next) && (next->beat <= beat); prev = next); /* make the insert */ tempochange->next = next; prev->next = tempochange; tempomap->hint = prev; /* update the real time of each change */ for (tempochange = prev; tempochange->next; tempochange = tempochange->next) { tempochange->next->rtime = tempochange->rtime + elapsed_time(tempochange->tempo, tempochange->next->beat - tempochange->beat); } } /* tempomap_lookup -- convert beat to 4us time */ /* * The returned time is real time in units of 4us. */ time_type tempomap_lookup(tempomap, beat) tempomap_type tempomap; long beat; { register tempochange_type prev; register tempochange_type next; if ((!(tempomap->hint->next)) || (tempomap->hint->beat > beat)) tempomap->hint = tempomap->entries; /* find the last inflection point */ for (prev = tempomap->hint; (next = prev->next) && (next->beat <= beat); prev = next); /* interpolate */ return prev->rtime + elapsed_time(prev->tempo, beat - prev->beat); } /* elapsed_time -- compute the real elapsed time at a given tempo */ /* * the time returned is in units of 4us. */ static time_type elapsed_time(tempo, beat) long tempo; long beat; { return (time_type)((tempo * beat) >> 2); }
26.576
78
0.640277
912bde640de0b75d03aa05122292e29b6ec17dd8
884
c
C
tools/validate/matrix float multiplication/code.c
jayaraj-poroor/verticalthings
1e153ef61bcb4e3af45894c39961ae468e58706c
[ "MIT" ]
2
2018-09-04T02:38:14.000Z
2018-09-05T17:12:44.000Z
tools/validate/matrix float multiplication/code.c
jayaraj-poroor/verticalthings
1e153ef61bcb4e3af45894c39961ae468e58706c
[ "MIT" ]
1
2021-03-08T20:03:12.000Z
2021-03-08T20:03:12.000Z
tools/validate/matrix float multiplication/code.c
jayarajporoor/verticalthings
1e153ef61bcb4e3af45894c39961ae468e58706c
[ "MIT" ]
1
2018-09-30T14:17:49.000Z
2018-09-30T14:17:49.000Z
#define POI 1 #define POIROW 1 #define STOPOI 1 #define MSIZE 50 float first[MSIZE][MSIZE]; float second[MSIZE][MSIZE]; float res[MSIZE][MSIZE]; void initialize(){ for(int i=0; i<MSIZE; i++) { for(int j=0; j<MSIZE; j++) { float k = (rand()%10); k = k/10; first[i][j] = i + j + k; second[i][j] = i + j + k; } } } int main(void) { initialize(); int m, n, p, q, c, d, k; float sum = 0; m = MSIZE; n = MSIZE; p = MSIZE; q = MSIZE; float* resi = &res[0][0]; float* fp; float* sp1 = &second[0][0]; float* sp; float* po; float* fp1 = &first[0][0]; for (c = 0; c < m; c++) { sp = sp1; for (d = 0; d < n; d++) { po = sp; fp = fp1; sp = sp + MSIZE; sum = 0; for (k = 0; k < q; k++) { sum = sum + *fp * *po; fp++; po = po + 1; } *(resi+d) = sum; } fp1 = fp; resi += d; } }
17.68
37
0.458145
87a1d56cc234bd31cb20ec696e4968e13f2f5e54
593
h
C
pebble/core/main/queue.h
muvr/open-muvr
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
[ "Apache-2.0" ]
59
2015-03-08T17:32:22.000Z
2018-07-08T04:04:29.000Z
pebble/core/main/queue.h
muvr/open-muvr
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
[ "Apache-2.0" ]
1
2015-03-29T17:11:11.000Z
2015-03-29T17:11:11.000Z
pebble/core/main/queue.h
muvr/open-muvr
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
[ "Apache-2.0" ]
17
2015-03-12T18:40:50.000Z
2018-03-10T00:49:33.000Z
#pragma once #include "pebble.h" #include "debug_macros.h" #ifdef __cplusplus extern "C" { #endif struct QueueNode { uint8_t* buffer; uint16_t size; struct QueueNode* next; } QueueNodeStruct; typedef struct { int length; struct QueueNode* first; } Queue; Queue* queue_create(); void queue_destroy(Queue** queue); void queue_add(Queue* queue, uint8_t* buffer, uint16_t size); void queue_peek(Queue* queue, uint8_t** buffer, uint16_t* size); void queue_pop(Queue* queue, uint8_t** buffer, uint16_t* size); int queue_length(Queue* queue); #ifdef __cplusplus } #endif
19.766667
64
0.721754
0cf4d70657e1e3aefb14a667b3ea6e808f366668
60
h
C
modulo4/ex15b/asm.h
jpvacorreia/ARQCP_ISEP
60974b1e45f5d9b6a105075b08c14eb47dd58288
[ "MIT" ]
null
null
null
modulo4/ex15b/asm.h
jpvacorreia/ARQCP_ISEP
60974b1e45f5d9b6a105075b08c14eb47dd58288
[ "MIT" ]
null
null
null
modulo4/ex15b/asm.h
jpvacorreia/ARQCP_ISEP
60974b1e45f5d9b6a105075b08c14eb47dd58288
[ "MIT" ]
3
2019-11-01T20:56:30.000Z
2020-11-17T17:21:25.000Z
#ifndef ASM_H #define ASM_H void changes(int *ptr); #endif
12
24
0.733333
d000b030d7eba5da36a3c9de73442cac43d9bb7e
329
h
C
ZHBaseKit/Classes/ZHBaseKit/ZHBase.h
Panzhenghui/ZHBaseKit
78933dfd166658594348f364c5f942d02b896ff4
[ "MIT" ]
1
2020-01-20T10:18:47.000Z
2020-01-20T10:18:47.000Z
ZHBaseKit/Classes/ZHBaseKit/ZHBase.h
Panzhenghui/ZHBaseKit
78933dfd166658594348f364c5f942d02b896ff4
[ "MIT" ]
null
null
null
ZHBaseKit/Classes/ZHBaseKit/ZHBase.h
Panzhenghui/ZHBaseKit
78933dfd166658594348f364c5f942d02b896ff4
[ "MIT" ]
1
2021-07-11T14:38:35.000Z
2021-07-11T14:38:35.000Z
// // ZHBase.h // ZHBaseKit // // Created by pzh on 2019/11/6. // Copyright © 2019 Panzhenghui. All rights reserved. // #ifndef ZHBase_h #define ZHBase_h #import "ZHUIMacro.h" #import "ZHProtocol.h" #import "ZHBaseCell.h" #import "ZHBaseCellModel.h" #import "ZHBaseKit.h" #import <Masonry/Masonry.h> #endif /* ZHBase_h */
16.45
54
0.693009
f41b5733bb6252dc512c79ad9f7b4615a51bfd6b
1,845
c
C
Control/EIT_SpeedR.c
chenxiannn/SmartCarCode
173e95a08d34e1e96d41be138509a9ff00f968cd
[ "Apache-2.0" ]
19
2018-01-18T06:44:45.000Z
2021-11-13T14:33:01.000Z
Control/EIT_SpeedR.c
chenxiannn/SmartCarCode
173e95a08d34e1e96d41be138509a9ff00f968cd
[ "Apache-2.0" ]
1
2018-03-13T01:56:10.000Z
2018-03-13T01:56:10.000Z
Control/EIT_SpeedR.c
chenxiannn/SmartCarCode
173e95a08d34e1e96d41be138509a9ff00f968cd
[ "Apache-2.0" ]
16
2018-01-19T02:04:02.000Z
2021-07-04T02:01:18.000Z
/* ******************************************************************************* * EIT Car Project * Main FUNCTIONS * * (c) Copyright 2015-2020 Car@EIT * All Rights Reserved * File : EIT_SpeedR.c * This file is part of EIT Car Project * Embedded Innovation Team(EIT) - * Website:http://www.mizhiquan.com * ---------------------------------------------------------------------------- * LICENSING TERMS: * * The Code is provided in source form for FREE evaluation and educational * use. * * ---------------------------------------------------------------------------- * Change Logs: * Date Author Notes * 2016-02-08 Xian.Chen the first version * 2016-07-08 Xian.Chen update * ******************************************************************************* */ #include "EIT_SpeedR.h" PID MotorR_PID; void MotorRPID_Init(void) { MotorRPID_InitParam(); MotorRPID_InitState(0); MotorRPID_SetSpeed(0); PID_InitFbVal(&MotorR_PID,0); } void MotorRPID_InitParam(void) { MotorR_PID.Kp = gParam.MotorR_PID_KP; MotorR_PID.Ki = gParam.MotorR_PID_KI*gParam.MotorR_PID_Ts; MotorR_PID.Kd = -gParam.MotorR_PID_KD/gParam.MotorR_PID_Ts; MotorR_PID.MAX_Val = MOTORR_PWM_MAX; MotorR_PID.MIN_Val = MOTORR_PWM_MIN; MotorR_PID.spUpRate=(int32)(gParam.MOtroR_PID_UpRate*gParam.MotorR_PID_Ts); MotorR_PID.spDnRate=(int32)(gParam.MOtroR_PID_DnRate*gParam.MotorR_PID_Ts); } void MotorRPID_InitState(int32 I) { MotorR_PID.I = I; MotorR_PID.spValRamp=0; } void MotorRPID_SetSpeed( int32 spSpeed) { MotorR_PID.spVal = spSpeed; } void MotorRPID_SpeedControl(void) { PID_Run_PID(&MotorR_PID); //MotorR_PID.outVal=400; MotorR_Run(MotorR_PID.outVal); }
29.758065
80
0.550136
0b25a1d25b5e30732231de0c4df5f4467156a4b9
666
h
C
server_gui/walking2window.h
sinanelveren/Smart-Healthband-Bilek-Partner-Bil396-Project
62dcb29402221235f976a61b0eb8412dccccb12a
[ "MIT" ]
3
2019-05-09T19:43:56.000Z
2019-09-10T14:42:29.000Z
server_gui/walking2window.h
sinanelveren/Smart-Healthband-Bilek-Partner-Bil396-Project
62dcb29402221235f976a61b0eb8412dccccb12a
[ "MIT" ]
null
null
null
server_gui/walking2window.h
sinanelveren/Smart-Healthband-Bilek-Partner-Bil396-Project
62dcb29402221235f976a61b0eb8412dccccb12a
[ "MIT" ]
null
null
null
#ifndef WALKING2WINDOW_H #define WALKING2WINDOW_H #include <QDialog> #include "qcustomplot.h" #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtCharts/QChartView> #include <QtCharts/QPieSeries> #include <QtCharts/QPieSlice> namespace Ui { class walking2window; } class walking2window : public QDialog { Q_OBJECT public: explicit walking2window(QWidget *parent = nullptr); ~walking2window(); void setupPlot(QStringList wordList); QStringList csvReader(); private: Ui::walking2window *ui; int mon; int the; int wed; int thu; int fri; int sat; int sun; }; #endif // WALKING2WINDOW_H
18
55
0.717718
73b01e3d596753a2e58170b24164d32d4fcbe30c
19,831
h
C
admin/activec/samples/benefits/benefits.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/samples/benefits/benefits.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/samples/benefits/benefits.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: benefits.h // //-------------------------------------------------------------------------- #ifndef __BENEFITS_H_ #define __BENEFITS_H_ #include "resource.h" #include <atlsnap.h> #include "snaphelp.h" #include "atltask.h" #include "BenSvr.h" #include "Employee.h" // // Property page containing employee information. // class CEmployeeNamePage : public CSnapInPropertyPageImpl<CEmployeeNamePage> { public : CEmployeeNamePage(long lNotifyHandle, bool fStartup, bool bDeleteHandle = false, TCHAR* pTitle = NULL) : CSnapInPropertyPageImpl<CEmployeeNamePage> (pTitle),\ m_fStartup( fStartup ), m_lNotifyHandle(lNotifyHandle), m_bDeleteHandle(bDeleteHandle) // Should be true for only page. { m_pEmployee = NULL; } ~CEmployeeNamePage() { if (m_bDeleteHandle) MMCFreeNotifyHandle(m_lNotifyHandle); } enum { IDD = IDD_NAME_PAGE }; BEGIN_MSG_MAP(CEmployeeNamePage) MESSAGE_HANDLER( WM_INITDIALOG, OnInitDialog ) COMMAND_CODE_HANDLER( EN_CHANGE, OnChange ) CHAIN_MSG_MAP(CSnapInPropertyPageImpl<CEmployeeNamePage>) END_MSG_MAP() HRESULT PropertyChangeNotify(long param) { return MMCPropertyChangeNotify(m_lNotifyHandle, param); } // // Handler to initialize values in dialog. // LRESULT OnInitDialog( UINT uiMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled ); // // Calls OnWizardFinish() to handle the storage of employee // data. // BOOL OnApply() { return( OnWizardFinish() ); }; // // Calls OnWizardFinish() to handle the storage of employee // data. // BOOL OnWizardNext() { return( OnWizardFinish() ); }; // // This is overridden to modify the UI depending on whether // we're in start-up mode or not. // BOOL OnSetActive(); // // Overridden to store new values of employee. // BOOL OnWizardFinish(); // // Called when one of the values has been modified. We need // to inform the property page of the change. // LRESULT OnChange(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { UNUSED_ALWAYS( wNotifyCode ); UNUSED_ALWAYS( wID ); UNUSED_ALWAYS( hWndCtl ); UNUSED_ALWAYS( bHandled ); SetModified(); return( TRUE ); } public: long m_lNotifyHandle; bool m_bDeleteHandle; CEmployee* m_pEmployee; bool m_fStartup; }; // // Property page containing employee information. // class CEmployeeAddressPage : public CSnapInPropertyPageImpl<CEmployeeAddressPage> { public : CEmployeeAddressPage(long lNotifyHandle, bool fStartup, bool bDeleteHandle = false, TCHAR* pTitle = NULL) : CSnapInPropertyPageImpl<CEmployeeAddressPage> (pTitle),\ m_fStartup( fStartup ), m_lNotifyHandle(lNotifyHandle), m_bDeleteHandle(bDeleteHandle) // Should be true for only page. { m_pEmployee = NULL; } ~CEmployeeAddressPage() { if (m_bDeleteHandle) MMCFreeNotifyHandle(m_lNotifyHandle); } enum { IDD = IDD_ADDRESS_PAGE }; BEGIN_MSG_MAP(CEmployeeAddressPage) MESSAGE_HANDLER( WM_INITDIALOG, OnInitDialog ) COMMAND_CODE_HANDLER( EN_CHANGE, OnChange ) CHAIN_MSG_MAP(CSnapInPropertyPageImpl<CEmployeeAddressPage>) END_MSG_MAP() // Handler prototypes: // LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); // LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); // LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); HRESULT PropertyChangeNotify(long param) { return MMCPropertyChangeNotify(m_lNotifyHandle, param); } // // Handler to initialize values in dialog. // LRESULT OnInitDialog( UINT uiMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled ); // // Calls OnWizardFinish() to handle the storage of employee // data. // BOOL OnApply() { return( OnWizardFinish() ); }; // // This is overridden to modify the UI depending on whether // we're in start-up mode or not. // BOOL OnSetActive(); // // Overridden to store new values of employee. // BOOL OnWizardFinish(); // // Called when one of the values has been modified. We need // to inform the property page of the change. // LRESULT OnChange(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { UNUSED_ALWAYS( wNotifyCode ); UNUSED_ALWAYS( wID ); UNUSED_ALWAYS( hWndCtl ); UNUSED_ALWAYS( bHandled ); SetModified(); return( TRUE ); } public: long m_lNotifyHandle; bool m_bDeleteHandle; CEmployee* m_pEmployee; bool m_fStartup; }; template< class T > class CBenefitsData : public CSnapInItemImpl< T > { public: static const GUID* m_NODETYPE; static const TCHAR* m_SZNODETYPE; static const TCHAR* m_SZDISPLAY_NAME; static const CLSID* m_SNAPIN_CLASSID; CBenefitsData( CEmployee* pEmployee ) { // // Assign the given employee to our internal containment. // This employee will be assumed valid for the lifetime of // this object since persistence is maintained by our parent // node. // m_pEmployee = pEmployee; // // Always initialize our display name with the static declared. // m_bstrDisplayName = m_SZDISPLAY_NAME; // // Image indexes may need to be modified depending on the images specific to // the snapin. // memset(&m_scopeDataItem, 0, sizeof(SCOPEDATAITEM)); m_scopeDataItem.mask = SDI_STR | SDI_IMAGE | SDI_OPENIMAGE | SDI_PARAM; m_scopeDataItem.displayname = MMC_CALLBACK; m_scopeDataItem.nImage = 0; // May need modification m_scopeDataItem.nOpenImage = 0; // May need modification m_scopeDataItem.lParam = (LPARAM) this; memset(&m_resultDataItem, 0, sizeof(RESULTDATAITEM)); m_resultDataItem.mask = RDI_STR | RDI_IMAGE | RDI_PARAM; m_resultDataItem.str = MMC_CALLBACK; m_resultDataItem.nImage = 0; // May need modification m_resultDataItem.lParam = (LPARAM) this; } ~CBenefitsData() { } STDMETHOD(GetScopePaneInfo)(SCOPEDATAITEM *pScopeDataItem) { if (pScopeDataItem->mask & SDI_STR) pScopeDataItem->displayname = m_bstrDisplayName; if (pScopeDataItem->mask & SDI_IMAGE) pScopeDataItem->nImage = m_scopeDataItem.nImage; if (pScopeDataItem->mask & SDI_OPENIMAGE) pScopeDataItem->nOpenImage = m_scopeDataItem.nOpenImage; if (pScopeDataItem->mask & SDI_PARAM) pScopeDataItem->lParam = m_scopeDataItem.lParam; if (pScopeDataItem->mask & SDI_STATE ) pScopeDataItem->nState = m_scopeDataItem.nState; // // SDI_CHILDREN should be overridden by its derived classes. // return S_OK; } STDMETHOD(GetResultPaneInfo)(RESULTDATAITEM *pResultDataItem) { if (pResultDataItem->bScopeItem) { if (pResultDataItem->mask & RDI_STR) { pResultDataItem->str = GetResultPaneColInfo(pResultDataItem->nCol); } if (pResultDataItem->mask & RDI_IMAGE) { pResultDataItem->nImage = m_scopeDataItem.nImage; } if (pResultDataItem->mask & RDI_PARAM) { pResultDataItem->lParam = m_scopeDataItem.lParam; } return S_OK; } if (pResultDataItem->mask & RDI_STR) { pResultDataItem->str = GetResultPaneColInfo(pResultDataItem->nCol); } if (pResultDataItem->mask & RDI_IMAGE) { pResultDataItem->nImage = m_resultDataItem.nImage; } if (pResultDataItem->mask & RDI_PARAM) { pResultDataItem->lParam = m_resultDataItem.lParam; } if (pResultDataItem->mask & RDI_INDEX) { pResultDataItem->nIndex = m_resultDataItem.nIndex; } return S_OK; } // // Overridden to provide result icons. // STDMETHOD( OnAddImages )( MMC_NOTIFY_TYPE event, long arg, long param, IConsole* pConsole, DATA_OBJECT_TYPES type ) { UNUSED_ALWAYS( event ); UNUSED_ALWAYS( param ); UNUSED_ALWAYS( pConsole ); UNUSED_ALWAYS( type ); // Add Images IImageList* pImageList = (IImageList*) arg; HRESULT hr = E_FAIL; // Load bitmaps associated with the scope pane // and add them to the image list // Loads the default bitmaps generated by the wizard // Change as required HBITMAP hBitmap16 = LoadBitmap( _Module.GetResourceInstance(), MAKEINTRESOURCE( IDB_BENEFITS_16 ) ); if (hBitmap16 != NULL) { HBITMAP hBitmap32 = LoadBitmap( _Module.GetResourceInstance(), MAKEINTRESOURCE( IDB_BENEFITS_32 ) ); if (hBitmap32 != NULL) { hr = pImageList->ImageListSetStrip( (long*)hBitmap16, (long*) hBitmap32, 0, RGB( 0, 128, 128 ) ); if ( FAILED( hr ) ) ATLTRACE( _T( "IImageList::ImageListSetStrip failed\n" ) ); } } return( hr ); } virtual LPOLESTR GetResultPaneColInfo(int nCol) { if (nCol == 0) { T* pT = static_cast<T*>(this); return( pT->m_bstrDisplayName ); } // TODO : Return the text for other columns return OLESTR("Generic Description"); } // // Helper function to extract the appropriate console from // a base object type. // STDMETHOD( GetConsole )( CSnapInObjectRootBase* pObj, IConsole** ppConsole ) { HRESULT hr = E_FAIL; if ( pObj->m_nType == 1 ) { // // This is the id of the data object. // *ppConsole = ( (CBenefits*) pObj )->m_spConsole; (*ppConsole)->AddRef(); hr = S_OK; } else if ( pObj->m_nType == 2 ) { // // This is the id of the component object. // *ppConsole = ( (CBenefitsComponent*) pObj )->m_spConsole; (*ppConsole)->AddRef(); hr = S_OK; } return( hr ); } // // Called to determine if the clipboard data can be obtained and // if it has a node type that matches the given GUID. // STDMETHOD( IsClipboardDataType )( LPDATAOBJECT pDataObject, GUID inGuid ) { HRESULT hr = S_FALSE; if ( pDataObject == NULL ) return( E_POINTER ); STGMEDIUM stgmedium = { TYMED_HGLOBAL, NULL }; FORMATETC formatetc = { CSnapInItem::m_CCF_NODETYPE, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; // // Allocate memory to received the GUID. // stgmedium.hGlobal = GlobalAlloc( 0, sizeof( GUID ) ); if ( stgmedium.hGlobal == NULL ) return( E_OUTOFMEMORY ); // // Retrieve the GUID of the paste object. // hr = pDataObject->GetDataHere( &formatetc, &stgmedium ); if( FAILED( hr ) ) { GlobalFree(stgmedium.hGlobal); return( hr ); } // // Make a local copy of the GUID. // GUID guid; memcpy( &guid, stgmedium.hGlobal, sizeof( GUID ) ); GlobalFree( stgmedium.hGlobal ); // // Check to see if the node is of the appropriate type. // if ( IsEqualGUID( guid, inGuid ) ) hr = S_OK; else hr = S_FALSE; return( hr ); } // // Command handler for "OnImport" functionality. For the current // sample, display a simple message box. // STDMETHOD( OnImport )(bool& bHandled, CSnapInObjectRootBase* pObj) { UNUSED_ALWAYS( bHandled ); USES_CONVERSION; int nResult; CComPtr<IConsole> spConsole; // // Retrieve the appropriate console. // GetConsole( pObj, &spConsole ); spConsole->MessageBox( T2OLE( _T( "Data successfully imported" ) ), T2OLE( _T( "Benefits" ) ), MB_ICONINFORMATION | MB_OK, &nResult ); return( S_OK ); }; // // Command handler for "OnExport" functionality. For the current // sample, display a simple message box. // STDMETHOD( OnExport )(bool& bHandled, CSnapInObjectRootBase* pObj) { UNUSED_ALWAYS( bHandled ); USES_CONVERSION; int nResult; CComPtr<IConsole> spConsole; // // Retrieve the appropriate console. // GetConsole( pObj, &spConsole ); spConsole->MessageBox( T2OLE( _T( "Data successfully exported" ) ), T2OLE( _T( "Benefits" ) ), MB_ICONINFORMATION | MB_OK, &nResult ); return( S_OK ); }; protected: // // Container for the employee information. // CEmployee* m_pEmployee; }; template< class T > class CChildrenBenefitsData : public CBenefitsData< T > { public: // // Call the benefits data with no employee. All of our // containment nodes are not passed in an employee. // CChildrenBenefitsData< T >( CEmployee* pEmployee = NULL ) : CBenefitsData< T >( pEmployee ) { }; // // Overridden to automatically clean-up any child nodes. // virtual ~CChildrenBenefitsData() { // // Free any added nodes. // for ( int i = 0; i < m_Nodes.GetSize(); i++ ) { CSnapInItem* pNode; pNode = m_Nodes[ i ]; _ASSERTE( pNode != NULL ); delete pNode; } } // // Overridden to automatically expand any child nodes. // STDMETHOD( OnShow )( MMC_NOTIFY_TYPE event, long arg, long param, IConsole* pConsole, DATA_OBJECT_TYPES type) { UNUSED_ALWAYS( event ); UNUSED_ALWAYS( param ); UNUSED_ALWAYS( type ); HRESULT hr = E_NOTIMPL; ATLTRACE2(atlTraceSnapin, 0, _T("CChildNodeImpl::OnExpand\n")); // // Only add the items if we're being selected. // if ( arg == TRUE ) { CComQIPtr<IResultData,&IID_IResultData> spResultData( pConsole ); // // Loop through and add each subnode. // for ( int i = 0; i < m_Nodes.GetSize(); i++ ) { CSnapInItem* pNode; RESULTDATAITEM* pResultData; pNode = m_Nodes[ i ]; _ASSERTE( pNode != NULL ); // // Get the scope pane info for the node and set // relative id. // pNode->GetResultData( &pResultData ); _ASSERTE( pResultData != NULL ); // // Add the item to the scope list using the newly // populated scope data item. // hr = spResultData->InsertItem( pResultData ); _ASSERTE( SUCCEEDED( hr ) ); } } return( hr ); }; // // Overridden to automatically expand any child nodes. // STDMETHOD( OnExpand )( MMC_NOTIFY_TYPE event, long arg, long param, IConsole* pConsole, DATA_OBJECT_TYPES type) { UNUSED_ALWAYS( event ); UNUSED_ALWAYS( arg ); UNUSED_ALWAYS( type ); ATLTRACE2(atlTraceSnapin, 0, _T("CChildNodeImpl::OnExpand\n")); CComQIPtr<IConsoleNameSpace, &IID_IConsoleNameSpace> pNameSpace( pConsole ); HRESULT hr = E_NOTIMPL; // // Loop through and add each subnode. // for ( int i = 0; i < m_Nodes.GetSize(); i++ ) { CSnapInItem* pNode; SCOPEDATAITEM* pScopeData; pNode = m_Nodes[ i ]; _ASSERTE( pNode != NULL ); // // Get the scope pane info for the node and set // relative id. // pNode->GetScopeData( &pScopeData ); _ASSERTE( pScopeData != NULL ); pScopeData->relativeID = param; // // Add the item to the scope list using the newly // populated scope data item. // hr = pNameSpace->InsertItem( pScopeData ); _ASSERTE( SUCCEEDED( hr ) ); } return( hr ); }; // // Used as containment for all child nodes. // CSimpleArray<CSnapInItem*> m_Nodes; }; class CBenefits; class CBenefitsComponent : public CComObjectRootEx<CComSingleThreadModel>, public CSnapInObjectRoot<2, CBenefits >, public IExtendPropertySheetImpl<CBenefitsComponent>, public IExtendContextMenuImpl<CBenefitsComponent>, public IExtendControlbarImpl<CBenefitsComponent>, public IComponentImpl<CBenefitsComponent>, public IExtendTaskPadImpl<CBenefitsComponent> { public: BEGIN_COM_MAP(CBenefitsComponent) COM_INTERFACE_ENTRY(IComponent) COM_INTERFACE_ENTRY(IExtendPropertySheet) COM_INTERFACE_ENTRY(IExtendContextMenu) COM_INTERFACE_ENTRY(IExtendControlbar) COM_INTERFACE_ENTRY(IExtendTaskPad) END_COM_MAP() public: CBenefitsComponent() { // // Taskpad initialization stuff. // m_pszTitle = L"Benefits Taskpad"; m_pszBackgroundPath = NULL; } STDMETHOD(Notify)(LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, long arg, long param) { if (lpDataObject != NULL) return IComponentImpl<CBenefitsComponent>::Notify(lpDataObject, event, arg, param); return E_NOTIMPL; } // // Taskpad related information. Specifies titles, background // information, etc. // LPOLESTR m_pszTitle; LPOLESTR m_pszBackgroundPath; }; class CBenefits : public CComObjectRootEx<CComSingleThreadModel>, public CSnapInObjectRoot<1, CBenefits>, public IComponentDataImpl<CBenefits, CBenefitsComponent>, public IExtendPropertySheetImpl<CBenefits>, public IExtendContextMenuImpl<CBenefits>, public IPersistStream, public CComCoClass<CBenefits, &CLSID_Benefits>, public ISnapinHelpImpl<CBenefits> { public: CBenefits(); ~CBenefits(); BEGIN_COM_MAP(CBenefits) COM_INTERFACE_ENTRY(IComponentData) COM_INTERFACE_ENTRY(IExtendPropertySheet) COM_INTERFACE_ENTRY(IExtendContextMenu) COM_INTERFACE_ENTRY(IPersistStream) COM_INTERFACE_ENTRY(ISnapinHelp) END_COM_MAP() DECLARE_REGISTRY_RESOURCEID(IDR_BENEFITS) DECLARE_NOT_AGGREGATABLE(CBenefits) // // Return the classid of this object. // STDMETHOD(GetClassID)(CLSID *pClassID) { *pClassID = GetObjectCLSID(); return S_OK; } // // Call the root node's implementation. // STDMETHOD(IsDirty)(); // // Call the root node's implementation. // STDMETHOD(Load)(LPSTREAM pStm); // // Call the root node's implementation. // STDMETHOD(Save)(LPSTREAM pStm, BOOL fClearDirty); // // Call the root node's implementation. // STDMETHOD(GetSizeMax)(ULARGE_INTEGER FAR* pcbSize ); STDMETHOD(Initialize)(LPUNKNOWN pUnknown); static void WINAPI ObjectMain(bool bStarting) { if (bStarting) CSnapInItem::Init(); } // // This is overridden to handle update notifications from // the property pages. // STDMETHOD(Notify)(LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, long arg, long param); }; class ATL_NO_VTABLE CBenefitsAbout : public ISnapinAbout, public CComObjectRoot, public CComCoClass< CBenefitsAbout, &CLSID_BenefitsAbout> { public: DECLARE_REGISTRY(CBenefitsAbout, _T("BenefitsAbout.1"), _T("BenefitsAbout.1"), IDS_BENEFITS_DESC, THREADFLAGS_BOTH); BEGIN_COM_MAP(CBenefitsAbout) COM_INTERFACE_ENTRY(ISnapinAbout) END_COM_MAP() STDMETHOD(GetSnapinDescription)(LPOLESTR *lpDescription) { USES_CONVERSION; TCHAR szBuf[256]; if (::LoadString(_Module.GetResourceInstance(), IDS_BENEFITS_DESC, szBuf, 256) == 0) return E_FAIL; *lpDescription = (LPOLESTR)CoTaskMemAlloc((lstrlen(szBuf) + 1) * sizeof(OLECHAR)); if (*lpDescription == NULL) return E_OUTOFMEMORY; ocscpy(*lpDescription, T2OLE(szBuf)); return S_OK; } STDMETHOD(GetProvider)(LPOLESTR *lpName) { USES_CONVERSION; TCHAR szBuf[256]; if (::LoadString(_Module.GetResourceInstance(), IDS_BENEFITS_PROVIDER, szBuf, 256) == 0) return E_FAIL; *lpName = (LPOLESTR)CoTaskMemAlloc((lstrlen(szBuf) + 1) * sizeof(OLECHAR)); if (*lpName == NULL) return E_OUTOFMEMORY; ocscpy(*lpName, T2OLE(szBuf)); return S_OK; } STDMETHOD(GetSnapinVersion)(LPOLESTR *lpVersion) { USES_CONVERSION; TCHAR szBuf[256]; if (::LoadString(_Module.GetResourceInstance(), IDS_BENEFITS_VERSION, szBuf, 256) == 0) return E_FAIL; *lpVersion = (LPOLESTR)CoTaskMemAlloc((lstrlen(szBuf) + 1) * sizeof(OLECHAR)); if (*lpVersion == NULL) return E_OUTOFMEMORY; ocscpy(*lpVersion, T2OLE(szBuf)); return S_OK; } STDMETHOD(GetSnapinImage)(HICON *hAppIcon) { *hAppIcon = NULL; return S_OK; } STDMETHOD(GetStaticFolderImage)(HBITMAP *hSmallImage, HBITMAP *hSmallImageOpen, HBITMAP *hLargeImage, COLORREF *cMask) { UNUSED_ALWAYS( hSmallImage ); UNUSED_ALWAYS( cMask ); *hSmallImageOpen = *hLargeImage = *hLargeImage = 0; return S_OK; } }; #endif
24.543317
118
0.670163
42a92125cc3c09bbf1b1b9a66ff3347583f8517d
1,262
h
C
release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/rtl8367rb__V1.2.12/include/rtl8367b_asicdrv_trunking.h
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
null
null
null
release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/rtl8367rb__V1.2.12/include/rtl8367b_asicdrv_trunking.h
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
null
null
null
release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/rtl8367rb__V1.2.12/include/rtl8367b_asicdrv_trunking.h
zhoutao0712/rtn11pb1
09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05
[ "Apache-2.0" ]
null
null
null
#ifndef _RTL8367B_ASICDRV_TRUNKING_H_ #define _RTL8367B_ASICDRV_TRUNKING_H_ #include <rtl8367b_asicdrv.h> #define RTL8367B_MAX_TRUNK_GID (1) #define RTL8367B_TRUNKING_PORTNO (4) #define RTL8367B_TRUNKING_HASHVALUE_MAX (15) extern ret_t rtl8367b_setAsicTrunkingGroup(rtk_uint32 group, rtk_uint32 portmask); extern ret_t rtl8367b_getAsicTrunkingGroup(rtk_uint32 group, rtk_uint32* pPortmask); extern ret_t rtl8367b_setAsicTrunkingFlood(rtk_uint32 enabled); extern ret_t rtl8367b_getAsicTrunkingFlood(rtk_uint32* pEnabled); extern ret_t rtl8367b_setAsicTrunkingHashSelect(rtk_uint32 hashsel); extern ret_t rtl8367b_getAsicTrunkingHashSelect(rtk_uint32* pHashsel); extern ret_t rtl8367b_getAsicQeueuEmptyStatus(rtk_uint32* pPortmask); extern ret_t rtl8367b_setAsicTrunkingMode(rtk_uint32 mode); extern ret_t rtl8367b_getAsicTrunkingMode(rtk_uint32* pMode); extern ret_t rtl8367b_setAsicTrunkingFc(rtk_uint32 group, rtk_uint32 enabled); extern ret_t rtl8367b_getAsicTrunkingFc(rtk_uint32 group, rtk_uint32* pEnabled); extern ret_t rtl8367b_setAsicTrunkingHashTable(rtk_uint32 hashval, rtk_uint32 portId); extern ret_t rtl8367b_getAsicTrunkingHashTable(rtk_uint32 hashval, rtk_uint32* pPortId); #endif /*_RTL8367B_ASICDRV_TRUNKING_H_*/
45.071429
88
0.853407
5d67bb73bf3849ed9a4828fa4ce4d469806e66ee
558
h
C
xlat/tcflsh_options.h
pixeldustproject-o/android_external_strace
0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec
[ "BSD-3-Clause" ]
3
2017-05-05T06:46:55.000Z
2019-11-04T05:26:01.000Z
xlat/tcflsh_options.h
pixeldustproject-o/android_external_strace
0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec
[ "BSD-3-Clause" ]
null
null
null
xlat/tcflsh_options.h
pixeldustproject-o/android_external_strace
0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec
[ "BSD-3-Clause" ]
1
2017-02-28T13:18:18.000Z
2017-02-28T13:18:18.000Z
/* Generated by ./xlat/gen.sh from ./xlat/tcflsh_options.in; do not edit. */ #ifdef IN_MPERS # error static const struct xlat tcflsh_options in mpers mode #else static const struct xlat tcflsh_options[] = { #if defined(TCIFLUSH) || (defined(HAVE_DECL_TCIFLUSH) && HAVE_DECL_TCIFLUSH) XLAT(TCIFLUSH), #endif #if defined(TCOFLUSH) || (defined(HAVE_DECL_TCOFLUSH) && HAVE_DECL_TCOFLUSH) XLAT(TCOFLUSH), #endif #if defined(TCIOFLUSH) || (defined(HAVE_DECL_TCIOFLUSH) && HAVE_DECL_TCIOFLUSH) XLAT(TCIOFLUSH), #endif XLAT_END }; #endif /* !IN_MPERS */
23.25
79
0.738351
71269f275199a78c368d375fd02dba92f9cf8d61
357
h
C
protocols/JSONHTTPRequestDelegate.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
protocols/JSONHTTPRequestDelegate.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
protocols/JSONHTTPRequestDelegate.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser. */ @protocol JSONHTTPRequestDelegate <NSObject> @required - (void)request:(JSONHTTPRequest *)arg1 didFailWithError:(NSError *)arg2; - (void)request:(JSONHTTPRequest *)arg1 didReceiveObject:(id)arg2; @optional - (void)request:(JSONHTTPRequest *)arg1 hasWrittenBytes:(long long)arg2 expectsToWrite:(long long)arg3; @end
22.3125
103
0.770308
19cf75e8746010625ea59aae9c358cb6a78ff720
982
h
C
Lab2/date.h
VolMartLabs/1semlabs
3ce4a6e1b8eb46d0c177b84cc12ecdbea96b572d
[ "MIT" ]
null
null
null
Lab2/date.h
VolMartLabs/1semlabs
3ce4a6e1b8eb46d0c177b84cc12ecdbea96b572d
[ "MIT" ]
null
null
null
Lab2/date.h
VolMartLabs/1semlabs
3ce4a6e1b8eb46d0c177b84cc12ecdbea96b572d
[ "MIT" ]
null
null
null
#ifndef DATE_H #define DATE_H #include <iostream> #include <QTextStream> #include <ctime> class Date { private: int _day; int _month; int _year; int _hours; int _mins; int _secs; public: Date(); explicit Date(int day, int month, int year, int secs, int mins, int hours) : _day(day), _month(month), _year(year), _secs(secs), _mins(mins), _hours(hours) {} int day() const; void setDay(const int &day); int month() const; void setMonth(const int &month); int year() const; void setYear(const int &year); int secs() const; void setSecs(const int &secs); int mins() const; void setMins(const int &mins); int hours() const; void setHours(const int &hours); }; bool operator > (Date a, Date b); bool operator < (Date a, Date b); bool operator >= (Date a, Date b); bool operator <= (Date a, Date b); bool operator == (Date a, Date b); bool operator != (Date a, Date b); #endif // DATE_H
19.254902
75
0.6222
61706c19bc09fead51bdb12ee5a62c062a12f362
4,384
h
C
src/qt/qtbase/src/plugins/platforms/cocoa/qcocoamenuitem.h
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtbase/src/plugins/platforms/cocoa/qcocoamenuitem.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/plugins/platforms/cocoa/qcocoamenuitem.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2022-02-18T10:41:38.000Z
2022-02-18T10:41:38.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Copyright (C) 2012 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author James Turner <james.turner@kdab.com> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QCOCOAMENUITEM_H #define QCOCOAMENUITEM_H #include <qpa/qplatformmenu.h> #include <QtGui/QImage> //#define QT_COCOA_ENABLE_MENU_DEBUG #ifdef __OBJC__ #define QT_FORWARD_DECLARE_OBJC_CLASS(__KLASS__) @class __KLASS__ #else #define QT_FORWARD_DECLARE_OBJC_CLASS(__KLASS__) typedef struct objc_object __KLASS__ #endif QT_FORWARD_DECLARE_OBJC_CLASS(NSMenuItem); QT_FORWARD_DECLARE_OBJC_CLASS(NSMenu); QT_FORWARD_DECLARE_OBJC_CLASS(NSObject); QT_BEGIN_NAMESPACE class QCocoaMenu; class QCocoaMenuItem : public QPlatformMenuItem { public: QCocoaMenuItem(); virtual ~QCocoaMenuItem(); inline virtual void setTag(quintptr tag) { m_tag = tag; } inline virtual quintptr tag() const { return m_tag; } void setText(const QString &text); void setIcon(const QIcon &icon); void setMenu(QPlatformMenu *menu); void setVisible(bool isVisible); void setIsSeparator(bool isSeparator); void setFont(const QFont &font); void setRole(MenuRole role); void setShortcut(const QKeySequence& shortcut); void setCheckable(bool checkable) { Q_UNUSED(checkable) } void setChecked(bool isChecked); void setEnabled(bool isEnabled); inline QString text() const { return m_text; } inline NSMenuItem * nsItem() { return m_native; } NSMenuItem *sync(); void syncMerged(); void syncModalState(bool modal); inline bool isMerged() const { return m_merged; } inline bool isEnabled() const { return m_enabled; } inline bool isSeparator() const { return m_isSeparator; } QCocoaMenu *menu() const { return m_menu; } MenuRole effectiveRole() const; private: QString mergeText(); QKeySequence mergeAccel(); NSMenuItem *m_native; QString m_text; bool m_textSynced; QIcon m_icon; QCocoaMenu *m_menu; bool m_isVisible; bool m_enabled; bool m_isSeparator; QFont m_font; MenuRole m_role; MenuRole m_detectedRole; QKeySequence m_shortcut; bool m_checked; bool m_merged; quintptr m_tag; }; #define COCOA_MENU_ANCESTOR(m) ((m)->property("_qCocoaMenuAncestor").value<QObject *>()) #define SET_COCOA_MENU_ANCESTOR(m, ancestor) (m)->setProperty("_qCocoaMenuAncestor", QVariant::fromValue<QObject *>(ancestor)) QT_END_NAMESPACE #endif
33.723077
132
0.718066
9faa2177cbd0b58a99231496766de47c04c47fd8
4,078
h
C
arduino-midi-sound-module/envelope.h
DLehenbauer/arduino-midi-synth
a8ad8e36dbcc8a1c40ec63657f3fc3007a817d10
[ "MIT" ]
47
2018-05-23T00:36:04.000Z
2022-03-18T17:33:44.000Z
arduino-midi-sound-module/envelope.h
DLehenbauer/arduino-midi-synth
a8ad8e36dbcc8a1c40ec63657f3fc3007a817d10
[ "MIT" ]
4
2018-06-04T22:06:13.000Z
2020-03-22T19:16:42.000Z
arduino-midi-sound-module/envelope.h
DLehenbauer/arduino-midi-synth
a8ad8e36dbcc8a1c40ec63657f3fc3007a817d10
[ "MIT" ]
5
2018-05-20T03:16:35.000Z
2021-01-07T19:24:49.000Z
/* Envelope Generator https://github.com/DLehenbauer/arduino-midi-sound-module Envelope generator used for amplitude, frequency, and wavetable offset modulation. */ #ifndef __ENVELOPE_H__ #define __ENVELOPE_H__ #include <stdint.h> #include "instruments.h" class Envelope { private: const EnvelopeStage* pFirstStage = nullptr; // Pointer to first stage in 'Instruments::EnvelopeStages[]' uint8_t loopStart = 0xFF; // Index of loop start uint8_t loopEnd = 0xFF; // Index of loop end / release start uint8_t stageIndex = 0xFF; // Current stage index int16_t value = 0; // Current Q8.8 fixed-point value int16_t slope = 0; // Current Q8.8 slope (added to current value at each sample()) int8_t limit = -64; // Value limit at which envelope will advance to next stage // Updates 'slope' and 'limit' with the value of the current 'stageIndex'. void loadStage() volatile { EnvelopeStage stage; Instruments::getEnvelopeStage(pFirstStage + stageIndex, /* out: */ stage); slope = stage.slope; limit = stage.limit; } public: // Each call to 'sample()' advances the envelope generator to it's next state, and returns // a value in the range [0 .. 127]. uint8_t sample() volatile { value += slope; // Increase/decrease the current value according to the slope. int8_t out = value >> 8; // Convert Q8.8 fixed point value to uint8_t output const bool nextStage = (out < 0) || // Advance to next stage if the slope has overflowed (slope <= 0) // Otherwise, advance to next stage if... ? out <= limit // decreasing value is below or equal to limit : out >= limit; // or increasing value is above or equal to limit if (nextStage) { // If advancing to next stage... out = limit; // clamp output to the limit value = limit << 8; // clamp value to limit stageIndex++; // advance to next envelope stage if (stageIndex == loopEnd) { // If next stage is end of loop... stageIndex = loopStart; // jump to start of loop } loadStage(); // Load the slope/limit for the new stage } return out; // Return the new value } // 'start()' is called by 'Synth::noteOn()' to intialize the envelope generators with the /// program from 'Instruments::EnvelopePrograms' at the given 'programIndex'. void start(uint8_t programIndex) volatile { EnvelopeProgram program; Instruments::getEnvelopeProgram(programIndex, program); pFirstStage = program.start; loopStart = program.loopStartAndEnd >> 4; loopEnd = program.loopStartAndEnd & 0x0F; value = program.initialValue << 8; stageIndex = 0; loadStage(); } // 'stop()' is called by 'Synth::noteOff()' to advance the the envelope generator to the // 'loopEnd' stage, if it has not already passed it. // // Note: The generator will not loop back to 'loopStart', but continue advancing until it // reaches a stage than never completes, such as { slope: 0, limit: -64 }. void stop() volatile { if (stageIndex < loopEnd) { stageIndex = loopEnd; loadStage(); } } // Allow Synth::getNextVoice() to inspect private state when choosing the next best voice. friend class Synth; #ifdef __EMSCRIPTEN__ uint8_t sampleEm() { return sample(); } void startEm(uint8_t program) { start(program); } void stopEm() { stop(); } uint8_t getStageIndex() { return stageIndex; } #endif // __EMSCRIPTEN__ }; #endif //__ENVELOPE_H__
42.926316
115
0.576753
197d2eef6c9056cbb2698779079626239eb93465
3,102
h
C
Libraries/Base/Macro.h
hung0913208/Base
420b4ce8e08f9624b4e884039218ffd233b88335
[ "BSD-3-Clause" ]
null
null
null
Libraries/Base/Macro.h
hung0913208/Base
420b4ce8e08f9624b4e884039218ffd233b88335
[ "BSD-3-Clause" ]
null
null
null
Libraries/Base/Macro.h
hung0913208/Base
420b4ce8e08f9624b4e884039218ffd233b88335
[ "BSD-3-Clause" ]
2
2020-11-04T08:00:37.000Z
2020-11-06T08:33:33.000Z
#ifndef BASE_MACRO_H_ #define BASE_MACRO_H_ #if defined(COVERAGE) || !defined(NDEBUG) #define DEBUGING 1 #endif #ifndef SUPPRESS_UNUSED_ATTRIBUE #if defined(__GNUC__) && defined(__clang__) #define UNUSED(x) x __attribute__((__unused__)) #else #define UNUSED(x) x #endif // __GNUC__ #if defined(__GNUC__) && defined(__clang__) #define UNUSED_FUNCTION(x) __attribute__((__unused__)) x #else #define UNUSED_FUNCTION(x) x #endif // __GNUC__ #else #define UNUSED(x) x #define UNUSED_FUNCTION(x) x #endif // SUPPRESS_UNUSED_ATTRIBUE #ifdef __linux__ #define LINUX 1 #define UNIX 1 #elif __APPLE__ #include "TargetConditionals.h" #define APPLE 1 #define UNIX 1 #if TARGET_IPHONE_SIMULATOR #define IOS_SIMULATOR 1 #elif TARGET_OS_IPHONE #define IOS_DEVICE 1 #elif TARGET_OS_MAC #define OSX_DEVICE 1 #else #error "Unknown Apple platform" #endif // DETECT_OSX_DEVICE #elif _WIN32 #ifdef _WIN64 #define WINDOWS 64 #else #define WINDOWS 32 #endif // DETECT_WINDOW_VERSION #elif !defined(BSD) #define UNIX 1 #define BSD 1 #if __FreeBSD__ #define FREEBSD __FreeBSD__ #elif __NetBSD__ #define NETBSD __NetBSD__ #elif defined(__OpenBSD__) #define OPENBSD __OpenBSD__ #elif defined(__DragonFly__) #define DRAGONFLY __DragonFly__ #endif // DETECT_BSD_DISTRIBUTE #endif // DETECT_OS #ifndef __FUNCTION__ #define __FUNCTION__ __func__ #endif // __FUNCTION__ /* * __unqual_scalar_typeof(x) - Declare an unqualified scalar type, leaving * non-scalar types unchanged. */ /* * Prefer C11 _Generic for better compile-times and simpler code. Note: 'char' * is not type-compatible with 'signed char', and we define a separate case. */ #define __scalar_type_to_expr_cases(type) \ unsigned type : (unsigned type)0, signed type : (signed type)0 #if __cplusplus #define __unqual_scalar_typeof(x) __typeof__(x) #else #define __unqual_scalar_typeof(x) \ typeof(_Generic((x), char \ : (char)0, __scalar_type_to_expr_cases(char), \ __scalar_type_to_expr_cases(short), \ __scalar_type_to_expr_cases(int), \ __scalar_type_to_expr_cases(long), \ __scalar_type_to_expr_cases(long long), default \ : (x))) #endif #define READ_ONCE(x) (*(const volatile __unqual_scalar_typeof(x) *)&(x)) #if __cplusplus #define WRITE_ONCE(x, val) \ do { \ *((volatile __typeof__(x) *)&(x)) = (val); \ } while (0) #else #define WRITE_ONCE(x, val) \ do { \ *(volatile typeof(x) *)&(x) = (val); \ } while (0) #endif #endif // BASE_MACRO_H_
26.512821
80
0.586074
b2197c22b854e6a2ce2a8ef59bb63319e91b19fb
267
h
C
MissGem-iOS/MissGem/Category/NSString+MD5.h
AugustusQu/MissGem
fd4edc58fbb5e5a1bc6862262e6cbeb8f8fee18b
[ "Apache-2.0" ]
null
null
null
MissGem-iOS/MissGem/Category/NSString+MD5.h
AugustusQu/MissGem
fd4edc58fbb5e5a1bc6862262e6cbeb8f8fee18b
[ "Apache-2.0" ]
null
null
null
MissGem-iOS/MissGem/Category/NSString+MD5.h
AugustusQu/MissGem
fd4edc58fbb5e5a1bc6862262e6cbeb8f8fee18b
[ "Apache-2.0" ]
null
null
null
// // NSString+MD5.h // leZhuoGameSDk // // Created by xiang on 16/5/12. // Copyright © 2016年 ZhanxiangQu. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (MD5) /** * 将字符串进行MD5 * * @return MD5后的字符串 */ - (NSString *)MD5; @end
14.052632
55
0.644195
c969d29f9881317c3bf7526ab1d4ebf7b754ba60
906
h
C
src/AppLines/b3ProfileBevelStumpSpline.h
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/b3ProfileBevelStumpSpline.h
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/b3ProfileBevelStumpSpline.h
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3ProfileBevelStumpSpline.h $ ** $Release: Dortmund 2002 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - Profile template ** ** (C) Copyright 2002 Steffen A. Mork ** All Rights Reserved ** ** */ #ifndef B3_PROFILE_BEVELSTUMP_SPLINE_H #define B3_PROFILE_BEVELSTUMP_SPLINE_H #include "b3Profile.h" #include "DlgProfileBevelStumpSpline.h" class b3ProfileBevelStumpSpline : public b3Profile { static b3ProfileBevelStumpSpline m_RegisterProfile; public: b3ProfileBevelStumpSpline(); virtual b3_bool b3Create(); virtual b3_bool b3MatchClassType(b3_u32 class_type); virtual int b3AddImage(CImageList * images); virtual b3_bool b3ComputeProfile(b3Spline * spline, ...); virtual b3_bool b3ComputeShape(b3Spline * spline, b3Shape * shape, ...); }; #endif
23.842105
88
0.678808
c73de6e4956fa665fe62c19a32d6555d1d92ff08
301
h
C
Labs/Cpp6/Task3/Animal.h
yolorusher/C-Labs
fbb9f502dad6860d1d9ac562cad38aea67f6f5ae
[ "Apache-2.0" ]
1
2021-04-19T00:16:09.000Z
2021-04-19T00:16:09.000Z
Labs/Cpp6/Task3/Animal.h
shaykhullinsergey/C-Labs
fbb9f502dad6860d1d9ac562cad38aea67f6f5ae
[ "Apache-2.0" ]
null
null
null
Labs/Cpp6/Task3/Animal.h
shaykhullinsergey/C-Labs
fbb9f502dad6860d1d9ac562cad38aea67f6f5ae
[ "Apache-2.0" ]
null
null
null
#pragma once class Animal { protected: char* _name; char*_mood; int _legs; bool _hunger; public: Animal(char*, char*, int, bool); virtual void Move() = 0; virtual void Eat() = 0; virtual void Talk() = 0; virtual void Cry() = 0; virtual void Display(); virtual ~Animal(); };
17.705882
34
0.621262
db4114d907538f2e1a6a8b35806f95fe0008c7e1
224
h
C
allowsBackgroundLocationUpdates/allowsBackgroundLocationUpdates/ViewController.h
zhuzhiwen0527/allowsBackgroundLocationUpdates
b2f84f01f8a62190ccca67ef2fef9955b4c6f14f
[ "MIT" ]
null
null
null
allowsBackgroundLocationUpdates/allowsBackgroundLocationUpdates/ViewController.h
zhuzhiwen0527/allowsBackgroundLocationUpdates
b2f84f01f8a62190ccca67ef2fef9955b4c6f14f
[ "MIT" ]
null
null
null
allowsBackgroundLocationUpdates/allowsBackgroundLocationUpdates/ViewController.h
zhuzhiwen0527/allowsBackgroundLocationUpdates
b2f84f01f8a62190ccca67ef2fef9955b4c6f14f
[ "MIT" ]
null
null
null
// // ViewController.h // allowsBackgroundLocationUpdates // // Created by zzw on 16/4/18. // Copyright © 2016年 zzw. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
14
47
0.705357
71f97e2e4c8faec060de4d68b8c2a330d3275e11
1,073
h
C
sources/availability/availabilityitem.h
arxarian/shiftplanner
53cf12ae240ce65357fdf5da5c65014504998102
[ "MIT" ]
null
null
null
sources/availability/availabilityitem.h
arxarian/shiftplanner
53cf12ae240ce65357fdf5da5c65014504998102
[ "MIT" ]
null
null
null
sources/availability/availabilityitem.h
arxarian/shiftplanner
53cf12ae240ce65357fdf5da5c65014504998102
[ "MIT" ]
null
null
null
#pragma once #include <QDate> #include <QObject> class AvailabilityItem : public QObject { Q_OBJECT Q_PROPERTY(QDate day READ day WRITE setDay NOTIFY dayChanged) Q_PROPERTY(Availability availability READ availability WRITE setAvailability NOTIFY availabilityChanged) public: enum Availability { Day, Morning, Afternoon, MorningOrAfterNoon, Unavailable }; Q_ENUM(Availability) explicit AvailabilityItem(QObject* parent = nullptr); explicit AvailabilityItem(const QDate& day, Availability availability, QObject* parent = nullptr); explicit AvailabilityItem(const QDate& day, const QString& availability, QObject* parent = nullptr); const QString toString(); QDate day() const; Availability availability() const; public slots: void setDay(const QDate& day); void setAvailability(Availability availability); signals: void dayChanged(QDate day); void availabilityChanged(Availability availability); private: QDate m_day; Availability m_availability; };
24.386364
108
0.724138
b3413124e5c5b24f68de94344cf5404174715852
6,258
c
C
serial.c
mhk3000/grbLeightcee
f8e521e17602432fd001f70e20afdddd80ffb18a
[ "MIT" ]
null
null
null
serial.c
mhk3000/grbLeightcee
f8e521e17602432fd001f70e20afdddd80ffb18a
[ "MIT" ]
null
null
null
serial.c
mhk3000/grbLeightcee
f8e521e17602432fd001f70e20afdddd80ffb18a
[ "MIT" ]
null
null
null
/* serial.c - Low level functions for sending and recieving bytes via the serial port Part of Grbl The MIT License (MIT) GRBL(tm) - Embedded CNC g-code interpreter and motion-controller Copyright (c) 2009-2011 Simen Svale Skogsrud Copyright (c) 2011-2012 Sungeun K. Jeon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <avr/interrupt.h> #include "serial.h" #include "config.h" #include "motion_control.h" #include "protocol.h" uint8_t serial_rx_buffer[RX_BUFFER_SIZE]; uint8_t serial_rx_buffer_head = 0; volatile uint8_t serial_rx_buffer_tail = 0; uint8_t serial_tx_buffer[RX_BUFFER_SIZE]; uint8_t serial_tx_buffer_head = 0; volatile uint8_t serial_tx_buffer_tail = 0; #ifdef ENABLE_XONXOFF volatile uint8_t flow_ctrl = XON_SENT; // Flow control state variable // Returns the number of bytes in the RX buffer. This replaces a typical byte counter to prevent // the interrupt and main programs from writing to the counter at the same time. static uint8_t get_serial_rx_buffer_count() { if (serial_rx_buffer_head == serial_rx_buffer_tail) { return(0); } if (serial_rx_buffer_head < serial_rx_buffer_tail) { return(serial_rx_buffer_tail-serial_rx_buffer_head); } return (RX_BUFFER_SIZE - (serial_rx_buffer_head-serial_rx_buffer_tail)); } #endif void serial_init() { // Set baud rate #if BAUD_RATE < 57600 uint16_t UBRR0_value = ((F_CPU / (8L * BAUD_RATE)) - 1)/2 ; UCSR0A &= ~(1 << U2X0); // baud doubler off - Only needed on Uno XXX #else uint16_t UBRR0_value = ((F_CPU / (4L * BAUD_RATE)) - 1)/2; UCSR0A |= (1 << U2X0); // baud doubler on for high baud rates, i.e. 115200 #endif UBRR0H = UBRR0_value >> 8; UBRR0L = UBRR0_value; // enable rx and tx UCSR0B |= 1<<RXEN0; UCSR0B |= 1<<TXEN0; // enable interrupt on complete reception of a byte UCSR0B |= 1<<RXCIE0; // defaults to 8-bit, no parity, 1 stop bit } void serial_write(uint8_t data) { // Calculate next head uint8_t next_head = serial_tx_buffer_head + 1; if (next_head == TX_BUFFER_SIZE) { next_head = 0; } // Wait until there is space in the buffer while (next_head == serial_tx_buffer_tail) { if (sys.execute & EXEC_RESET) { return; } // Only check for abort to avoid an endless loop. } // Store data and advance head serial_tx_buffer[serial_tx_buffer_head] = data; serial_tx_buffer_head = next_head; // Enable Data Register Empty Interrupt to make sure tx-streaming is running UCSR0B |= (1 << UDRIE0); } // Data Register Empty Interrupt handler ISR(SERIAL_UDRE) { // Temporary serial_tx_buffer_tail (to optimize for volatile) uint8_t tail = serial_tx_buffer_tail; #ifdef ENABLE_XONXOFF if (flow_ctrl == SEND_XOFF) { UDR0 = XOFF_CHAR; flow_ctrl = XOFF_SENT; } else if (flow_ctrl == SEND_XON) { UDR0 = XON_CHAR; flow_ctrl = XON_SENT; } else #endif { // Send a byte from the buffer UDR0 = serial_tx_buffer[tail]; // Update tail position tail++; if (tail == TX_BUFFER_SIZE) { tail = 0; } serial_tx_buffer_tail = tail; } // Turn off Data Register Empty Interrupt to stop tx-streaming if this concludes the transfer if (tail == serial_tx_buffer_head) { UCSR0B &= ~(1 << UDRIE0); } } uint8_t serial_read() { uint8_t tail = serial_rx_buffer_tail; // Temporary serial_rx_buffer_tail (to optimize for volatile) if (serial_rx_buffer_head == tail) { return SERIAL_NO_DATA; } else { uint8_t data = serial_rx_buffer[tail]; tail++; if (tail == RX_BUFFER_SIZE) { tail = 0; } serial_rx_buffer_tail = tail; #ifdef ENABLE_XONXOFF if ((get_serial_rx_buffer_count() < serial_rx_buffer_LOW) && flow_ctrl == XOFF_SENT) { flow_ctrl = SEND_XON; UCSR0B |= (1 << UDRIE0); // Force TX } #endif return data; } } ISR(SERIAL_RX) { uint8_t data = UDR0; uint8_t next_head; // Pick off runtime command characters directly from the serial stream. These characters are // not passed into the buffer, but these set system state flag bits for runtime execution. switch (data) { case CMD_STATUS_REPORT: sys.execute |= EXEC_STATUS_REPORT; break; // Set as true case CMD_CYCLE_START: sys.execute |= EXEC_CYCLE_START; break; // Set as true case CMD_FEED_HOLD: sys.execute |= EXEC_FEED_HOLD; break; // Set as true case CMD_RESET: mc_reset(); break; // Call motion control reset routine. default: // Write character to buffer next_head = serial_rx_buffer_head + 1; if (next_head == RX_BUFFER_SIZE) { next_head = 0; } // Write data to buffer unless it is full. if (next_head != serial_rx_buffer_tail) { serial_rx_buffer[serial_rx_buffer_head] = data; serial_rx_buffer_head = next_head; #ifdef ENABLE_XONXOFF if ((get_serial_rx_buffer_count() >= serial_rx_buffer_FULL) && flow_ctrl == XON_SENT) { flow_ctrl = SEND_XOFF; UCSR0B |= (1 << UDRIE0); // Force TX } #endif } } } void serial_reset_read_buffer() { serial_rx_buffer_tail = serial_rx_buffer_head; #ifdef ENABLE_XONXOFF flow_ctrl = XON_SENT; #endif }
32.936842
111
0.69527
8303e1871d6e9b7cb23a885dd68c4158701da24d
4,806
c
C
codesafe/src/secure_boot_debug/util.c
ARM-software/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
2
2021-06-14T17:29:27.000Z
2021-07-04T00:13:39.000Z
codesafe/src/secure_boot_debug/util.c
QPC-database/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
null
null
null
codesafe/src/secure_boot_debug/util.c
QPC-database/Cryptocell-713-TEE-Lib
bc0aca96f9769bba1a5927aa2bc6b82ceee94dea
[ "BSD-3-Clause" ]
5
2021-01-24T11:06:38.000Z
2021-07-04T00:13:40.000Z
/* * Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause OR Arm's non-OSI source license * */ #define CC_PAL_LOG_CUR_COMPONENT CC_LOG_MASK_SECURE_BOOT /************* Include Files ****************/ #include "util.h" /************************ Defines ******************************/ /* rotate 32-bits word by 16 bits */ #define UTIL_ROT32(x) ( (x) >> 16 | (x) << 16 ) /* inverse the bytes order in a word */ #define UTIL_REVERSE32(x) ( ((UTIL_ROT32((x)) & 0xff00ff00UL) >> 8) | ((UTIL_ROT32((x)) & 0x00ff00ffUL) << 8) ) /******************** Private Functions ************************/ /* ------------------------------------------------------------ ** * @brief This function executes a reversed bytes copy on a specified buffer. * * on a 6 byte buffer: * * buff[5] <---> buff[0] * buff[4] <---> buff[1] * buff[3] <---> buff[2] * * @param[in] dst_ptr - The counter buffer. * @param[in] src_ptr - The counter size in bytes. * */ void UTIL_ReverseBuff( uint8_t *pBuff , uint32_t size ) { /* FUNCTION DECLARATIONS */ /* loop variable */ uint32_t i; /* a temp variable */ uint32_t temp; /* FUNCTION LOGIC */ /* execute the reverse memcopy */ for( i = 0 ; i < (size / 2) ; i++ ) { temp = pBuff[i]; pBuff[i] = pBuff[size - i - 1]; pBuff[size - i - 1] = temp; } return; }/* END OF UTIL_ReverseBuff */ /* ------------------------------------------------------------ ** * @brief This function executes a memory copy from one buffer to enother. * * Assuming: There no overlapping of the buffers. * * @param[in] pDst - The first counter buffer. * @param[in] pSrc - The second counter buffer. * @param[in] size - The counters size in bytes. * */ void UTIL_MemCopy( uint8_t *pDst , const uint8_t *pSrc , uint32_t size ) { /* FUNCTION DECLARATIONS */ /* loop variable */ uint32_t i; /* FUNCTION LOGIC */ /* execute memcopy */ for (i = 0; i < size; i++) pDst[i] = pSrc[i]; return; }/* END OF UTIL_MemCopy */ /* ------------------------------------------------------------ ** * @brief This function executes a reverse bytes copying from one buffer to another buffer. * Overlapping is not allowed, besides in-place operation. * * @param[in] pDst - The pointer to destination buffer. * @param[in] pSrc - The pointer to source buffer. * @param[in] size - The size in bytes. * */ void UTIL_ReverseMemCopy( uint8_t *pDst, uint8_t *pSrc, uint32_t size ) { /* FUNCTION DECLARATIONS */ /* loop variable */ uint32_t i; uint8_t tmp; /* buffers position identifiers */ uint32_t dstPos, srcPos; /* FUNCTION LOGIC */ /* initialize the source and the destination position */ dstPos = size - 1; srcPos = 0; /* execute the reverse copy in case of different buffers */ if (pDst != pSrc) { for( i = 0 ; i < size ; i++ ) pDst[dstPos--] = pSrc[srcPos++]; } else { /* execute the reverse copy in case of in-place reversing */ for( i = 0 ; i < size/2 ; i++ ) { tmp = pDst[dstPos]; pDst[dstPos--] = pSrc[srcPos]; pSrc[srcPos++] = tmp; } } return; }/* END OF UTIL_ReverseMemCopy */ /* ------------------------------------------------------------ ** * @brief This function executes a memory set operation on a buffer. * * @param[in] pBuff - The buffer. * @param[in] val - The value to set the buffer. * @param[in] size - The buffers size. * */ void UTIL_MemSet( uint8_t *pBuff, uint8_t val, uint32_t size ) { /* FUNCTION DECLARATIONS */ /* loop variable */ uint32_t i; /* FUNCTION LOGIC */ for (i = 0 ; i < size ; i++) pBuff[i] = val; return; }/* END OF UTIL_MemSet */ /* ------------------------------------------------------------ */ /* * @brief This function executes a memory secure comparing of 2 buffers. * * @param [in] pBuff1 - The first counter buffer. * @param [in] pBuff2 - The second counter buffer. * @param [in] size - Tthe first counter size in bytes. * @return 1 - if buffers are equalled, 0 - otherwaise. */ /* Trust in Soft annotations - __TRUSTINSOFT_ANALYZER__ */ /*@ requires \initialized(pBuff1 + (0 .. size -1)); requires \initialized(pBuff2 + (0 .. size -1)); */ uint32_t UTIL_MemCmp( uint8_t *pBuff1 , uint8_t *pBuff2 , uint32_t size ) { /* FUNCTION DECLARATIONS */ /* loop variable */ uint32_t i; uint32_t stat = 0; /* FUNCTION LOGIC */ for( i = 0; i < size; i++ ) { stat |= (pBuff1[i] ^ pBuff2[i]); } if(stat == 0) return CC_TRUE; else return CC_FALSE; }/* END OF UTIL_MemCmp */
24.773196
112
0.537245
04517827b796cade46615cd97fa02cc3f05fc70a
1,351
h
C
src/net/dcsctp/common/str_join.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
344
2016-07-03T11:45:20.000Z
2022-03-19T16:54:10.000Z
src/net/dcsctp/common/str_join.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
59
2020-08-24T09:17:42.000Z
2022-02-27T23:33:37.000Z
src/net/dcsctp/common/str_join.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
278
2016-04-26T07:37:12.000Z
2022-01-24T10:09:44.000Z
/* * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef NET_DCSCTP_COMMON_STR_JOIN_H_ #define NET_DCSCTP_COMMON_STR_JOIN_H_ #include <string> #include "absl/strings/string_view.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { template <typename Range> std::string StrJoin(const Range& seq, absl::string_view delimiter) { rtc::StringBuilder sb; int idx = 0; for (const typename Range::value_type& elem : seq) { if (idx > 0) { sb << delimiter; } sb << elem; ++idx; } return sb.Release(); } template <typename Range, typename Functor> std::string StrJoin(const Range& seq, absl::string_view delimiter, const Functor& fn) { rtc::StringBuilder sb; int idx = 0; for (const typename Range::value_type& elem : seq) { if (idx > 0) { sb << delimiter; } fn(sb, elem); ++idx; } return sb.Release(); } } // namespace dcsctp #endif // NET_DCSCTP_COMMON_STR_JOIN_H_
23.701754
71
0.669134
44cdf561f7d2c2cf8c7dcccc935585909a59783a
2,414
h
C
xmysqlnd/xmysqlnd_warning_list.h
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
14
2017-11-16T03:13:31.000Z
2022-03-10T14:59:53.000Z
xmysqlnd/xmysqlnd_warning_list.h
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
8
2018-03-02T06:08:27.000Z
2022-01-18T10:34:43.000Z
xmysqlnd/xmysqlnd_warning_list.h
kirmorozov/pecl-database-mysql_xdevapi
214e0b13dcea17dfa86000092860e3fb35f02257
[ "PHP-3.01" ]
18
2018-03-01T13:45:16.000Z
2022-03-10T06:30:02.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andrey Hristov <andrey@php.net> | +----------------------------------------------------------------------+ */ #ifndef XMYSQLND_WARNING_LIST_H #define XMYSQLND_WARNING_LIST_H #include "xmysqlnd_driver.h" #include "xmysqlnd_wireprotocol_types.h" /* enum xmysqlnd_stmt_warning_level */ namespace mysqlx { namespace drv { // marines: TODO problems with custom allocator vs emplace_back && in-place initialization struct st_xmysqlnd_warning //: public util::custom_allocable { util::string message; unsigned int code; xmysqlnd_stmt_warning_level level; }; using XMYSQLND_WARNING = st_xmysqlnd_warning; class xmysqlnd_warning_list : public util::custom_allocable { public: xmysqlnd_warning_list(); void add_warning( const xmysqlnd_stmt_warning_level level, const unsigned int code, const util::string_view& message); std::size_t count() const; XMYSQLND_WARNING get_warning(std::size_t index) const; private: util::vector<st_xmysqlnd_warning> warnings; }; using XMYSQLND_WARNING_LIST = xmysqlnd_warning_list; XMYSQLND_WARNING_LIST* xmysqlnd_warning_list_create(const zend_bool persistent, const MYSQLND_CLASS_METHODS_TYPE(xmysqlnd_object_factory) * const object_factory, MYSQLND_STATS * stats, MYSQLND_ERROR_INFO * error_info); void xmysqlnd_warning_list_free(XMYSQLND_WARNING_LIST* const list); } // namespace drv } // namespace mysqlx #endif /* XMYSQLND_WARNING_LIST_H */
38.31746
218
0.589478
cd0e2b260710db2314f703fe0af5909121c14eac
557
h
C
YuvUtils.h
BeckYoung/libyuv-google
0cf222a9475cac96c0eb8b5a925e9534c86f1b67
[ "BSD-3-Clause" ]
null
null
null
YuvUtils.h
BeckYoung/libyuv-google
0cf222a9475cac96c0eb8b5a925e9534c86f1b67
[ "BSD-3-Clause" ]
null
null
null
YuvUtils.h
BeckYoung/libyuv-google
0cf222a9475cac96c0eb8b5a925e9534c86f1b67
[ "BSD-3-Clause" ]
null
null
null
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_test_x264encoderdemo_YuvUtils */ #ifndef _Included_com_test_x264encoderdemo_YuvUtils #define _Included_com_test_x264encoderdemo_YuvUtils #ifdef __cplusplus extern "C" { #endif /* * Class: com_test_x264encoderdemo_YuvUtils * Method: yuv420Rotate90 * Signature: ([BIII)V */ JNIEXPORT void JNICALL Java_com_test_x264encoderdemo_YuvUtils_yuv420Rotate90 (JNIEnv *, jobject, jbyteArray, jbyteArray, jint, jint, jint); #ifdef __cplusplus } #endif #endif
25.318182
76
0.78456
fae18bbe814cebfd7cdc9f6dab3d90e78bee6543
4,875
c
C
board/stm32f407vet6/vector_handlers.c
aananthcn/osek-os
8a5cf718d444d6f4912f905f9a237f5f15fe4780
[ "MIT", "Apache-2.0", "MIT-0" ]
5
2021-11-07T17:54:22.000Z
2022-02-21T17:29:04.000Z
board/stm32f407vet6/vector_handlers.c
aananthcn/osek-os
8a5cf718d444d6f4912f905f9a237f5f15fe4780
[ "MIT", "Apache-2.0", "MIT-0" ]
null
null
null
board/stm32f407vet6/vector_handlers.c
aananthcn/osek-os
8a5cf718d444d6f4912f905f9a237f5f15fe4780
[ "MIT", "Apache-2.0", "MIT-0" ]
2
2022-01-22T08:41:59.000Z
2022-02-02T16:00:33.000Z
#include <ostypes.h> #include <stdarg.h> #include <stdio.h> #include <os_api.h> #include <sg_ivector.h> #include "stm32f407vet6.h" #include "cortex-m4.h" /* Exception no: 1 */ extern void _Reset_handler(void); /* _Reset_handler is implemented in startup.s */ /* Exception no: 2 */ void __attribute__((interrupt)) _NMI_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* Exception no: 3 */ void __attribute__((interrupt)) _HardFault_handler(unsigned int* pStack) { pr_log("\nEntered a trap function: %s()\n", __func__); if (NVIC_HFSR & (1uL << 31)) { NVIC_HFSR |= (1uL << 31); // Reset Hard Fault status *(pStack + 6u) += 2u; // PC is located on stack at SP + 24 bytes; // increment PC by 2 to skip break instruction. return; // Return to interrupted application } #if DEBUG // // Read NVIC registers // HardFaultRegs.syshndctrl.byte = SYSHND_CTRL; // System Handler Control and State Register HardFaultRegs.mfsr.byte = NVIC_MFSR; // Memory Fault Status Register HardFaultRegs.bfsr.byte = NVIC_BFSR; // Bus Fault Status Register HardFaultRegs.bfar = NVIC_BFAR; // Bus Fault Manage Address Register HardFaultRegs.ufsr.byte = NVIC_UFSR; // Usage Fault Status Register HardFaultRegs.hfsr.byte = NVIC_HFSR; // Hard Fault Status Register HardFaultRegs.dfsr.byte = NVIC_DFSR; // Debug Fault Status Register HardFaultRegs.afsr = NVIC_AFSR; // Auxiliary Fault Status Register // // Halt execution // If NVIC registers indicate readable memory, change the variable value // to != 0 to continue execution. // _Continue = 0u; while (_Continue == 0u) ; // // Read saved registers from the stack // HardFaultRegs.SavedRegs.r0 = pStack[0]; // Register R0 HardFaultRegs.SavedRegs.r1 = pStack[1]; // Register R1 HardFaultRegs.SavedRegs.r2 = pStack[2]; // Register R2 HardFaultRegs.SavedRegs.r3 = pStack[3]; // Register R3 HardFaultRegs.SavedRegs.r12 = pStack[4]; // Register R12 HardFaultRegs.SavedRegs.lr = pStack[5]; // Link register LR HardFaultRegs.SavedRegs.pc = pStack[6]; // Program counter PC HardFaultRegs.SavedRegs.psr.byte = pStack[7]; // Program status word PSR // // Halt execution // To step out of the HardFaultHandler, change the variable value to != 0. // _Continue = 0u; while (_Continue == 0u) { } #else // // If this module is included in a release configuration, // simply stay in the HardFault handler // (void)pStack; do { } while (1); #endif } /* Exception no: 4 */ void __attribute__((interrupt)) _MemManage_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* Exception no: 5 */ void __attribute__((interrupt)) _BusFault_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* Exception no: 6 */ void __attribute__((interrupt)) _UsageFault_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* Exception no: 11 */ void __attribute__((interrupt)) _SVCall_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* Exception no: 12 */ void __attribute__((interrupt)) _DebugMonitor_handler(void) { pr_log("\nEntered function: %s()\n", __func__); _Reset_handler(); } /* Exception no: 14 */ void __attribute__((interrupt)) _PendSV_handler(void) { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } extern void SystemTickISR(void); /* Exception no: 15 */ void __attribute__((interrupt)) _SysTick_handler(void) { SystemTickISR(); } /////////////////////////////////////////////////////////////////////////////// // Exception no: 16 void __attribute__((interrupt)) _irq_handler() { pr_log("\nEntered a trap function: %s()\n", __func__); for (;;); } /* The following function doesn't need for Cortex M4 */ #if 0 void __copy_vectors(void) { extern uint32_t _vectors_start; extern uint32_t _vectors_end; uint32_t *vectors_src = &_vectors_start; uint32_t *vectors_dst = (uint32_t *)0; while (vectors_src < &_vectors_end) *vectors_dst++ = *vectors_src++; } #endif
32.718121
122
0.566974
a380dc7a6909ddaf1763b9e046de0bd3d35bb698
11,664
h
C
aws-cpp-sdk-route53resolver/include/aws/route53resolver/model/FirewallDomainListMetadata.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-route53resolver/include/aws/route53resolver/model/FirewallDomainListMetadata.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-route53resolver/include/aws/route53resolver/model/FirewallDomainListMetadata.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/route53resolver/Route53Resolver_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Route53Resolver { namespace Model { /** * <p>Minimal high-level information for a firewall domain list. The action * <a>ListFirewallDomainLists</a> returns an array of these objects. </p> <p>To * retrieve full information for a firewall domain list, call * <a>GetFirewallDomainList</a> and <a>ListFirewallDomains</a>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/route53resolver-2018-04-01/FirewallDomainListMetadata">AWS * API Reference</a></p> */ class AWS_ROUTE53RESOLVER_API FirewallDomainListMetadata { public: FirewallDomainListMetadata(); FirewallDomainListMetadata(Aws::Utils::Json::JsonView jsonValue); FirewallDomainListMetadata& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The ID of the domain list. </p> */ inline const Aws::String& GetId() const{ return m_id; } /** * <p>The ID of the domain list. </p> */ inline bool IdHasBeenSet() const { return m_idHasBeenSet; } /** * <p>The ID of the domain list. </p> */ inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; } /** * <p>The ID of the domain list. </p> */ inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); } /** * <p>The ID of the domain list. </p> */ inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); } /** * <p>The ID of the domain list. </p> */ inline FirewallDomainListMetadata& WithId(const Aws::String& value) { SetId(value); return *this;} /** * <p>The ID of the domain list. </p> */ inline FirewallDomainListMetadata& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;} /** * <p>The ID of the domain list. </p> */ inline FirewallDomainListMetadata& WithId(const char* value) { SetId(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline FirewallDomainListMetadata& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline FirewallDomainListMetadata& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the firewall domain list metadata.</p> */ inline FirewallDomainListMetadata& WithArn(const char* value) { SetArn(value); return *this;} /** * <p>The name of the domain list. </p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the domain list. </p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the domain list. </p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the domain list. </p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the domain list. </p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the domain list. </p> */ inline FirewallDomainListMetadata& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the domain list. </p> */ inline FirewallDomainListMetadata& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the domain list. </p> */ inline FirewallDomainListMetadata& WithName(const char* value) { SetName(value); return *this;} /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline const Aws::String& GetCreatorRequestId() const{ return m_creatorRequestId; } /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline bool CreatorRequestIdHasBeenSet() const { return m_creatorRequestIdHasBeenSet; } /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline void SetCreatorRequestId(const Aws::String& value) { m_creatorRequestIdHasBeenSet = true; m_creatorRequestId = value; } /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline void SetCreatorRequestId(Aws::String&& value) { m_creatorRequestIdHasBeenSet = true; m_creatorRequestId = std::move(value); } /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline void SetCreatorRequestId(const char* value) { m_creatorRequestIdHasBeenSet = true; m_creatorRequestId.assign(value); } /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline FirewallDomainListMetadata& WithCreatorRequestId(const Aws::String& value) { SetCreatorRequestId(value); return *this;} /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline FirewallDomainListMetadata& WithCreatorRequestId(Aws::String&& value) { SetCreatorRequestId(std::move(value)); return *this;} /** * <p>A unique string defined by you to identify the request. This allows you to * retry failed requests without the risk of running the operation twice. This can * be any unique string, for example, a timestamp. </p> */ inline FirewallDomainListMetadata& WithCreatorRequestId(const char* value) { SetCreatorRequestId(value); return *this;} /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline const Aws::String& GetManagedOwnerName() const{ return m_managedOwnerName; } /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline bool ManagedOwnerNameHasBeenSet() const { return m_managedOwnerNameHasBeenSet; } /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline void SetManagedOwnerName(const Aws::String& value) { m_managedOwnerNameHasBeenSet = true; m_managedOwnerName = value; } /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline void SetManagedOwnerName(Aws::String&& value) { m_managedOwnerNameHasBeenSet = true; m_managedOwnerName = std::move(value); } /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline void SetManagedOwnerName(const char* value) { m_managedOwnerNameHasBeenSet = true; m_managedOwnerName.assign(value); } /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline FirewallDomainListMetadata& WithManagedOwnerName(const Aws::String& value) { SetManagedOwnerName(value); return *this;} /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline FirewallDomainListMetadata& WithManagedOwnerName(Aws::String&& value) { SetManagedOwnerName(std::move(value)); return *this;} /** * <p>The owner of the list, used only for lists that are not managed by you. For * example, the managed domain list <code>AWSManagedDomainsMalwareDomainList</code> * has the managed owner name <code>Route 53 Resolver DNS Firewall</code>.</p> */ inline FirewallDomainListMetadata& WithManagedOwnerName(const char* value) { SetManagedOwnerName(value); return *this;} private: Aws::String m_id; bool m_idHasBeenSet; Aws::String m_arn; bool m_arnHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_creatorRequestId; bool m_creatorRequestIdHasBeenSet; Aws::String m_managedOwnerName; bool m_managedOwnerNameHasBeenSet; }; } // namespace Model } // namespace Route53Resolver } // namespace Aws
38.750831
136
0.675497
9e7cc08921f0b3f628f9fb66bed5f74907f482e7
3,480
h
C
src/parser/ParserDriver.h
remysucre/souffle
0b7add1b6ea75c9d7a52fa292f51f6c2fee3183c
[ "UPL-1.0" ]
null
null
null
src/parser/ParserDriver.h
remysucre/souffle
0b7add1b6ea75c9d7a52fa292f51f6c2fee3183c
[ "UPL-1.0" ]
null
null
null
src/parser/ParserDriver.h
remysucre/souffle
0b7add1b6ea75c9d7a52fa292f51f6c2fee3183c
[ "UPL-1.0" ]
null
null
null
/* * Souffle - A Datalog Compiler * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file ParserDriver.h * * Defines the parser driver. * ***********************************************************************/ #pragma once #include "RelationTag.h" #include "ast/Clause.h" #include "ast/Component.h" #include "ast/ComponentInit.h" #include "ast/Counter.h" #include "ast/Directive.h" #include "ast/FunctorDeclaration.h" #include "ast/Pragma.h" #include "ast/QualifiedName.h" #include "ast/Relation.h" #include "ast/SubsetType.h" #include "ast/TranslationUnit.h" #include "ast/Type.h" #include "parser/SrcLocation.h" #include "reports/DebugReport.h" #include <cstdio> #include <filesystem> #include <memory> #include <set> #include <string> #include <vector> namespace souffle { class ParserDriver { public: virtual ~ParserDriver() = default; void addRelation(Own<ast::Relation> r); void addFunctorDeclaration(Own<ast::FunctorDeclaration> f); void addDirective(Own<ast::Directive> d); void addType(Own<ast::Type> type); void addClause(Own<ast::Clause> c); void addComponent(Own<ast::Component> c); void addInstantiation(Own<ast::ComponentInit> ci); void addPragma(Own<ast::Pragma> p); void addIoFromDeprecatedTag(ast::Relation& r); Own<ast::SubsetType> mkDeprecatedSubType( ast::QualifiedName name, ast::QualifiedName attr, SrcLocation loc); std::set<RelationTag> addReprTag(RelationTag tag, SrcLocation tagLoc, std::set<RelationTag> tags); std::set<RelationTag> addDeprecatedTag(RelationTag tag, SrcLocation tagLoc, std::set<RelationTag> tags); std::set<RelationTag> addTag(RelationTag tag, SrcLocation tagLoc, std::set<RelationTag> tags); std::set<RelationTag> addTag(RelationTag tag, std::vector<RelationTag> incompatible, SrcLocation tagLoc, std::set<RelationTag> tags); Own<ast::Counter> addDeprecatedCounter(SrcLocation tagLoc); Own<ast::TranslationUnit> parse( const std::string& filename, FILE* in, ErrorReport& errorReport, DebugReport& debugReport); Own<ast::TranslationUnit> parse( const std::string& code, ErrorReport& errorReport, DebugReport& debugReport); static Own<ast::TranslationUnit> parseTranslationUnit( const std::string& filename, FILE* in, ErrorReport& errorReport, DebugReport& debugReport); static Own<ast::TranslationUnit> parseTranslationUnit( const std::string& code, ErrorReport& errorReport, DebugReport& debugReport); void warning(const SrcLocation& loc, const std::string& msg); void error(const SrcLocation& loc, const std::string& msg); void error(const std::string& msg); std::optional<std::filesystem::path> searchIncludePath( const std::string& IncludeString, const SrcLocation& IncludeLoc); bool canEnterOnce(const SrcLocation& onceLoc); void addComment(const SrcLocation& Loc, const std::stringstream& Content); Own<ast::TranslationUnit> translationUnit; bool trace_scanning = false; std::set<std::pair<std::filesystem::path, int>> VisitedLocations; std::deque<std::pair<SrcLocation, std::string>> ScannedComments; }; } // end of namespace souffle
35.151515
108
0.689368
9e8e8d9639bbfdf3c2f9149e16a377134d5e94b7
58,267
c
C
release/src/linux/linux/drivers/net/tulip/tulip_core.c
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
80
2015-01-02T10:14:04.000Z
2021-06-07T06:29:49.000Z
release/src/linux/linux/drivers/net/tulip/tulip_core.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
9
2015-05-14T11:03:12.000Z
2018-01-04T07:12:58.000Z
release/src/linux/linux/drivers/net/tulip/tulip_core.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
69
2015-01-02T10:45:56.000Z
2021-09-06T07:52:13.000Z
/* tulip_core.c: A DEC 21x4x-family ethernet driver for Linux. */ /* Maintained by Jeff Garzik <jgarzik@mandrakesoft.com> Copyright 2000-2002 The Linux Kernel Team Written/copyright 1994-2001 by Donald Becker. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Please refer to Documentation/DocBook/tulip.{pdf,ps,html} for more information on this driver, or visit the project Web page at http://sourceforge.net/projects/tulip/ */ #define DRV_NAME "tulip" #define DRV_VERSION "0.9.15-pre12" #define DRV_RELDATE "Aug 9, 2002" #include <linux/config.h> #include <linux/module.h> #include "tulip.h" #include <linux/pci.h> #include <linux/init.h> #include <linux/etherdevice.h> #include <linux/delay.h> #include <linux/mii.h> #include <linux/ethtool.h> #include <linux/crc32.h> #include <asm/unaligned.h> #include <asm/uaccess.h> #ifdef __sparc__ #include <asm/pbm.h> #endif static char version[] __devinitdata = "Linux Tulip driver version " DRV_VERSION " (" DRV_RELDATE ")\n"; /* A few user-configurable values. */ /* Maximum events (Rx packets, etc.) to handle at each interrupt. */ static unsigned int max_interrupt_work = 25; #define MAX_UNITS 8 /* Used to pass the full-duplex flag, etc. */ static int full_duplex[MAX_UNITS]; static int options[MAX_UNITS]; static int mtu[MAX_UNITS]; /* Jumbo MTU for interfaces. */ /* The possible media types that can be set in options[] are: */ const char * const medianame[32] = { "10baseT", "10base2", "AUI", "100baseTx", "10baseT-FDX", "100baseTx-FDX", "100baseT4", "100baseFx", "100baseFx-FDX", "MII 10baseT", "MII 10baseT-FDX", "MII", "10baseT(forced)", "MII 100baseTx", "MII 100baseTx-FDX", "MII 100baseT4", "MII 100baseFx-HDX", "MII 100baseFx-FDX", "Home-PNA 1Mbps", "Invalid-19", "","","","", "","","","", "","","","Transceiver reset", }; /* Set the copy breakpoint for the copy-only-tiny-buffer Rx structure. */ #if defined(__alpha__) || defined(__arm__) || defined(__hppa__) \ || defined(__sparc_) || defined(__ia64__) \ || defined(__sh__) || defined(__mips__) static int rx_copybreak = 1518; #else static int rx_copybreak = 100; #endif /* Set the bus performance register. Typical: Set 16 longword cache alignment, no burst limit. Cache alignment bits 15:14 Burst length 13:8 0000 No alignment 0x00000000 unlimited 0800 8 longwords 4000 8 longwords 0100 1 longword 1000 16 longwords 8000 16 longwords 0200 2 longwords 2000 32 longwords C000 32 longwords 0400 4 longwords Warning: many older 486 systems are broken and require setting 0x00A04800 8 longword cache alignment, 8 longword burst. ToDo: Non-Intel setting could be better. */ #if defined(__alpha__) || defined(__ia64__) || defined(__x86_64__) static int csr0 = 0x01A00000 | 0xE000; #elif defined(__i386__) || defined(__powerpc__) static int csr0 = 0x01A00000 | 0x8000; #elif defined(__sparc__) || defined(__hppa__) /* The UltraSparc PCI controllers will disconnect at every 64-byte * crossing anyways so it makes no sense to tell Tulip to burst * any more than that. */ static int csr0 = 0x01A00000 | 0x9000; #elif defined(__arm__) || defined(__sh__) static int csr0 = 0x01A00000 | 0x4800; #elif defined(__mips__) static int csr0 = 0x00200000 | 0x4000; #else #warning Processor architecture undefined! static int csr0 = 0x00A00000 | 0x4800; #endif /* Operational parameters that usually are not changed. */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (4*HZ) MODULE_AUTHOR("The Linux Kernel Team"); MODULE_DESCRIPTION("Digital 21*4* Tulip ethernet driver"); MODULE_LICENSE("GPL"); MODULE_PARM(tulip_debug, "i"); MODULE_PARM(max_interrupt_work, "i"); MODULE_PARM(rx_copybreak, "i"); MODULE_PARM(csr0, "i"); MODULE_PARM(options, "1-" __MODULE_STRING(MAX_UNITS) "i"); MODULE_PARM(full_duplex, "1-" __MODULE_STRING(MAX_UNITS) "i"); #define PFX DRV_NAME ": " #ifdef TULIP_DEBUG int tulip_debug = TULIP_DEBUG; #else int tulip_debug = 1; #endif /* * This table use during operation for capabilities and media timer. * * It is indexed via the values in 'enum chips' */ struct tulip_chip_table tulip_tbl[] = { /* DC21040 */ { "Digital DC21040 Tulip", 128, 0x0001ebef, 0, tulip_timer }, /* DC21041 */ { "Digital DC21041 Tulip", 128, 0x0001ebef, HAS_MEDIA_TABLE | HAS_NWAY, tulip_timer }, /* DC21140 */ { "Digital DS21140 Tulip", 128, 0x0001ebef, HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_PCI_MWI, tulip_timer }, /* DC21142, DC21143 */ { "Digital DS21143 Tulip", 128, 0x0801fbff, HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI | HAS_NWAY | HAS_INTR_MITIGATION | HAS_PCI_MWI, t21142_timer }, /* LC82C168 */ { "Lite-On 82c168 PNIC", 256, 0x0001fbef, HAS_MII | HAS_PNICNWAY, pnic_timer }, /* MX98713 */ { "Macronix 98713 PMAC", 128, 0x0001ebef, HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer }, /* MX98715 */ { "Macronix 98715 PMAC", 256, 0x0001ebef, HAS_MEDIA_TABLE, mxic_timer }, /* MX98725 */ { "Macronix 98725 PMAC", 256, 0x0001ebef, HAS_MEDIA_TABLE, mxic_timer }, /* AX88140 */ { "ASIX AX88140", 128, 0x0001fbff, HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | MC_HASH_ONLY | IS_ASIX, tulip_timer }, /* PNIC2 */ { "Lite-On PNIC-II", 256, 0x0801fbff, HAS_MII | HAS_NWAY | HAS_8023X | HAS_PCI_MWI, pnic2_timer }, /* COMET */ { "ADMtek Comet", 256, 0x0001abef, MC_HASH_ONLY | COMET_MAC_ADDR, comet_timer }, /* COMPEX9881 */ { "Compex 9881 PMAC", 128, 0x0001ebef, HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer }, /* I21145 */ { "Intel DS21145 Tulip", 128, 0x0801fbff, HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI | HAS_NWAY | HAS_PCI_MWI, t21142_timer }, /* DM910X */ { "Davicom DM9102/DM9102A", 128, 0x0001ebef, HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_ACPI, tulip_timer }, /* CONEXANT */ { "Conexant LANfinity", 256, 0x0001ebef, HAS_MII, tulip_timer }, }; static struct pci_device_id tulip_pci_tbl[] __devinitdata = { { 0x1011, 0x0002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21040 }, { 0x1011, 0x0014, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21041 }, { 0x1011, 0x0009, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21140 }, { 0x1011, 0x0019, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21143 }, { 0x11AD, 0x0002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, LC82C168 }, { 0x10d9, 0x0512, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98713 }, { 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 }, /* { 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98725 },*/ { 0x125B, 0x1400, PCI_ANY_ID, PCI_ANY_ID, 0, 0, AX88140 }, { 0x11AD, 0xc115, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PNIC2 }, { 0x1317, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1317, 0x0985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1317, 0x1985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1317, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x13D1, 0xAB02, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x13D1, 0xAB03, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x13D1, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x104A, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x104A, 0x2774, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1259, 0xa120, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x11F6, 0x9881, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMPEX9881 }, { 0x8086, 0x0039, PCI_ANY_ID, PCI_ANY_ID, 0, 0, I21145 }, { 0x1282, 0x9100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X }, { 0x1282, 0x9102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X }, { 0x1113, 0x1216, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1113, 0x1217, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 }, { 0x1113, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1186, 0x1561, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1626, 0x8410, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x1737, 0xAB09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, { 0x14f1, 0x1803, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CONEXANT }, { } /* terminate list */ }; MODULE_DEVICE_TABLE(pci, tulip_pci_tbl); /* A full-duplex map for media types. */ const char tulip_media_cap[32] = {0,0,0,16, 3,19,16,24, 27,4,7,5, 0,20,23,20, 28,31,0,0, }; u8 t21040_csr13[] = {2,0x0C,8,4, 4,0,0,0, 0,0,0,0, 4,0,0,0}; /* 21041 transceiver register settings: 10-T, 10-2, AUI, 10-T, 10T-FD*/ u16 t21041_csr13[] = { csr13_mask_10bt, /* 10-T */ csr13_mask_auibnc, /* 10-2 */ csr13_mask_auibnc, /* AUI */ csr13_mask_10bt, /* 10-T */ csr13_mask_10bt, /* 10T-FD */ }; u16 t21041_csr14[] = { 0xFFFF, 0xF7FD, 0xF7FD, 0x7F3F, 0x7F3D, }; u16 t21041_csr15[] = { 0x0008, 0x0006, 0x000E, 0x0008, 0x0008, }; static void tulip_tx_timeout(struct net_device *dev); static void tulip_init_ring(struct net_device *dev); static int tulip_start_xmit(struct sk_buff *skb, struct net_device *dev); static int tulip_open(struct net_device *dev); static int tulip_close(struct net_device *dev); static void tulip_up(struct net_device *dev); static void tulip_down(struct net_device *dev); static struct net_device_stats *tulip_get_stats(struct net_device *dev); static int private_ioctl(struct net_device *dev, struct ifreq *rq, int cmd); static void set_rx_mode(struct net_device *dev); static void tulip_set_power_state (struct tulip_private *tp, int sleep, int snooze) { if (tp->flags & HAS_ACPI) { u32 tmp, newtmp; pci_read_config_dword (tp->pdev, CFDD, &tmp); newtmp = tmp & ~(CFDD_Sleep | CFDD_Snooze); if (sleep) newtmp |= CFDD_Sleep; else if (snooze) newtmp |= CFDD_Snooze; if (tmp != newtmp) pci_write_config_dword (tp->pdev, CFDD, newtmp); } } static void tulip_up(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; long ioaddr = dev->base_addr; int next_tick = 3*HZ; int i; /* Wake the chip from sleep/snooze mode. */ tulip_set_power_state (tp, 0, 0); /* On some chip revs we must set the MII/SYM port before the reset!? */ if (tp->mii_cnt || (tp->mtable && tp->mtable->has_mii)) outl(0x00040000, ioaddr + CSR6); /* Reset the chip, holding bit 0 set at least 50 PCI cycles. */ outl(0x00000001, ioaddr + CSR0); udelay(100); /* Deassert reset. Wait the specified 50 PCI cycles after a reset by initializing Tx and Rx queues and the address filter list. */ outl(tp->csr0, ioaddr + CSR0); udelay(100); if (tulip_debug > 1) printk(KERN_DEBUG "%s: tulip_up(), irq==%d.\n", dev->name, dev->irq); outl(tp->rx_ring_dma, ioaddr + CSR3); outl(tp->tx_ring_dma, ioaddr + CSR4); tp->cur_rx = tp->cur_tx = 0; tp->dirty_rx = tp->dirty_tx = 0; if (tp->flags & MC_HASH_ONLY) { u32 addr_low = cpu_to_le32(get_unaligned((u32 *)dev->dev_addr)); u32 addr_high = cpu_to_le32(get_unaligned((u16 *)(dev->dev_addr+4))); if (tp->chip_id == AX88140) { outl(0, ioaddr + CSR13); outl(addr_low, ioaddr + CSR14); outl(1, ioaddr + CSR13); outl(addr_high, ioaddr + CSR14); } else if (tp->flags & COMET_MAC_ADDR) { outl(addr_low, ioaddr + 0xA4); outl(addr_high, ioaddr + 0xA8); outl(0, ioaddr + 0xAC); outl(0, ioaddr + 0xB0); } } else { /* This is set_rx_mode(), but without starting the transmitter. */ u16 *eaddrs = (u16 *)dev->dev_addr; u16 *setup_frm = &tp->setup_frame[15*6]; dma_addr_t mapping; /* 21140 bug: you must add the broadcast address. */ memset(tp->setup_frame, 0xff, sizeof(tp->setup_frame)); /* Fill the final entry of the table with our physical address. */ *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2]; mapping = pci_map_single(tp->pdev, tp->setup_frame, sizeof(tp->setup_frame), PCI_DMA_TODEVICE); tp->tx_buffers[tp->cur_tx].skb = NULL; tp->tx_buffers[tp->cur_tx].mapping = mapping; /* Put the setup frame on the Tx list. */ tp->tx_ring[tp->cur_tx].length = cpu_to_le32(0x08000000 | 192); tp->tx_ring[tp->cur_tx].buffer1 = cpu_to_le32(mapping); tp->tx_ring[tp->cur_tx].status = cpu_to_le32(DescOwned); tp->cur_tx++; } tp->saved_if_port = dev->if_port; if (dev->if_port == 0) dev->if_port = tp->default_port; /* Allow selecting a default media. */ i = 0; if (tp->mtable == NULL) goto media_picked; if (dev->if_port) { int looking_for = tulip_media_cap[dev->if_port] & MediaIsMII ? 11 : (dev->if_port == 12 ? 0 : dev->if_port); for (i = 0; i < tp->mtable->leafcount; i++) if (tp->mtable->mleaf[i].media == looking_for) { printk(KERN_INFO "%s: Using user-specified media %s.\n", dev->name, medianame[dev->if_port]); goto media_picked; } } if ((tp->mtable->defaultmedia & 0x0800) == 0) { int looking_for = tp->mtable->defaultmedia & MEDIA_MASK; for (i = 0; i < tp->mtable->leafcount; i++) if (tp->mtable->mleaf[i].media == looking_for) { printk(KERN_INFO "%s: Using EEPROM-set media %s.\n", dev->name, medianame[looking_for]); goto media_picked; } } /* Start sensing first non-full-duplex media. */ for (i = tp->mtable->leafcount - 1; (tulip_media_cap[tp->mtable->mleaf[i].media] & MediaAlwaysFD) && i > 0; i--) ; media_picked: tp->csr6 = 0; tp->cur_index = i; tp->nwayset = 0; if (dev->if_port) { if (tp->chip_id == DC21143 && (tulip_media_cap[dev->if_port] & MediaIsMII)) { /* We must reset the media CSRs when we force-select MII mode. */ outl(0x0000, ioaddr + CSR13); outl(0x0000, ioaddr + CSR14); outl(0x0008, ioaddr + CSR15); } tulip_select_media(dev, 1); } else if (tp->chip_id == DC21041) { dev->if_port = 0; tp->nway = tp->mediasense = 1; tp->nwayset = tp->lpar = 0; outl(0x00000000, ioaddr + CSR13); outl(0xFFFFFFFF, ioaddr + CSR14); outl(0x00000008, ioaddr + CSR15); /* Listen on AUI also. */ tp->csr6 = 0x80020000; if (tp->sym_advertise & 0x0040) tp->csr6 |= FullDuplex; outl(tp->csr6, ioaddr + CSR6); outl(0x0000EF01, ioaddr + CSR13); } else if (tp->chip_id == DC21142) { if (tp->mii_cnt) { tulip_select_media(dev, 1); if (tulip_debug > 1) printk(KERN_INFO "%s: Using MII transceiver %d, status " "%4.4x.\n", dev->name, tp->phys[0], tulip_mdio_read(dev, tp->phys[0], 1)); outl(csr6_mask_defstate, ioaddr + CSR6); tp->csr6 = csr6_mask_hdcap; dev->if_port = 11; outl(0x0000, ioaddr + CSR13); outl(0x0000, ioaddr + CSR14); } else t21142_start_nway(dev); } else if (tp->chip_id == PNIC2) { /* for initial startup advertise 10/100 Full and Half */ tp->sym_advertise = 0x01E0; /* enable autonegotiate end interrupt */ outl(inl(ioaddr+CSR5)| 0x00008010, ioaddr + CSR5); outl(inl(ioaddr+CSR7)| 0x00008010, ioaddr + CSR7); pnic2_start_nway(dev); } else if (tp->chip_id == LC82C168 && ! tp->medialock) { if (tp->mii_cnt) { dev->if_port = 11; tp->csr6 = 0x814C0000 | (tp->full_duplex ? 0x0200 : 0); outl(0x0001, ioaddr + CSR15); } else if (inl(ioaddr + CSR5) & TPLnkPass) pnic_do_nway(dev); else { /* Start with 10mbps to do autonegotiation. */ outl(0x32, ioaddr + CSR12); tp->csr6 = 0x00420000; outl(0x0001B078, ioaddr + 0xB8); outl(0x0201B078, ioaddr + 0xB8); next_tick = 1*HZ; } } else if ((tp->chip_id == MX98713 || tp->chip_id == COMPEX9881) && ! tp->medialock) { dev->if_port = 0; tp->csr6 = 0x01880000 | (tp->full_duplex ? 0x0200 : 0); outl(0x0f370000 | inw(ioaddr + 0x80), ioaddr + 0x80); } else if (tp->chip_id == MX98715 || tp->chip_id == MX98725) { /* Provided by BOLO, Macronix - 12/10/1998. */ dev->if_port = 0; tp->csr6 = 0x01a80200; outl(0x0f370000 | inw(ioaddr + 0x80), ioaddr + 0x80); outl(0x11000 | inw(ioaddr + 0xa0), ioaddr + 0xa0); } else if (tp->chip_id == COMET || tp->chip_id == CONEXANT) { /* Enable automatic Tx underrun recovery. */ outl(inl(ioaddr + 0x88) | 1, ioaddr + 0x88); dev->if_port = tp->mii_cnt ? 11 : 0; tp->csr6 = 0x00040000; } else if (tp->chip_id == AX88140) { tp->csr6 = tp->mii_cnt ? 0x00040100 : 0x00000100; } else tulip_select_media(dev, 1); /* Start the chip's Tx to process setup frame. */ tulip_stop_rxtx(tp); barrier(); udelay(5); outl(tp->csr6 | TxOn, ioaddr + CSR6); /* Enable interrupts by setting the interrupt mask. */ outl(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR5); outl(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR7); tulip_start_rxtx(tp); outl(0, ioaddr + CSR2); /* Rx poll demand */ if (tulip_debug > 2) { printk(KERN_DEBUG "%s: Done tulip_up(), CSR0 %8.8x, CSR5 %8.8x CSR6 %8.8x.\n", dev->name, inl(ioaddr + CSR0), inl(ioaddr + CSR5), inl(ioaddr + CSR6)); } /* Set the timer to switch to check for link beat and perhaps switch to an alternate media type. */ tp->timer.expires = RUN_AT(next_tick); add_timer(&tp->timer); } #ifdef CONFIG_NET_HW_FLOWCONTROL /* Enable receiver */ void tulip_xon(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; clear_bit(tp->fc_bit, &netdev_fc_xoff); if (netif_running(dev)){ tulip_refill_rx(dev); outl(tulip_tbl[tp->chip_id].valid_intrs, dev->base_addr+CSR7); } } #endif static int tulip_open(struct net_device *dev) { #ifdef CONFIG_NET_HW_FLOWCONTROL struct tulip_private *tp = (struct tulip_private *)dev->priv; #endif int retval; MOD_INC_USE_COUNT; if ((retval = request_irq(dev->irq, &tulip_interrupt, SA_SHIRQ, dev->name, dev))) { MOD_DEC_USE_COUNT; return retval; } tulip_init_ring (dev); tulip_up (dev); #ifdef CONFIG_NET_HW_FLOWCONTROL tp->fc_bit = netdev_register_fc(dev, tulip_xon); #endif netif_start_queue (dev); return 0; } static void tulip_tx_timeout(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; long ioaddr = dev->base_addr; unsigned long flags; spin_lock_irqsave (&tp->lock, flags); if (tulip_media_cap[dev->if_port] & MediaIsMII) { /* Do nothing -- the media monitor should handle this. */ if (tulip_debug > 1) printk(KERN_WARNING "%s: Transmit timeout using MII device.\n", dev->name); } else if (tp->chip_id == DC21040) { if ( !tp->medialock && inl(ioaddr + CSR12) & 0x0002) { dev->if_port = (dev->if_port == 2 ? 0 : 2); printk(KERN_INFO "%s: 21040 transmit timed out, switching to " "%s.\n", dev->name, medianame[dev->if_port]); tulip_select_media(dev, 0); } goto out; } else if (tp->chip_id == DC21041) { int csr12 = inl(ioaddr + CSR12); printk(KERN_WARNING "%s: 21041 transmit timed out, status %8.8x, " "CSR12 %8.8x, CSR13 %8.8x, CSR14 %8.8x, resetting...\n", dev->name, inl(ioaddr + CSR5), csr12, inl(ioaddr + CSR13), inl(ioaddr + CSR14)); tp->mediasense = 1; if ( ! tp->medialock) { if (dev->if_port == 1 || dev->if_port == 2) if (csr12 & 0x0004) { dev->if_port = 2 - dev->if_port; } else dev->if_port = 0; else dev->if_port = 1; tulip_select_media(dev, 0); } } else if (tp->chip_id == DC21140 || tp->chip_id == DC21142 || tp->chip_id == MX98713 || tp->chip_id == COMPEX9881 || tp->chip_id == DM910X) { printk(KERN_WARNING "%s: 21140 transmit timed out, status %8.8x, " "SIA %8.8x %8.8x %8.8x %8.8x, resetting...\n", dev->name, inl(ioaddr + CSR5), inl(ioaddr + CSR12), inl(ioaddr + CSR13), inl(ioaddr + CSR14), inl(ioaddr + CSR15)); if ( ! tp->medialock && tp->mtable) { do --tp->cur_index; while (tp->cur_index >= 0 && (tulip_media_cap[tp->mtable->mleaf[tp->cur_index].media] & MediaIsFD)); if (--tp->cur_index < 0) { /* We start again, but should instead look for default. */ tp->cur_index = tp->mtable->leafcount - 1; } tulip_select_media(dev, 0); printk(KERN_WARNING "%s: transmit timed out, switching to %s " "media.\n", dev->name, medianame[dev->if_port]); } } else if (tp->chip_id == PNIC2) { printk(KERN_WARNING "%s: PNIC2 transmit timed out, status %8.8x, " "CSR6/7 %8.8x / %8.8x CSR12 %8.8x, resetting...\n", dev->name, (int)inl(ioaddr + CSR5), (int)inl(ioaddr + CSR6), (int)inl(ioaddr + CSR7), (int)inl(ioaddr + CSR12)); } else { printk(KERN_WARNING "%s: Transmit timed out, status %8.8x, CSR12 " "%8.8x, resetting...\n", dev->name, inl(ioaddr + CSR5), inl(ioaddr + CSR12)); dev->if_port = 0; } #if defined(way_too_many_messages) if (tulip_debug > 3) { int i; for (i = 0; i < RX_RING_SIZE; i++) { u8 *buf = (u8 *)(tp->rx_ring[i].buffer1); int j; printk(KERN_DEBUG "%2d: %8.8x %8.8x %8.8x %8.8x " "%2.2x %2.2x %2.2x.\n", i, (unsigned int)tp->rx_ring[i].status, (unsigned int)tp->rx_ring[i].length, (unsigned int)tp->rx_ring[i].buffer1, (unsigned int)tp->rx_ring[i].buffer2, buf[0], buf[1], buf[2]); for (j = 0; buf[j] != 0xee && j < 1600; j++) if (j < 100) printk(" %2.2x", buf[j]); printk(" j=%d.\n", j); } printk(KERN_DEBUG " Rx ring %8.8x: ", (int)tp->rx_ring); for (i = 0; i < RX_RING_SIZE; i++) printk(" %8.8x", (unsigned int)tp->rx_ring[i].status); printk("\n" KERN_DEBUG " Tx ring %8.8x: ", (int)tp->tx_ring); for (i = 0; i < TX_RING_SIZE; i++) printk(" %8.8x", (unsigned int)tp->tx_ring[i].status); printk("\n"); } #endif /* Stop and restart the chip's Tx processes . */ #ifdef CONFIG_NET_HW_FLOWCONTROL if (tp->fc_bit && test_bit(tp->fc_bit,&netdev_fc_xoff)) printk("BUG tx_timeout restarting rx when fc on\n"); #endif tulip_restart_rxtx(tp); /* Trigger an immediate transmit demand. */ outl(0, ioaddr + CSR1); tp->stats.tx_errors++; out: spin_unlock_irqrestore (&tp->lock, flags); dev->trans_start = jiffies; netif_wake_queue (dev); } /* Initialize the Rx and Tx rings, along with various 'dev' bits. */ static void tulip_init_ring(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; int i; tp->susp_rx = 0; tp->ttimer = 0; tp->nir = 0; for (i = 0; i < RX_RING_SIZE; i++) { tp->rx_ring[i].status = 0x00000000; tp->rx_ring[i].length = cpu_to_le32(PKT_BUF_SZ); tp->rx_ring[i].buffer2 = cpu_to_le32(tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * (i + 1)); tp->rx_buffers[i].skb = NULL; tp->rx_buffers[i].mapping = 0; } /* Mark the last entry as wrapping the ring. */ tp->rx_ring[i-1].length = cpu_to_le32(PKT_BUF_SZ | DESC_RING_WRAP); tp->rx_ring[i-1].buffer2 = cpu_to_le32(tp->rx_ring_dma); for (i = 0; i < RX_RING_SIZE; i++) { dma_addr_t mapping; /* Note the receive buffer must be longword aligned. dev_alloc_skb() provides 16 byte alignment. But do *not* use skb_reserve() to align the IP header! */ struct sk_buff *skb = dev_alloc_skb(PKT_BUF_SZ); tp->rx_buffers[i].skb = skb; if (skb == NULL) break; mapping = pci_map_single(tp->pdev, skb->tail, PKT_BUF_SZ, PCI_DMA_FROMDEVICE); tp->rx_buffers[i].mapping = mapping; skb->dev = dev; /* Mark as being used by this device. */ tp->rx_ring[i].status = cpu_to_le32(DescOwned); /* Owned by Tulip chip */ tp->rx_ring[i].buffer1 = cpu_to_le32(mapping); } tp->dirty_rx = (unsigned int)(i - RX_RING_SIZE); /* The Tx buffer descriptor is filled in as needed, but we do need to clear the ownership bit. */ for (i = 0; i < TX_RING_SIZE; i++) { tp->tx_buffers[i].skb = NULL; tp->tx_buffers[i].mapping = 0; tp->tx_ring[i].status = 0x00000000; tp->tx_ring[i].buffer2 = cpu_to_le32(tp->tx_ring_dma + sizeof(struct tulip_tx_desc) * (i + 1)); } tp->tx_ring[i-1].buffer2 = cpu_to_le32(tp->tx_ring_dma); } static int tulip_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; int entry; u32 flag; dma_addr_t mapping; unsigned long eflags; spin_lock_irqsave(&tp->lock, eflags); /* Calculate the next Tx descriptor entry. */ entry = tp->cur_tx % TX_RING_SIZE; tp->tx_buffers[entry].skb = skb; mapping = pci_map_single(tp->pdev, skb->data, skb->len, PCI_DMA_TODEVICE); tp->tx_buffers[entry].mapping = mapping; tp->tx_ring[entry].buffer1 = cpu_to_le32(mapping); if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE/2) {/* Typical path */ flag = 0x60000000; /* No interrupt */ } else if (tp->cur_tx - tp->dirty_tx == TX_RING_SIZE/2) { flag = 0xe0000000; /* Tx-done intr. */ } else if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE - 2) { flag = 0x60000000; /* No Tx-done intr. */ } else { /* Leave room for set_rx_mode() to fill entries. */ flag = 0xe0000000; /* Tx-done intr. */ netif_stop_queue(dev); } if (entry == TX_RING_SIZE-1) flag = 0xe0000000 | DESC_RING_WRAP; tp->tx_ring[entry].length = cpu_to_le32(skb->len | flag); /* if we were using Transmit Automatic Polling, we would need a * wmb() here. */ tp->tx_ring[entry].status = cpu_to_le32(DescOwned); wmb(); tp->cur_tx++; /* Trigger an immediate transmit demand. */ outl(0, dev->base_addr + CSR1); spin_unlock_irqrestore(&tp->lock, eflags); dev->trans_start = jiffies; return 0; } static void tulip_clean_tx_ring(struct tulip_private *tp) { unsigned int dirty_tx; for (dirty_tx = tp->dirty_tx ; tp->cur_tx - dirty_tx > 0; dirty_tx++) { int entry = dirty_tx % TX_RING_SIZE; int status = le32_to_cpu(tp->tx_ring[entry].status); if (status < 0) { tp->stats.tx_errors++; /* It wasn't Txed */ tp->tx_ring[entry].status = 0; } /* Check for Tx filter setup frames. */ if (tp->tx_buffers[entry].skb == NULL) { /* test because dummy frames not mapped */ if (tp->tx_buffers[entry].mapping) pci_unmap_single(tp->pdev, tp->tx_buffers[entry].mapping, sizeof(tp->setup_frame), PCI_DMA_TODEVICE); continue; } pci_unmap_single(tp->pdev, tp->tx_buffers[entry].mapping, tp->tx_buffers[entry].skb->len, PCI_DMA_TODEVICE); /* Free the original skb. */ dev_kfree_skb_irq(tp->tx_buffers[entry].skb); tp->tx_buffers[entry].skb = NULL; tp->tx_buffers[entry].mapping = 0; } } static void tulip_down (struct net_device *dev) { long ioaddr = dev->base_addr; struct tulip_private *tp = (struct tulip_private *) dev->priv; unsigned long flags; del_timer_sync (&tp->timer); spin_lock_irqsave (&tp->lock, flags); /* Disable interrupts by clearing the interrupt mask. */ outl (0x00000000, ioaddr + CSR7); /* Stop the Tx and Rx processes. */ tulip_stop_rxtx(tp); /* prepare receive buffers */ tulip_refill_rx(dev); /* release any unconsumed transmit buffers */ tulip_clean_tx_ring(tp); /* 21040 -- Leave the card in 10baseT state. */ if (tp->chip_id == DC21040) outl (0x00000004, ioaddr + CSR13); if (inl (ioaddr + CSR6) != 0xffffffff) tp->stats.rx_missed_errors += inl (ioaddr + CSR8) & 0xffff; spin_unlock_irqrestore (&tp->lock, flags); init_timer(&tp->timer); tp->timer.data = (unsigned long)dev; tp->timer.function = tulip_tbl[tp->chip_id].media_timer; dev->if_port = tp->saved_if_port; /* Leave the driver in snooze, not sleep, mode. */ tulip_set_power_state (tp, 0, 1); } static int tulip_close (struct net_device *dev) { long ioaddr = dev->base_addr; struct tulip_private *tp = (struct tulip_private *) dev->priv; int i; netif_stop_queue (dev); #ifdef CONFIG_NET_HW_FLOWCONTROL if (tp->fc_bit) { int bit = tp->fc_bit; tp->fc_bit = 0; netdev_unregister_fc(bit); } #endif tulip_down (dev); if (tulip_debug > 1) printk (KERN_DEBUG "%s: Shutting down ethercard, status was %2.2x.\n", dev->name, inl (ioaddr + CSR5)); free_irq (dev->irq, dev); /* Free all the skbuffs in the Rx queue. */ for (i = 0; i < RX_RING_SIZE; i++) { struct sk_buff *skb = tp->rx_buffers[i].skb; dma_addr_t mapping = tp->rx_buffers[i].mapping; tp->rx_buffers[i].skb = NULL; tp->rx_buffers[i].mapping = 0; tp->rx_ring[i].status = 0; /* Not owned by Tulip chip. */ tp->rx_ring[i].length = 0; tp->rx_ring[i].buffer1 = 0xBADF00D0; /* An invalid address. */ if (skb) { pci_unmap_single(tp->pdev, mapping, PKT_BUF_SZ, PCI_DMA_FROMDEVICE); dev_kfree_skb (skb); } } for (i = 0; i < TX_RING_SIZE; i++) { struct sk_buff *skb = tp->tx_buffers[i].skb; if (skb != NULL) { pci_unmap_single(tp->pdev, tp->tx_buffers[i].mapping, skb->len, PCI_DMA_TODEVICE); dev_kfree_skb (skb); } tp->tx_buffers[i].skb = NULL; tp->tx_buffers[i].mapping = 0; } MOD_DEC_USE_COUNT; return 0; } static struct net_device_stats *tulip_get_stats(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; long ioaddr = dev->base_addr; if (netif_running(dev)) { unsigned long flags; spin_lock_irqsave (&tp->lock, flags); tp->stats.rx_missed_errors += inl(ioaddr + CSR8) & 0xffff; spin_unlock_irqrestore(&tp->lock, flags); } return &tp->stats; } static int netdev_ethtool_ioctl(struct net_device *dev, void *useraddr) { struct tulip_private *np = dev->priv; u32 ethcmd; if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd))) return -EFAULT; switch (ethcmd) { case ETHTOOL_GDRVINFO: { struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO}; strcpy(info.driver, DRV_NAME); strcpy(info.version, DRV_VERSION); strcpy(info.bus_info, np->pdev->slot_name); if (copy_to_user(useraddr, &info, sizeof(info))) return -EFAULT; return 0; } } return -EOPNOTSUPP; } /* Provide ioctl() calls to examine the MII xcvr state. */ static int private_ioctl (struct net_device *dev, struct ifreq *rq, int cmd) { struct tulip_private *tp = dev->priv; long ioaddr = dev->base_addr; struct mii_ioctl_data *data = (struct mii_ioctl_data *) & rq->ifr_data; const unsigned int phy_idx = 0; int phy = tp->phys[phy_idx] & 0x1f; unsigned int regnum = data->reg_num; switch (cmd) { case SIOCETHTOOL: return netdev_ethtool_ioctl(dev, (void *) rq->ifr_data); case SIOCGMIIPHY: /* Get address of MII PHY in use. */ case SIOCDEVPRIVATE: /* for binary compat, remove in 2.5 */ if (tp->mii_cnt) data->phy_id = phy; else if (tp->flags & HAS_NWAY) data->phy_id = 32; else if (tp->chip_id == COMET) data->phy_id = 1; else return -ENODEV; case SIOCGMIIREG: /* Read MII PHY register. */ case SIOCDEVPRIVATE+1: /* for binary compat, remove in 2.5 */ if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) { int csr12 = inl (ioaddr + CSR12); int csr14 = inl (ioaddr + CSR14); switch (regnum) { case 0: if (((csr14<<5) & 0x1000) || (dev->if_port == 5 && tp->nwayset)) data->val_out = 0x1000; else data->val_out = (tulip_media_cap[dev->if_port]&MediaIs100 ? 0x2000 : 0) | (tulip_media_cap[dev->if_port]&MediaIsFD ? 0x0100 : 0); break; case 1: data->val_out = 0x1848 + ((csr12&0x7000) == 0x5000 ? 0x20 : 0) + ((csr12&0x06) == 6 ? 0 : 4); if (tp->chip_id != DC21041) data->val_out |= 0x6048; break; case 4: /* Advertised value, bogus 10baseTx-FD value from CSR6. */ data->val_out = ((inl(ioaddr + CSR6) >> 3) & 0x0040) + ((csr14 >> 1) & 0x20) + 1; if (tp->chip_id != DC21041) data->val_out |= ((csr14 >> 9) & 0x03C0); break; case 5: data->val_out = tp->lpar; break; default: data->val_out = 0; break; } } else { data->val_out = tulip_mdio_read (dev, data->phy_id & 0x1f, regnum); } return 0; case SIOCSMIIREG: /* Write MII PHY register. */ case SIOCDEVPRIVATE+2: /* for binary compat, remove in 2.5 */ if (!capable (CAP_NET_ADMIN)) return -EPERM; if (regnum & ~0x1f) return -EINVAL; if (data->phy_id == phy) { u16 value = data->val_in; switch (regnum) { case 0: /* Check for autonegotiation on or reset. */ tp->full_duplex_lock = (value & 0x9000) ? 0 : 1; if (tp->full_duplex_lock) tp->full_duplex = (value & 0x0100) ? 1 : 0; break; case 4: tp->advertising[phy_idx] = tp->mii_advertise = data->val_in; break; } } if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) { u16 value = data->val_in; if (regnum == 0) { if ((value & 0x1200) == 0x1200) { if (tp->chip_id == PNIC2) { pnic2_start_nway (dev); } else { t21142_start_nway (dev); } } } else if (regnum == 4) tp->sym_advertise = value; } else { tulip_mdio_write (dev, data->phy_id & 0x1f, regnum, data->val_in); } return 0; default: return -EOPNOTSUPP; } return -EOPNOTSUPP; } /* Set or clear the multicast filter for this adaptor. Note that we only use exclusion around actually queueing the new frame, not around filling tp->setup_frame. This is non-deterministic when re-entered but still correct. */ #undef set_bit_le #define set_bit_le(i,p) do { ((char *)(p))[(i)/8] |= (1<<((i)%8)); } while(0) static void build_setup_frame_hash(u16 *setup_frm, struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; u16 hash_table[32]; struct dev_mc_list *mclist; int i; u16 *eaddrs; memset(hash_table, 0, sizeof(hash_table)); set_bit_le(255, hash_table); /* Broadcast entry */ /* This should work on big-endian machines as well. */ for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count; i++, mclist = mclist->next) { int index = ether_crc_le(ETH_ALEN, mclist->dmi_addr) & 0x1ff; set_bit_le(index, hash_table); for (i = 0; i < 32; i++) { *setup_frm++ = hash_table[i]; *setup_frm++ = hash_table[i]; } setup_frm = &tp->setup_frame[13*6]; } /* Fill the final entry with our physical address. */ eaddrs = (u16 *)dev->dev_addr; *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2]; } static void build_setup_frame_perfect(u16 *setup_frm, struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; struct dev_mc_list *mclist; int i; u16 *eaddrs; /* We have <= 14 addresses so we can use the wonderful 16 address perfect filtering of the Tulip. */ for (i = 0, mclist = dev->mc_list; i < dev->mc_count; i++, mclist = mclist->next) { eaddrs = (u16 *)mclist->dmi_addr; *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++; *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++; *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++; } /* Fill the unused entries with the broadcast address. */ memset(setup_frm, 0xff, (15-i)*12); setup_frm = &tp->setup_frame[15*6]; /* Fill the final entry with our physical address. */ eaddrs = (u16 *)dev->dev_addr; *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2]; } static void set_rx_mode(struct net_device *dev) { struct tulip_private *tp = (struct tulip_private *)dev->priv; long ioaddr = dev->base_addr; int csr6; csr6 = inl(ioaddr + CSR6) & ~0x00D5; tp->csr6 &= ~0x00D5; if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */ tp->csr6 |= AcceptAllMulticast | AcceptAllPhys; csr6 |= AcceptAllMulticast | AcceptAllPhys; /* Unconditionally log net taps. */ printk(KERN_INFO "%s: Promiscuous mode enabled.\n", dev->name); } else if ((dev->mc_count > 1000) || (dev->flags & IFF_ALLMULTI)) { /* Too many to filter well -- accept all multicasts. */ tp->csr6 |= AcceptAllMulticast; csr6 |= AcceptAllMulticast; } else if (tp->flags & MC_HASH_ONLY) { /* Some work-alikes have only a 64-entry hash filter table. */ /* Should verify correctness on big-endian/__powerpc__ */ struct dev_mc_list *mclist; int i; if (dev->mc_count > 64) { /* Arbitrary non-effective limit. */ tp->csr6 |= AcceptAllMulticast; csr6 |= AcceptAllMulticast; } else { u32 mc_filter[2] = {0, 0}; /* Multicast hash filter */ int filterbit; for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count; i++, mclist = mclist->next) { if (tp->flags & COMET_MAC_ADDR) filterbit = ether_crc_le(ETH_ALEN, mclist->dmi_addr); else filterbit = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26; filterbit &= 0x3f; mc_filter[filterbit >> 5] |= cpu_to_le32(1 << (filterbit & 31)); if (tulip_debug > 2) { printk(KERN_INFO "%s: Added filter for %2.2x:%2.2x:%2.2x:" "%2.2x:%2.2x:%2.2x %8.8x bit %d.\n", dev->name, mclist->dmi_addr[0], mclist->dmi_addr[1], mclist->dmi_addr[2], mclist->dmi_addr[3], mclist->dmi_addr[4], mclist->dmi_addr[5], ether_crc(ETH_ALEN, mclist->dmi_addr), filterbit); } } if (mc_filter[0] == tp->mc_filter[0] && mc_filter[1] == tp->mc_filter[1]) ; /* No change. */ else if (tp->flags & IS_ASIX) { outl(2, ioaddr + CSR13); outl(mc_filter[0], ioaddr + CSR14); outl(3, ioaddr + CSR13); outl(mc_filter[1], ioaddr + CSR14); } else if (tp->flags & COMET_MAC_ADDR) { outl(mc_filter[0], ioaddr + 0xAC); outl(mc_filter[1], ioaddr + 0xB0); } tp->mc_filter[0] = mc_filter[0]; tp->mc_filter[1] = mc_filter[1]; } } else { unsigned long flags; /* Note that only the low-address shortword of setup_frame is valid! The values are doubled for big-endian architectures. */ if (dev->mc_count > 14) { /* Must use a multicast hash table. */ build_setup_frame_hash(tp->setup_frame, dev); } else { build_setup_frame_perfect(tp->setup_frame, dev); } spin_lock_irqsave(&tp->lock, flags); if (tp->cur_tx - tp->dirty_tx > TX_RING_SIZE - 2) { /* Same setup recently queued, we need not add it. */ } else { u32 tx_flags = 0x08000000 | 192; unsigned int entry; int dummy = -1; /* Now add this frame to the Tx list. */ entry = tp->cur_tx++ % TX_RING_SIZE; if (entry != 0) { /* Avoid a chip errata by prefixing a dummy entry. */ tp->tx_buffers[entry].skb = NULL; tp->tx_buffers[entry].mapping = 0; tp->tx_ring[entry].length = (entry == TX_RING_SIZE-1) ? cpu_to_le32(DESC_RING_WRAP) : 0; tp->tx_ring[entry].buffer1 = 0; /* Must set DescOwned later to avoid race with chip */ dummy = entry; entry = tp->cur_tx++ % TX_RING_SIZE; } tp->tx_buffers[entry].skb = NULL; tp->tx_buffers[entry].mapping = pci_map_single(tp->pdev, tp->setup_frame, sizeof(tp->setup_frame), PCI_DMA_TODEVICE); /* Put the setup frame on the Tx list. */ if (entry == TX_RING_SIZE-1) tx_flags |= DESC_RING_WRAP; /* Wrap ring. */ tp->tx_ring[entry].length = cpu_to_le32(tx_flags); tp->tx_ring[entry].buffer1 = cpu_to_le32(tp->tx_buffers[entry].mapping); tp->tx_ring[entry].status = cpu_to_le32(DescOwned); if (dummy >= 0) tp->tx_ring[dummy].status = cpu_to_le32(DescOwned); if (tp->cur_tx - tp->dirty_tx >= TX_RING_SIZE - 2) netif_stop_queue(dev); /* Trigger an immediate transmit demand. */ outl(0, ioaddr + CSR1); } spin_unlock_irqrestore(&tp->lock, flags); } outl(csr6, ioaddr + CSR6); } #ifdef CONFIG_TULIP_MWI static void __devinit tulip_mwi_config (struct pci_dev *pdev, struct net_device *dev) { struct tulip_private *tp = dev->priv; u8 cache; u16 pci_command; u32 csr0; if (tulip_debug > 3) printk(KERN_DEBUG "%s: tulip_mwi_config()\n", pdev->slot_name); tp->csr0 = csr0 = 0; /* if we have any cache line size at all, we can do MRM */ csr0 |= MRM; /* ...and barring hardware bugs, MWI */ if (!(tp->chip_id == DC21143 && tp->revision == 65)) csr0 |= MWI; /* set or disable MWI in the standard PCI command bit. * Check for the case where mwi is desired but not available */ if (csr0 & MWI) pci_set_mwi(pdev); else pci_clear_mwi(pdev); /* read result from hardware (in case bit refused to enable) */ pci_read_config_word(pdev, PCI_COMMAND, &pci_command); if ((csr0 & MWI) && (!(pci_command & PCI_COMMAND_INVALIDATE))) csr0 &= ~MWI; /* if cache line size hardwired to zero, no MWI */ pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cache); if ((csr0 & MWI) && (cache == 0)) { csr0 &= ~MWI; pci_clear_mwi(pdev); } /* assign per-cacheline-size cache alignment and * burst length values */ switch (cache) { case 8: csr0 |= MRL | (1 << CALShift) | (16 << BurstLenShift); break; case 16: csr0 |= MRL | (2 << CALShift) | (16 << BurstLenShift); break; case 32: csr0 |= MRL | (3 << CALShift) | (32 << BurstLenShift); break; default: cache = 0; break; } /* if we have a good cache line size, we by now have a good * csr0, so save it and exit */ if (cache) goto out; /* we don't have a good csr0 or cache line size, disable MWI */ if (csr0 & MWI) { pci_clear_mwi(pdev); csr0 &= ~MWI; } /* sane defaults for burst length and cache alignment * originally from de4x5 driver */ csr0 |= (8 << BurstLenShift) | (1 << CALShift); out: tp->csr0 = csr0; if (tulip_debug > 2) printk(KERN_DEBUG "%s: MWI config cacheline=%d, csr0=%08x\n", pdev->slot_name, cache, csr0); } #endif static int __devinit tulip_init_one (struct pci_dev *pdev, const struct pci_device_id *ent) { struct tulip_private *tp; /* See note below on the multiport cards. */ static unsigned char last_phys_addr[6] = {0x00, 'L', 'i', 'n', 'u', 'x'}; static int last_irq; static int multiport_cnt; /* For four-port boards w/one EEPROM */ u8 chip_rev; int i, irq; unsigned short sum; u8 ee_data[EEPROM_SIZE]; struct net_device *dev; long ioaddr; static int board_idx = -1; int chip_idx = ent->driver_data; unsigned int t2104x_mode = 0; unsigned int eeprom_missing = 0; unsigned int force_csr0 = 0; #ifndef MODULE static int did_version; /* Already printed version info. */ if (tulip_debug > 0 && did_version++ == 0) printk (KERN_INFO "%s", version); #endif board_idx++; /* * Lan media wire a tulip chip to a wan interface. Needs a very * different driver (lmc driver) */ if (pdev->subsystem_vendor == PCI_VENDOR_ID_LMC) { printk (KERN_ERR PFX "skipping LMC card.\n"); return -ENODEV; } /* * Early DM9100's need software CRC and the DMFE driver */ if (pdev->vendor == 0x1282 && pdev->device == 0x9100) { u32 dev_rev; /* Read Chip revision */ pci_read_config_dword(pdev, PCI_REVISION_ID, &dev_rev); if(dev_rev < 0x02000030) { printk(KERN_ERR PFX "skipping early DM9100 with Crc bug (use dmfe)\n"); return -ENODEV; } } /* * Looks for early PCI chipsets where people report hangs * without the workarounds being on. */ /* Intel Saturn. Switch to 8 long words burst, 8 long word cache aligned Aries might need this too. The Saturn errata are not pretty reading but thankfully its an old 486 chipset. */ if (pci_find_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82424, NULL)) { csr0 = MRL | MRM | (8 << BurstLenShift) | (1 << CALShift); force_csr0 = 1; } if (pci_find_device(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_496, NULL)) { csr0 = MRL | MRM | (8 << BurstLenShift) | (1 << CALShift); force_csr0 = 1; } /* bugfix: the ASIX must have a burst limit or horrible things happen. */ if (chip_idx == AX88140) { if ((csr0 & 0x3f00) == 0) csr0 |= 0x2000; } /* PNIC doesn't have MWI/MRL/MRM... */ if (chip_idx == LC82C168) csr0 &= ~0xfff10000; /* zero reserved bits 31:20, 16 */ /* DM9102A has troubles with MRM & clear reserved bits 24:22, 20, 16, 7:1 */ if (pdev->vendor == 0x1282 && pdev->device == 0x9102) csr0 &= ~0x01f100ff; #if defined(__sparc__) /* DM9102A needs 32-dword alignment/burst length on sparc - chip bug? */ if (pdev->vendor == 0x1282 && pdev->device == 0x9102) csr0 = (csr0 & ~0xff00) | 0xe000; #endif /* * And back to business */ i = pci_enable_device(pdev); if (i) { printk (KERN_ERR PFX "Cannot enable tulip board #%d, aborting\n", board_idx); return i; } ioaddr = pci_resource_start (pdev, 0); irq = pdev->irq; /* alloc_etherdev ensures aligned and zeroed private structures */ dev = alloc_etherdev (sizeof (*tp)); if (!dev) { printk (KERN_ERR PFX "ether device alloc failed, aborting\n"); return -ENOMEM; } if (pci_resource_len (pdev, 0) < tulip_tbl[chip_idx].io_size) { printk (KERN_ERR PFX "%s: I/O region (0x%lx@0x%lx) too small, " "aborting\n", pdev->slot_name, pci_resource_len (pdev, 0), pci_resource_start (pdev, 0)); goto err_out_free_netdev; } /* grab all resources from both PIO and MMIO regions, as we * don't want anyone else messing around with our hardware */ if (pci_request_regions (pdev, "tulip")) goto err_out_free_netdev; #ifndef USE_IO_OPS ioaddr = (unsigned long) ioremap (pci_resource_start (pdev, 1), tulip_tbl[chip_idx].io_size); if (!ioaddr) goto err_out_free_res; #endif pci_read_config_byte (pdev, PCI_REVISION_ID, &chip_rev); /* * initialize private data structure 'tp' * it is zeroed and aligned in alloc_etherdev */ tp = dev->priv; tp->rx_ring = pci_alloc_consistent(pdev, sizeof(struct tulip_rx_desc) * RX_RING_SIZE + sizeof(struct tulip_tx_desc) * TX_RING_SIZE, &tp->rx_ring_dma); if (!tp->rx_ring) goto err_out_mtable; tp->tx_ring = (struct tulip_tx_desc *)(tp->rx_ring + RX_RING_SIZE); tp->tx_ring_dma = tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * RX_RING_SIZE; tp->chip_id = chip_idx; tp->flags = tulip_tbl[chip_idx].flags; tp->pdev = pdev; tp->base_addr = ioaddr; tp->revision = chip_rev; tp->csr0 = csr0; spin_lock_init(&tp->lock); spin_lock_init(&tp->mii_lock); init_timer(&tp->timer); tp->timer.data = (unsigned long)dev; tp->timer.function = tulip_tbl[tp->chip_id].media_timer; dev->base_addr = ioaddr; #ifdef CONFIG_TULIP_MWI if (!force_csr0 && (tp->flags & HAS_PCI_MWI)) tulip_mwi_config (pdev, dev); #else /* MWI is broken for DC21143 rev 65... */ if (chip_idx == DC21143 && chip_rev == 65) tp->csr0 &= ~MWI; #endif /* Stop the chip's Tx and Rx processes. */ tulip_stop_rxtx(tp); pci_set_master(pdev); /* Clear the missed-packet counter. */ inl(ioaddr + CSR8); if (chip_idx == DC21041) { if (inl(ioaddr + CSR9) & 0x8000) { chip_idx = DC21040; t2104x_mode = 1; } else { t2104x_mode = 2; } } /* The station address ROM is read byte serially. The register must be polled, waiting for the value to be read bit serially from the EEPROM. */ sum = 0; if (chip_idx == DC21040) { outl(0, ioaddr + CSR9); /* Reset the pointer with a dummy write. */ for (i = 0; i < 6; i++) { int value, boguscnt = 100000; do value = inl(ioaddr + CSR9); while (value < 0 && --boguscnt > 0); dev->dev_addr[i] = value; sum += value & 0xff; } } else if (chip_idx == LC82C168) { for (i = 0; i < 3; i++) { int value, boguscnt = 100000; outl(0x600 | i, ioaddr + 0x98); do value = inl(ioaddr + CSR9); while (value < 0 && --boguscnt > 0); put_unaligned(le16_to_cpu(value), ((u16*)dev->dev_addr) + i); sum += value & 0xffff; } } else if (chip_idx == COMET) { /* No need to read the EEPROM. */ put_unaligned(inl(ioaddr + 0xA4), (u32 *)dev->dev_addr); put_unaligned(inl(ioaddr + 0xA8), (u16 *)(dev->dev_addr + 4)); for (i = 0; i < 6; i ++) sum += dev->dev_addr[i]; } else { /* A serial EEPROM interface, we read now and sort it out later. */ int sa_offset = 0; int ee_addr_size = tulip_read_eeprom(ioaddr, 0xff, 8) & 0x40000 ? 8 : 6; for (i = 0; i < sizeof(ee_data)/2; i++) ((u16 *)ee_data)[i] = le16_to_cpu(tulip_read_eeprom(ioaddr, i, ee_addr_size)); /* DEC now has a specification (see Notes) but early board makers just put the address in the first EEPROM locations. */ /* This does memcmp(eedata, eedata+16, 8) */ for (i = 0; i < 8; i ++) if (ee_data[i] != ee_data[16+i]) sa_offset = 20; if (chip_idx == CONEXANT) { /* Check that the tuple type and length is correct. */ if (ee_data[0x198] == 0x04 && ee_data[0x199] == 6) sa_offset = 0x19A; } if (ee_data[0] == 0xff && ee_data[1] == 0xff && ee_data[2] == 0) { sa_offset = 2; /* Grrr, damn Matrox boards. */ multiport_cnt = 4; } #ifdef CONFIG_DDB5476 if ((pdev->bus->number == 0) && (PCI_SLOT(pdev->devfn) == 6)) { /* DDB5476 MAC address in first EEPROM locations. */ sa_offset = 0; /* No media table either */ tp->flags &= ~HAS_MEDIA_TABLE; } #endif #ifdef CONFIG_DDB5477 if ((pdev->bus->number == 0) && (PCI_SLOT(pdev->devfn) == 4)) { /* DDB5477 MAC address in first EEPROM locations. */ sa_offset = 0; /* No media table either */ tp->flags &= ~HAS_MEDIA_TABLE; } #endif #ifdef CONFIG_MIPS_COBALT if ((pdev->bus->number == 0) && ((PCI_SLOT(pdev->devfn) == 7) || (PCI_SLOT(pdev->devfn) == 12))) { /* Cobalt MAC address in first EEPROM locations. */ sa_offset = 0; /* No media table either */ tp->flags &= ~HAS_MEDIA_TABLE; } #endif #ifdef __hppa__ /* 3x5 HSC (J3514A) has a broken srom */ if(ee_data[0] == 0x61 && ee_data[1] == 0x10) { /* pci_vendor_id and subsystem_id are swapped */ ee_data[0] = ee_data[2]; ee_data[1] = ee_data[3]; ee_data[2] = 0x61; ee_data[3] = 0x10; /* srom need to be byte-swaped and shifted up 1 word. * This shift needs to happen at the end of the MAC * first because of the 2 byte overlap. */ for(i = 4; i >= 0; i -= 2) { ee_data[17 + i + 3] = ee_data[17 + i]; ee_data[16 + i + 5] = ee_data[16 + i]; } } #endif for (i = 0; i < 6; i ++) { dev->dev_addr[i] = ee_data[i + sa_offset]; sum += ee_data[i + sa_offset]; } } /* Lite-On boards have the address byte-swapped. */ if ((dev->dev_addr[0] == 0xA0 || dev->dev_addr[0] == 0xC0) && dev->dev_addr[1] == 0x00) for (i = 0; i < 6; i+=2) { char tmp = dev->dev_addr[i]; dev->dev_addr[i] = dev->dev_addr[i+1]; dev->dev_addr[i+1] = tmp; } /* On the Zynx 315 Etherarray and other multiport boards only the first Tulip has an EEPROM. On Sparc systems the mac address is held in the OBP property "local-mac-address". The addresses of the subsequent ports are derived from the first. Many PCI BIOSes also incorrectly report the IRQ line, so we correct that here as well. */ if (sum == 0 || sum == 6*0xff) { #if defined(__sparc__) struct pcidev_cookie *pcp = pdev->sysdata; #endif eeprom_missing = 1; for (i = 0; i < 5; i++) dev->dev_addr[i] = last_phys_addr[i]; dev->dev_addr[i] = last_phys_addr[i] + 1; #if defined(__sparc__) if ((pcp != NULL) && prom_getproplen(pcp->prom_node, "local-mac-address") == 6) { prom_getproperty(pcp->prom_node, "local-mac-address", dev->dev_addr, 6); } #endif #if defined(__i386__) /* Patch up x86 BIOS bug. */ if (last_irq) irq = last_irq; #endif } for (i = 0; i < 6; i++) last_phys_addr[i] = dev->dev_addr[i]; last_irq = irq; dev->irq = irq; /* The lower four bits are the media type. */ if (board_idx >= 0 && board_idx < MAX_UNITS) { if (options[board_idx] & MEDIA_MASK) tp->default_port = options[board_idx] & MEDIA_MASK; if ((options[board_idx] & FullDuplex) || full_duplex[board_idx] > 0) tp->full_duplex = 1; if (mtu[board_idx] > 0) dev->mtu = mtu[board_idx]; } if (dev->mem_start & MEDIA_MASK) tp->default_port = dev->mem_start & MEDIA_MASK; if (tp->default_port) { printk(KERN_INFO "tulip%d: Transceiver selection forced to %s.\n", board_idx, medianame[tp->default_port & MEDIA_MASK]); tp->medialock = 1; if (tulip_media_cap[tp->default_port] & MediaAlwaysFD) tp->full_duplex = 1; } if (tp->full_duplex) tp->full_duplex_lock = 1; if (tulip_media_cap[tp->default_port] & MediaIsMII) { u16 media2advert[] = { 0x20, 0x40, 0x03e0, 0x60, 0x80, 0x100, 0x200 }; tp->mii_advertise = media2advert[tp->default_port - 9]; tp->mii_advertise |= (tp->flags & HAS_8023X); /* Matching bits! */ } if (tp->flags & HAS_MEDIA_TABLE) { memcpy(tp->eeprom, ee_data, sizeof(tp->eeprom)); sprintf(dev->name, "tulip%d", board_idx); /* hack */ tulip_parse_eeprom(dev); strcpy(dev->name, "eth%d"); /* un-hack */ } if ((tp->flags & ALWAYS_CHECK_MII) || (tp->mtable && tp->mtable->has_mii) || ( ! tp->mtable && (tp->flags & HAS_MII))) { if (tp->mtable && tp->mtable->has_mii) { for (i = 0; i < tp->mtable->leafcount; i++) if (tp->mtable->mleaf[i].media == 11) { tp->cur_index = i; tp->saved_if_port = dev->if_port; tulip_select_media(dev, 2); dev->if_port = tp->saved_if_port; break; } } /* Find the connected MII xcvrs. Doing this in open() would allow detecting external xcvrs later, but takes much time. */ tulip_find_mii (dev, board_idx); } /* The Tulip-specific entries in the device structure. */ dev->open = tulip_open; dev->hard_start_xmit = tulip_start_xmit; dev->tx_timeout = tulip_tx_timeout; dev->watchdog_timeo = TX_TIMEOUT; dev->stop = tulip_close; dev->get_stats = tulip_get_stats; dev->do_ioctl = private_ioctl; dev->set_multicast_list = set_rx_mode; if (register_netdev(dev)) goto err_out_free_ring; printk(KERN_INFO "%s: %s rev %d at %#3lx,", dev->name, tulip_tbl[chip_idx].chip_name, chip_rev, ioaddr); pci_set_drvdata(pdev, dev); if (t2104x_mode == 1) printk(" 21040 compatible mode,"); else if (t2104x_mode == 2) printk(" 21041 mode,"); if (eeprom_missing) printk(" EEPROM not present,"); for (i = 0; i < 6; i++) printk("%c%2.2X", i ? ':' : ' ', dev->dev_addr[i]); printk(", IRQ %d.\n", irq); if (tp->chip_id == PNIC2) tp->link_change = pnic2_lnk_change; else if ((tp->flags & HAS_NWAY) || tp->chip_id == DC21041) tp->link_change = t21142_lnk_change; else if (tp->flags & HAS_PNICNWAY) tp->link_change = pnic_lnk_change; /* Reset the xcvr interface and turn on heartbeat. */ switch (chip_idx) { case DC21041: if (tp->sym_advertise == 0) tp->sym_advertise = 0x0061; outl(0x00000000, ioaddr + CSR13); outl(0xFFFFFFFF, ioaddr + CSR14); outl(0x00000008, ioaddr + CSR15); /* Listen on AUI also. */ outl(inl(ioaddr + CSR6) | csr6_fd, ioaddr + CSR6); outl(0x0000EF01, ioaddr + CSR13); break; case DC21040: outl(0x00000000, ioaddr + CSR13); outl(0x00000004, ioaddr + CSR13); break; case DC21140: case DM910X: default: if (tp->mtable) outl(tp->mtable->csr12dir | 0x100, ioaddr + CSR12); break; case DC21142: if (tp->mii_cnt || tulip_media_cap[dev->if_port] & MediaIsMII) { outl(csr6_mask_defstate, ioaddr + CSR6); outl(0x0000, ioaddr + CSR13); outl(0x0000, ioaddr + CSR14); outl(csr6_mask_hdcap, ioaddr + CSR6); } else t21142_start_nway(dev); break; case PNIC2: /* just do a reset for sanity sake */ outl(0x0000, ioaddr + CSR13); outl(0x0000, ioaddr + CSR14); break; case LC82C168: if ( ! tp->mii_cnt) { tp->nway = 1; tp->nwayset = 0; outl(csr6_ttm | csr6_ca, ioaddr + CSR6); outl(0x30, ioaddr + CSR12); outl(0x0001F078, ioaddr + CSR6); outl(0x0201F078, ioaddr + CSR6); /* Turn on autonegotiation. */ } break; case MX98713: case COMPEX9881: outl(0x00000000, ioaddr + CSR6); outl(0x000711C0, ioaddr + CSR14); /* Turn on NWay. */ outl(0x00000001, ioaddr + CSR13); break; case MX98715: case MX98725: outl(0x01a80000, ioaddr + CSR6); outl(0xFFFFFFFF, ioaddr + CSR14); outl(0x00001000, ioaddr + CSR12); break; case COMET: /* No initialization necessary. */ break; } /* put the chip in snooze mode until opened */ tulip_set_power_state (tp, 0, 1); return 0; err_out_free_ring: pci_free_consistent (pdev, sizeof (struct tulip_rx_desc) * RX_RING_SIZE + sizeof (struct tulip_tx_desc) * TX_RING_SIZE, tp->rx_ring, tp->rx_ring_dma); err_out_mtable: if (tp->mtable) kfree (tp->mtable); #ifndef USE_IO_OPS iounmap((void *)ioaddr); err_out_free_res: #endif pci_release_regions (pdev); err_out_free_netdev: kfree (dev); return -ENODEV; } #ifdef CONFIG_PM static int tulip_suspend (struct pci_dev *pdev, u32 state) { struct net_device *dev = pci_get_drvdata(pdev); if (dev && netif_running (dev) && netif_device_present (dev)) { netif_device_detach (dev); tulip_down (dev); /* pci_power_off(pdev, -1); */ } return 0; } static int tulip_resume(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); if (dev && netif_running (dev) && !netif_device_present (dev)) { pci_enable_device (pdev); /* pci_power_on(pdev); */ tulip_up (dev); netif_device_attach (dev); } return 0; } #endif /* CONFIG_PM */ static void __devexit tulip_remove_one (struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata (pdev); struct tulip_private *tp; if (!dev) return; tp = dev->priv; pci_free_consistent (pdev, sizeof (struct tulip_rx_desc) * RX_RING_SIZE + sizeof (struct tulip_tx_desc) * TX_RING_SIZE, tp->rx_ring, tp->rx_ring_dma); unregister_netdev (dev); if (tp->mtable) kfree (tp->mtable); #ifndef USE_IO_OPS iounmap((void *)dev->base_addr); #endif kfree (dev); pci_release_regions (pdev); pci_set_drvdata (pdev, NULL); /* pci_power_off (pdev, -1); */ } static struct pci_driver tulip_driver = { name: DRV_NAME, id_table: tulip_pci_tbl, probe: tulip_init_one, remove: __devexit_p(tulip_remove_one), #ifdef CONFIG_PM suspend: tulip_suspend, resume: tulip_resume, #endif /* CONFIG_PM */ }; static int __init tulip_init (void) { #ifdef MODULE printk (KERN_INFO "%s", version); #endif /* copy module parms into globals */ tulip_rx_copybreak = rx_copybreak; tulip_max_interrupt_work = max_interrupt_work; /* probe for and init boards */ return pci_module_init (&tulip_driver); } static void __exit tulip_cleanup (void) { pci_unregister_driver (&tulip_driver); } module_init(tulip_init); module_exit(tulip_cleanup);
30.190155
111
0.644499
b10785b52eedf9da801d93dde80b2807d2b23124
13,944
h
C
compiler/floyd_ast/statement.h
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
null
null
null
compiler/floyd_ast/statement.h
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
null
null
null
compiler/floyd_ast/statement.h
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
null
null
null
// // parser_statement.h // Floyd // // Created by Marcus Zetterquist on 26/07/16. // Copyright © 2016 Marcus Zetterquist. All rights reserved. // #ifndef parser_statement_hpp #define parser_statement_hpp #include "expression.h" #include "quark.h" #include <vector> #include <string> //#include "../parts/xcode-libcxx-xcode9/variant" // https://github.com/youknowone/xcode-libcxx #include <variant> namespace floyd { struct statement_t; struct expression_t; json_t statement_to_json(const statement_t& e); //////////////////////////////////////// statement_opcode_t // String keys used to specify statement type inside the AST JSON. namespace statement_opcode_t { const std::string k_return = "return"; const std::string k_init_local = "init-local"; const std::string k_init_local2 = "init-local2"; const std::string k_assign = "assign"; const std::string k_assign2 = "assign2"; const std::string k_block = "block"; const std::string k_if = "if"; const std::string k_for = "for"; const std::string k_while = "while"; const std::string k_expression_statement = "expression-statement"; const std::string k_software_system_def = "software-system-def"; const std::string k_container_def = "container-def"; const std::string k_benchmark_def = "benchmark-def"; }; ////////////////////////////////////// symbol_t /* This is an entry in the symbol table, kept for each environment/stack frame. When you make a local variable it gets an entry in symbol table, with a type and name but no value. Like a reservered slot. You can also add precalculated constants directly to the symbol table. # Function values These are stored as local variable reservations of correct function-signature-type. They are inited during execution, not const-values in symbol table. Function calls needs to evaluate callee expression. ??? TODO: make functions const-values when possible. # Structs Struct-types are stored in symbol table as precalculated values. Struct instances are not. struct pixel_t { int red; int green; int blue; } - needs to become a precalculated symbol called "pixel_t" so print(pixel_t) etc works. - pixel_t variable = type: typeid_t = struct{ int red; int green; int blue; } const: value_t::typeid_value = */ struct symbol_t { enum class mutable_mode { immutable, mutable1 }; bool operator==(const symbol_t& other) const { return true && _mutable_mode == other._mutable_mode && _value_type == other._value_type && _init == other._init ; } public: bool check_invariant() const { QUARK_ASSERT(_init.is_undefined() || _init.get_type() == _value_type); return true; } public: symbol_t(mutable_mode mutable_mode, const floyd::typeid_t& value_type, const floyd::value_t& init_value) : _mutable_mode(mutable_mode), _value_type(value_type), _init(init_value) { QUARK_ASSERT(check_invariant()); } public: floyd::typeid_t get_type() const { QUARK_ASSERT(check_invariant()); return _value_type; } public: static symbol_t make_immutable_reserve(const floyd::typeid_t& value_type){ return symbol_t{ mutable_mode::immutable, value_type, {} }; } public: static symbol_t make_immutable_arg(const floyd::typeid_t& value_type){ return symbol_t{ mutable_mode::immutable, value_type, {} }; } //??? Mutable could support init-value too!? public: static symbol_t make_mutable(const floyd::typeid_t& value_type){ return symbol_t{ mutable_mode::mutable1, value_type, {} }; } public: static symbol_t make_immutable_precalc(const floyd::value_t& init_value){ QUARK_ASSERT(is_floyd_literal(init_value.get_type())); return symbol_t{ mutable_mode::immutable, init_value.get_type(), init_value }; } ////////////////////////////////////// STATE mutable_mode _mutable_mode; floyd::typeid_t _value_type; // If there is no initialization value, this member must be value_t::make_undefined(); floyd::value_t _init; }; symbol_t make_type_symbol(const floyd::typeid_t& t); std::string symbol_to_string(const symbol_t& symbol); ////////////////////////////////////// symbol_table_t struct symbol_table_t { bool check_invariant() const { return true; } bool operator==(const symbol_table_t& other) const { return _symbols == other._symbols; } public: std::vector<std::pair<std::string, symbol_t>> _symbols; }; const floyd::symbol_t* find_symbol(const symbol_table_t& symbol_table, const std::string& name); const floyd::symbol_t& find_symbol_required(const symbol_table_t& symbol_table, const std::string& name); std::vector<json_t> symbols_to_json(const symbol_table_t& symbols); symbol_table_t ast_json_to_symbols(const json_t& p); ////////////////////////////////////// body_t struct body_t { body_t(){ } body_t(const std::vector<statement_t>& s) : _statements(s), _symbol_table{} { } body_t(const std::vector<statement_t>& statements, const symbol_table_t& symbols) : _statements(statements), _symbol_table(symbols) { } bool check_invariant() const; //////////////////// STATE std::vector<statement_t> _statements; symbol_table_t _symbol_table; }; bool operator==(const body_t& lhs, const body_t& rhs); json_t body_to_json(const body_t& e); body_t json_to_body(const json_t& json); ////////////////////////////////////// statement_t /* Defines a statement, like "return" including any needed expression trees for the statement. Immutable */ struct statement_t { ////////////////////////////////////// return_statement_t struct return_statement_t { bool operator==(const return_statement_t& other) const { return _expression == other._expression; } expression_t _expression; }; public: static statement_t make__return_statement(const location_t& location, const expression_t& expression){ return statement_t(location, { return_statement_t{ expression } }); } ////////////////////////////////////// bind_local_t // Created a new name in current lexical scope and initialises it with an expression. struct bind_local_t { enum mutable_mode { k_mutable = 2, k_immutable }; bool operator==(const bind_local_t& other) const { return _new_local_name == other._new_local_name && _bindtype == other._bindtype && _expression == other._expression && _locals_mutable_mode == other._locals_mutable_mode; } std::string _new_local_name; typeid_t _bindtype; expression_t _expression; mutable_mode _locals_mutable_mode; }; public: static statement_t make__bind_local(const location_t& location, const std::string& new_local_name, const typeid_t& bindtype, const expression_t& expression, bind_local_t::mutable_mode locals_mutable_mode){ return statement_t(location, { bind_local_t{ new_local_name, bindtype, expression, locals_mutable_mode } }); } ////////////////////////////////////// assign_t // Mutate an existing variable, specified by name. struct assign_t { bool operator==(const assign_t& other) const { return _local_name == other._local_name && _expression == other._expression; } std::string _local_name; expression_t _expression; }; public: static statement_t make__assign(const location_t& location, const std::string& local_name, const expression_t& expression){ return statement_t(location, { assign_t{ local_name, expression} }); } ////////////////////////////////////// assign2_t // Mutate an existing variable, specified by resolved scope ID. struct assign2_t { bool operator==(const assign2_t& other) const { return _dest_variable == other._dest_variable && _expression == other._expression; } variable_address_t _dest_variable; expression_t _expression; }; public: static statement_t make__assign2(const location_t& location, const variable_address_t& dest_variable, const expression_t& expression){ return statement_t(location, { assign2_t{ dest_variable, expression} }); } ////////////////////////////////////// init2_t // Initialise an existing variable, specified by resolved scope ID. struct init2_t { bool operator==(const init2_t& other) const { return _dest_variable == other._dest_variable && _expression == other._expression; } variable_address_t _dest_variable; expression_t _expression; }; public: static statement_t make__init2(const location_t& location, const variable_address_t& dest_variable, const expression_t& expression){ return statement_t(location, { init2_t{ dest_variable, expression} }); } ////////////////////////////////////// block_statement_t struct block_statement_t { bool operator==(const block_statement_t& other) const { return _body == other._body; } body_t _body; }; public: static statement_t make__block_statement(const location_t& location, const body_t& body){ return statement_t(location, { block_statement_t{ body} }); } ////////////////////////////////////// ifelse_statement_t struct ifelse_statement_t { bool operator==(const ifelse_statement_t& other) const { return _condition == other._condition && _condition == other._condition && _then_body == other._then_body && _else_body == other._else_body ; } expression_t _condition; body_t _then_body; body_t _else_body; }; public: static statement_t make__ifelse_statement( const location_t& location, const expression_t& condition, const body_t& then_body, const body_t& else_body ){ return statement_t(location, { ifelse_statement_t{ condition, then_body, else_body} }); } ////////////////////////////////////// for_statement_t struct for_statement_t { enum range_type { k_open_range, // ..< k_closed_range // ... }; bool operator==(const for_statement_t& other) const { return _iterator_name == other._iterator_name && _start_expression == other._start_expression && _end_expression == other._end_expression && _body == other._body && _range_type == other._range_type ; } std::string _iterator_name; expression_t _start_expression; expression_t _end_expression; body_t _body; range_type _range_type; }; public: static statement_t make__for_statement( const location_t& location, const std::string iterator_name, const expression_t& start_expression, const expression_t& end_expression, const body_t& body, for_statement_t::range_type range_type ){ return statement_t(location, { for_statement_t{ iterator_name, start_expression, end_expression, body, range_type } }); } ////////////////////////////////////// software_system_statement_t struct software_system_statement_t { bool operator==(const software_system_statement_t& other) const { return _json_data == other._json_data; } json_t _json_data; }; public: static statement_t make__software_system_statement( const location_t& location, json_t json_data ){ return statement_t(location, { software_system_statement_t{ json_data } }); } ////////////////////////////////////// container_def_statement_t struct container_def_statement_t { bool operator==(const container_def_statement_t& other) const { return _json_data == other._json_data; } json_t _json_data; }; public: static statement_t make__container_def_statement( const location_t& location, json_t json_data ){ return statement_t(location, { container_def_statement_t{ json_data } }); } ////////////////////////////////////// benchmark_def_statement_t struct benchmark_def_statement_t { bool operator==(const benchmark_def_statement_t& other) const { return _body == other._body; } std::string name; body_t _body; }; public: static statement_t make__benchmark_def_statement( const location_t& location, const std::string& name, const body_t& body ){ return statement_t(location, { benchmark_def_statement_t{ name, body } }); } ////////////////////////////////////// while_statement_t struct while_statement_t { bool operator==(const while_statement_t& other) const { return _condition == other._condition && _body == other._body; } expression_t _condition; body_t _body; }; public: static statement_t make__while_statement( const location_t& location, const expression_t& condition, const body_t& body ){ return statement_t(location, { while_statement_t{ condition, body } }); } ////////////////////////////////////// expression_statement_t struct expression_statement_t { bool operator==(const expression_statement_t& other) const { return _expression == other._expression; } expression_t _expression; }; public: static statement_t make__expression_statement(const location_t& location, const expression_t& expression){ return statement_t(location, { expression_statement_t{ expression } }); } ////////////////////////////////////// statement_t typedef std::variant< return_statement_t, bind_local_t, assign_t, assign2_t, init2_t, block_statement_t, ifelse_statement_t, for_statement_t, while_statement_t, expression_statement_t, software_system_statement_t, container_def_statement_t, benchmark_def_statement_t > statement_variant_t; statement_t(const location_t& location, const statement_variant_t& contents) : #if DEBUG_DEEP debug_string(""), #endif location(location), _contents(contents) { const auto json = statement_to_json(*this); #if DEBUG_DEEP debug_string = json_to_compact_string(json); #endif } bool check_invariant() const { return true; } ////////////////////////////////////// STATE #if DEBUG_DEEP std::string debug_string; #endif location_t location; statement_variant_t _contents; }; static bool operator==(const statement_t& lhs, const statement_t& rhs){ return lhs.location == rhs.location && lhs._contents == rhs._contents; } const std::vector<statement_t> ast_json_to_statements(const json_t& p); json_t statement_to_json(const statement_t& e); } // floyd #endif /* parser_statement_hpp */
24.811388
214
0.70274
366433fd2e99076c11903de0320b7a5db594d074
67
h
C
ext/sam/SRC/TESTS/call_python/plugin.h
kbren/uwnet
aac01e243c19686b10c214b1c56b0bb7b7e06a07
[ "MIT" ]
1
2020-06-22T19:36:34.000Z
2020-06-22T19:36:34.000Z
ext/sam/SRC/TESTS/call_python/plugin.h
kbren/uwnet
aac01e243c19686b10c214b1c56b0bb7b7e06a07
[ "MIT" ]
null
null
null
ext/sam/SRC/TESTS/call_python/plugin.h
kbren/uwnet
aac01e243c19686b10c214b1c56b0bb7b7e06a07
[ "MIT" ]
2
2021-01-05T10:57:32.000Z
2022-02-07T19:01:53.000Z
extern void hello_world(void); extern void add_one(double *, int);
22.333333
35
0.761194
d2211e84b0a3ce4b8e5e1b9faa4c80f9064b311a
8,067
h
C
src/gromacs/topology/block.h
jlmaccal/gromacs
fbf723086ec6d21de5d1916397a326be8005541e
[ "BSD-2-Clause" ]
3
2020-11-09T14:24:00.000Z
2022-03-09T19:24:17.000Z
src/gromacs/topology/block.h
jlmaccal/gromacs
fbf723086ec6d21de5d1916397a326be8005541e
[ "BSD-2-Clause" ]
2
2020-11-09T14:16:24.000Z
2022-02-14T14:07:53.000Z
src/gromacs/topology/block.h
jlmaccal/gromacs
fbf723086ec6d21de5d1916397a326be8005541e
[ "BSD-2-Clause" ]
null
null
null
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2010,2014,2015,2018,2019,2020,2021, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_TOPOLOGY_BLOCK_H #define GMX_TOPOLOGY_BLOCK_H #include <stdio.h> #include <vector> #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/range.h" namespace gmx { template<typename> class ListOfLists; /*! \brief Division of a range of indices into consecutive blocks * * A range of consecutive indices 0 to full.range.end() is divided * into numBlocks() consecutive blocks of consecutive indices. * Block b contains indices i for which block(b).begin() <= i < block(b).end(). */ class RangePartitioning { public: /*! \brief A block defined by a range of atom indices */ using Block = Range<int>; /*! \brief Returns the number of blocks */ int numBlocks() const { return static_cast<int>(index_.size()) - 1; } /*! \brief Returns the size of the block with index \p blockIndex */ Block block(int blockIndex) const { return Block(index_[blockIndex], index_[blockIndex + 1LL]); } /*! \brief Returns the full range */ Block fullRange() const { return Block(index_.front(), index_.back()); } /*! \brief Returns a range starting at \p blockIndexBegin and ending at \p blockIndexEnd */ Block subRange(int blockIndexBegin, int blockIndexEnd) const { return Block(index_[blockIndexBegin], index_[blockIndexEnd]); } /*! \brief Returns true when all blocks have size 0 or numBlocks()=0 */ bool allBlocksHaveSizeOne() const { return (index_.back() == numBlocks()); } /*! \brief Appends a block of size \p blockSize at the end of the range * * \note blocksize has to be >= 1 */ void appendBlock(int blockSize) { GMX_ASSERT(blockSize > 0, "block sizes should be >= 1"); index_.push_back(index_.back() + blockSize); } /*! \brief Removes all blocks */ void clear() { index_.resize(1); } /*! \brief Reduces the number of blocks to \p newNumBlocks * * \note \p newNumBlocks should be <= numBlocks(). */ void reduceNumBlocks(int newNumBlocks) { GMX_ASSERT(newNumBlocks <= numBlocks(), "Can only shrink to fewer blocks"); index_.resize(newNumBlocks + 1LL); } /*! \brief Sets the partitioning to \p numBlocks blocks each of size 1 */ void setAllBlocksSizeOne(int numBlocks); /*! \brief Returns the raw block index array, avoid using this */ std::vector<int>& rawIndex() { return index_; } private: std::vector<int> index_ = { 0 }; /**< The list of block begin/end indices */ }; } // namespace gmx /* Deprecated, C-style version of RangePartitioning */ typedef struct t_block { int blockSize(int blockIndex) const { GMX_ASSERT(blockIndex < nr, "blockIndex should be in range"); return index[blockIndex + 1] - index[blockIndex]; } int nr; /* The number of blocks */ int* index; /* Array of indices (dim: nr+1) */ int nalloc_index; /* The allocation size for index */ } t_block; struct t_blocka { int nr; /* The number of blocks */ int* index; /* Array of indices in a (dim: nr+1) */ int nra; /* The number of atoms */ int* a; /* Array of atom numbers in each group */ /* (dim: nra) */ /* Block i (0<=i<nr) runs from */ /* index[i] to index[i+1]-1. There will */ /* allways be an extra entry in index */ /* to terminate the table */ int nalloc_index; /* The allocation size for index */ int nalloc_a; /* The allocation size for a */ }; /*! \brief * Fully initialize t_block datastructure. * * Initializes a \p block and sets up the first index to zero. * * \param[in,out] block datastructure to initialize. */ void init_block(t_block* block); /*! \brief * Fully initialize t_blocka datastructure. * * Initializes a \p block and sets up the first index to zero. * The atom number array is initialized to nullptr. * * \param[in,out] block datastructure to initialize. */ void init_blocka(t_blocka* block); /* TODO * In general all t_block datastructures should be avoided * in favour of RangePartitioning. This here is a simple cludge * to use more modern initialization while we move to the use * of RangePartitioning. */ /*! \brief * Minimal initialization of t_block datastructure. * * Performs the equivalent to a snew on a t_block, setting all * values to zero or nullptr. Needed for some cases where the topology * handling expects a block to be valid initialized (e.g. during domain * decomposition) but without the first block set to zero. * * \param[in,out] block datastructure to initialize. */ void init_block_null(t_block* block); /*! \brief * Minimal initialization of t_blocka datastructure. * * Performs the equivalent to a snew on a t_blocka, setting all * values to zero or nullptr. Needed for some cases where the topology * handling expects a block to be valid initialized (e.g. during domain * decomposition) but without the first block set to zero. * * \param[in,out] block datastructure to initialize. */ void init_blocka_null(t_blocka* block); t_blocka* new_blocka(); /* allocate new block */ void done_block(t_block* block); //! Deallocates memory within \c block void done_blocka(t_blocka* block); void copy_blocka(const t_blocka* src, t_blocka* dest); void copy_block(const t_block* src, t_block* dst); void stupid_fill_block(t_block* grp, int natom, gmx_bool bOneIndexGroup); /* Fill a block structure with numbers identical to the index * (0, 1, 2, .. natom-1) * If bOneIndexGroup, then all atoms are lumped in one index group, * otherwise there is one atom per index entry */ void stupid_fill_blocka(t_blocka* grp, int natom); /* Fill a block structure with numbers identical to the index * (0, 1, 2, .. natom-1) * There is one atom per index entry */ void pr_block(FILE* fp, int indent, const char* title, const t_block* block, gmx_bool bShowNumbers); void pr_blocka(FILE* fp, int indent, const char* title, const t_blocka* block, gmx_bool bShowNumbers); void pr_listoflists(FILE* fp, int indent, const char* title, const gmx::ListOfLists<int>* block, gmx_bool bShowNumbers); #endif
35.227074
120
0.6896
d26303bf61d201c7579403e5c18295c1bdad2a68
246
h
C
local_addons/ofxCv/example-difference-columns/src/ofApp.h
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
446
2015-01-08T00:14:06.000Z
2022-03-16T13:08:03.000Z
local_addons/ofxCv/example-difference-columns/src/ofApp.h
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
139
2015-01-02T19:20:53.000Z
2021-05-03T16:54:45.000Z
local_addons/ofxCv/example-difference-columns/src/ofApp.h
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
195
2015-01-18T05:13:39.000Z
2022-03-21T08:24:37.000Z
#pragma once #include "ofMain.h" #include "ofxCv.h" class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); ofVideoGrabber cam; ofPixels previous; ofImage diff; cv::Mat columnMean; };
14.470588
32
0.626016
321c1b371bb418fd9409a35e8bccccb89d25f6d3
2,348
c
C
sqlite/config.c
jklowden/mmalloc
161eb83c9ec838d0dab6b77c3e134e3a9fd55e2f
[ "BSD-3-Clause" ]
1
2021-07-27T17:28:40.000Z
2021-07-27T17:28:40.000Z
sqlite/config.c
jklowden/mmalloc
161eb83c9ec838d0dab6b77c3e134e3a9fd55e2f
[ "BSD-3-Clause" ]
null
null
null
sqlite/config.c
jklowden/mmalloc
161eb83c9ec838d0dab6b77c3e134e3a9fd55e2f
[ "BSD-3-Clause" ]
null
null
null
#include <mmalloc.h> #include <sqlite3.h> #include <err.h> size_t mmsize( void *ptr ); size_t mmrequired( size_t size ); /* * The sqlite3_config() interface may only be invoked prior to library * initialization using sqlite3_initialize() or after shutdown by * sqlite3_shutdown(). * https://www.sqlite.org/c3ref/config.html */ #if false typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; #endif static void *xMalloc( int size ) { malloc(size); } static void xFree( void *p ) { free(p); } static void *xRealloc( void *ptr, int size ) { realloc(ptr, size); } static int xSize( void *ptr ) { return (int) mmsize(ptr); } static int xRoundup( int size ) { return (int) mmrequired(size); } /* * By calling mmalloc once, the global variables used to compute sizes * in support of xSize and xRoundup are initialized. */ static int xInit( void *ptr ) { void *p = mmalloc(1); mfree(p); return SQLITE_OK; } static void xShutdown( void *p ) { ; } sqlite3_mem_methods methods = { xMalloc, xFree, xRealloc, xSize, xRoundup, xInit, xShutdown, NULL }; int use_libmmalloc() { int erc; /* * SQLITE_CONFIG_MALLOC The SQLITE_CONFIG_MALLOC option takes a * single argument which is a pointer to an instance of the * sqlite3_mem_methods structure. The argument specifies * alternative low-level memory allocation routines to be used in * place of the memory allocation routines built into * SQLite. SQLite makes its own private copy of the content of the * sqlite3_mem_methods structure before the sqlite3_config() call * returns. */ if( (erc = sqlite3_config(SQLITE_CONFIG_MALLOC, &methods)) != SQLITE_OK ) { errx(EXIT_FAILURE, "%s", sqlite3_errstr(erc)); } return erc; }
23.019608
79
0.67121
9a5799fe62026317c38f1a90776ab53ac80794c4
1,498
h
C
Unix Family/Linux.Darkside/main.h
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
3
2021-05-15T15:57:13.000Z
2022-03-16T09:11:05.000Z
Unix Family/Linux.Darkside/main.h
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
null
null
null
Unix Family/Linux.Darkside/main.h
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
3
2021-05-15T15:57:15.000Z
2022-01-08T20:51:04.000Z
#include "needed.h" MALLOC_DEFINE (HIDDEN_FILES, "hfile", "struct"); MALLOC_DEFINE (HIDDEN_PIDS, "hpid", "struct"); MALLOC_DEFINE (HIDDEN_PORTS, "hport", "struct"); MALLOC_DEFINE (HIDDEN_HOSTS, "hh", "struct"); MALLOC_DEFINE (PIDS, "pids", "int"); MALLOC_DEFINE (FILENAMES, "filenames", "char"); static int module_ops (struct module*, int, void*); static int start_module (void); static int end_module (void); static int check_proc (struct proc *p, int recursive); static int infect_oid (int *name, int size, int (*infected_func)(SYSCTL_HANDLER_ARGS), int (**old_func)(SYSCTL_HANDLER_ARGS)); static struct protected_pids* check_pid (int pid); static int hide_pid (int pid); static int unhide_pid (struct protected_pids *pp); static struct hidden_files* check_file (char *filename); static int hide_file (char *filename); static int unhide_file (struct hidden_files *pf); static struct protected_hosts* check_ip (u_int ip); static u_int hide_ip (u_int ip); static int unhide_ip (struct protected_hosts *ph); static struct protected_ports* check_port (u_short port); static int hide_port (u_short port); static int unhide_port (struct protected_ports *port); static int u2k (struct proc *p, struct u2k_args *uap); static int hide_link_file (int id); typedef TAILQ_HEAD(, module) modulelist_t; struct module { TAILQ_ENTRY(module) link; TAILQ_ENTRY(module) flink; struct linker_file *file; int refs; int id; char *name; modeventhand_t handler; void *arg; modspecific_t data; };
33.288889
126
0.756342
2c659fe269964783d6836bf8ce5913cc58a2f539
26,165
h
C
src/axisym_poroelasticity/Taxisym_poroelasticity_elements.h
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
src/axisym_poroelasticity/Taxisym_poroelasticity_elements.h
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
1
2022-03-23T16:16:41.000Z
2022-03-23T16:16:41.000Z
src/axisym_poroelasticity/Taxisym_poroelasticity_elements.h
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
// LIC// ==================================================================== // LIC// This file forms part of oomph-lib, the object-oriented, // LIC// multi-physics finite-element library, available // LIC// at http://www.oomph-lib.org. // LIC// // LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel // LIC// // LIC// This library is free software; you can redistribute it and/or // LIC// modify it under the terms of the GNU Lesser General Public // LIC// License as published by the Free Software Foundation; either // LIC// version 2.1 of the License, or (at your option) any later version. // LIC// // LIC// This library is distributed in the hope that it will be useful, // LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of // LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // LIC// Lesser General Public License for more details. // LIC// // LIC// You should have received a copy of the GNU Lesser General Public // LIC// License along with this library; if not, write to the Free Software // LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // LIC// 02110-1301 USA. // LIC// // LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk. // LIC// // LIC//==================================================================== #ifndef OOMPH_TAXISYM_POROELASTICITY_ELEMENTS_HEADER #define OOMPH_TAXISYM_POROELASTICITY_ELEMENTS_HEADER // Config header generated by autoconfig #ifdef HAVE_CONFIG_H #include <oomph-lib-config.h> #endif #include "axisym_poroelasticity_elements.h" #include "../generic/Telements.h" namespace oomph { /// ================================================================= /// Element which solves the Darcy/linear elasticity equations /// using TElements /// Geometrically the element is always a six noded triangle. /// We use the mid-side nodes to store edge-based flux degrees of /// freedom and internal data for the discontinuous pressure /// and internal flux dofs. /// ================================================================= template<unsigned ORDER> class TAxisymmetricPoroelasticityElement : public TElement<2, 3>, public AxisymmetricPoroelasticityEquations { private: /// The number of values stored at each node static const unsigned Initial_Nvalue[]; /// Face index associated with edge flux degree of freedom static const unsigned Face_index_of_edge_flux[]; /// Conversion scheme from an edge degree of freedom to the node /// it's stored at static const unsigned Q_edge_conv[]; /// The points along each edge where the fluxes are taken to be static const double Flux_interpolation_point[]; /// The internal data index where the internal q degrees of freedom are /// stored unsigned Q_internal_data_index; /// The internal data index where the p degrees of freedom are stored unsigned P_internal_data_index; /// Unit normal signs associated with each edge to ensure /// inter-element continuity of the flux std::vector<short> Sign_edge; public: /// Constructor TAxisymmetricPoroelasticityElement(); /// Destructor ~TAxisymmetricPoroelasticityElement(); /// Number of values required at node n unsigned required_nvalue(const unsigned& n) const { return Initial_Nvalue[n]; } /// Return the face index associated with specified edge unsigned face_index_of_edge(const unsigned& j) const { return (j + 2) % 3; } /// Compute the face element coordinates of the nth flux /// interpolation point along specified edge void face_local_coordinate_of_flux_interpolation_point( const unsigned& edge, const unsigned& n, Vector<double>& s) const { // Get the location of the n-th flux interpolation point along // the edge in terms of the distance along the edge itself Vector<double> flux_interpolation_point = edge_flux_interpolation_point(edge, n); // Convert the edge number to the number of the mid-edge node along that // edge unsigned node_number = Q_edge_conv[edge]; // The edge basis functions are defined in a clockwise manner, so we have // to effectively "flip" some coordinates switch (node_number) { case 3: s[0] = flux_interpolation_point[0]; break; case 4: s[0] = 1.0 - flux_interpolation_point[0]; break; case 5: s[0] = flux_interpolation_point[0]; break; } } /// Return the face index associated with j-th edge flux degree of freedom unsigned face_index_of_q_edge_basis_fct(const unsigned& j) const { return Face_index_of_edge_flux[j]; } /// Return the nodal index of the j-th solid displacement unknown /// [0: r; 1: z] unsigned u_index_axisym_poroelasticity(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= 2) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0,1)"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return j; } /// Return the equation number of the j-th edge (flux) degree of freedom int q_edge_local_eqn(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= nq_basis_edge()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_edge() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return this->nodal_local_eqn(q_edge_node_number(j), q_edge_index(j)); } /// Return the equation number of the j-th internal degree of freedom int q_internal_local_eqn(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= nq_basis_internal()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_internal() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return internal_local_eqn(q_internal_index(), j); } /// Return vector of pointers to the Data objects that store the /// edge flux values Vector<Data*> q_edge_data_pt() const { // It's the mid-side nodes: Vector<Data*> data_pt(3); data_pt[0] = node_pt(3); data_pt[1] = node_pt(4); data_pt[2] = node_pt(5); return data_pt; } /// Return pointer to the Data object that stores the internal flux values Data* q_internal_data_pt() const { return this->internal_data_pt(Q_internal_data_index); } /// Return the index of the internal data where the q_internal /// degrees of freedom are stored unsigned q_internal_index() const { return Q_internal_data_index; } /// Return the nodal index at which the jth edge unknown is stored unsigned q_edge_index(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= (nq_basis_edge())) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_edge() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return j % (ORDER + 1) + 2; } /// Return the number of the node where the jth edge unknown is stored unsigned q_edge_node_number(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= (nq_basis_edge())) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_edge() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return Q_edge_conv[j / (ORDER + 1)]; } /// Get pointer to node that stores the edge flux dofs for specified edge Node* edge_flux_node_pt(const unsigned& edge) { return node_pt(Q_edge_conv[edge]); } /// Return the values of the j-th edge (flux) degree of freedom double q_edge(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= (nq_basis_edge())) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_edge() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return nodal_value(q_edge_node_number(j), q_edge_index(j)); } /// Return the values of the j-th edge (flux) degree of /// freedom at time history level t double q_edge(const unsigned& t, const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= (nq_basis_edge())) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_edge() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return nodal_value(t, q_edge_node_number(j), q_edge_index(j)); } /// Return the values of the internal degree of freedom double q_internal(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= nq_basis_internal()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_internal() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return this->internal_data_pt(q_internal_index())->value(j); } /// Return the value of the j-th internal degree of freedom at /// time history level t double q_internal(const unsigned& t, const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= nq_basis_internal()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_internal() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return this->internal_data_pt(q_internal_index())->value(t, j); } /// Pin the j-th edge (flux) degree of freedom and set it to specified value void pin_q_edge_value(const unsigned& j, const double& value) { node_pt(q_edge_node_number(j))->pin(q_edge_index(j)); node_pt(q_edge_node_number(j))->set_value(q_edge_index(j), value); } /// Set the values of the j-th edge (flux) degree of freedom void set_q_edge(const unsigned& j, const double& value) { node_pt(q_edge_node_number(j))->set_value(q_edge_index(j), value); } /// Set the values of the j-th edge (flux) degree of freedom at /// time history level t void set_q_edge(const unsigned& t, const unsigned& j, const double& value) { node_pt(q_edge_node_number(j))->set_value(t, q_edge_index(j), value); } /// Set the values of the j-th internal degree of freedom void set_q_internal(const unsigned& j, const double& value) { this->internal_data_pt(q_internal_index())->set_value(j, value); } /// Set the values of the j-th internal degree of freedom at /// time history level t void set_q_internal(const unsigned& t, const unsigned& j, const double& value) { this->internal_data_pt(q_internal_index())->set_value(t, j, value); } /// Return the number of edge basis functions for flux q unsigned nq_basis_edge() const; /// Return the number of internal basis functions for flux q unsigned nq_basis_internal() const; /// Returns the local form of the q basis at local coordinate s void get_q_basis_local(const Vector<double>& s, Shape& q_basis) const; /// Returns the local form of the q basis and dbasis/ds at local coordinate /// s void get_div_q_basis_local(const Vector<double>& s, Shape& div_q_basis_ds) const; /// Returns the number of flux_interpolation points along each /// edge of the element unsigned nedge_flux_interpolation_point() const; /// Returns the local coordinate of the jth flux_interpolation point /// along specified edge Vector<double> edge_flux_interpolation_point(const unsigned& edge, const unsigned& j) const { #ifdef RANGE_CHECKING if (edge >= 3) { std::ostringstream error_message; error_message << "Range Error: edge " << edge << " is not in the range (0,2)"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } if (j >= nedge_flux_interpolation_point()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nedge_flux_interpolation_point() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif Vector<double> coord(1); coord[0] = (1.0 - sign_edge(edge)) / 2.0 + sign_edge(edge) * Flux_interpolation_point[j]; return coord; } /// Compute the global coordinates of the jth flux_interpolation /// point along specified edge void edge_flux_interpolation_point_global(const unsigned& edge, const unsigned& j, Vector<double>& x) const { #ifdef RANGE_CHECKING if (edge >= 3) { std::ostringstream error_message; error_message << "Range Error: edge " << edge << " is not in the range (0,2)"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } if (j >= nedge_flux_interpolation_point()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nedge_flux_interpolation_point() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif // Get the location of the n-th flux_interpolation point along the // edge in terms of the distance along the edge itself Vector<double> flux_interpolation_point = edge_flux_interpolation_point(edge, j); // Convert the edge number to the number of the mid-edge node along that // edge unsigned node_number = Q_edge_conv[edge]; // Storage for the local coords of the flux_interpolation point Vector<double> s_flux_interpolation(2, 0); // The edge basis functions are defined in a clockwise manner, so we have // to effectively "flip" the coordinates along edges 0 and 1 to match this switch (node_number) { case 3: s_flux_interpolation[0] = 1.0 - flux_interpolation_point[0]; s_flux_interpolation[1] = flux_interpolation_point[0]; break; case 4: s_flux_interpolation[0] = 0.0; s_flux_interpolation[1] = 1.0 - flux_interpolation_point[0]; break; case 5: s_flux_interpolation[0] = flux_interpolation_point[0]; s_flux_interpolation[1] = 0.0; break; } // Calculate the global coordinates from the local ones interpolated_x(s_flux_interpolation, x); } /// Pin the jth internal q value and set it to specified value void pin_q_internal_value(const unsigned& j, const double& q) { #ifdef RANGE_CHECKING if (j >= nq_basis_internal()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << nq_basis_internal() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif this->internal_data_pt(q_internal_index())->pin(j); this->internal_data_pt(q_internal_index())->set_value(j, q); } /// Return the equation number of the j-th pressure degree of freedom int p_local_eqn(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= np_basis()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << np_basis() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return this->internal_local_eqn(P_internal_data_index, j); } /// Return the jth pressure value double p_value(const unsigned& j) const { #ifdef RANGE_CHECKING if (j >= np_basis()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << np_basis() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif return this->internal_data_pt(P_internal_data_index)->value(j); } /// Return the total number of pressure basis functions unsigned np_basis() const; /// Return the pressure basis void get_p_basis(const Vector<double>& s, Shape& p_basis) const; /// Pin the jth pressure value and set to specified value void pin_p_value(const unsigned& j, const double& p) { #ifdef RANGE_CHECKING if (j >= np_basis()) { std::ostringstream error_message; error_message << "Range Error: j " << j << " is not in the range (0," << np_basis() - 1 << ")"; throw OomphLibError(error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif this->internal_data_pt(P_internal_data_index)->pin(j); this->internal_data_pt(P_internal_data_index)->set_value(j, p); } /// Return pointer to the Data object that stores the pressure values Data* p_data_pt() const { return this->internal_data_pt(P_internal_data_index); } /// Set the jth pressure value void set_p_value(const unsigned& j, const double& value) { this->internal_data_pt(P_internal_data_index)->set_value(j, value); } /// Scale the edge basis to allow arbitrary edge mappings void scale_basis(Shape& basis) const { // Storage for the lengths of the edges of the element Vector<double> length(3, 0.0); // Temporary storage for the vertex positions double x0, y0, x1, y1; // loop over the edges of the element and calculate their lengths (in x-y // space) for (unsigned i = 0; i < 3; i++) { x0 = this->node_pt(i)->x(0); y0 = this->node_pt(i)->x(1); x1 = this->node_pt((i + 1) % 3)->x(0); y1 = this->node_pt((i + 1) % 3)->x(1); length[i] = std::sqrt(std::pow(y1 - y0, 2) + std::pow(x1 - x0, 2)); } // lengths of the sides of the reference element (in the same order as the // basis functions) const double ref_length[3] = {std::sqrt(2.0), 1, 1}; // get the number of basis functions associated with the edges unsigned n_q_basis_edge = nq_basis_edge(); // rescale the edge basis functions to allow arbitrary edge mappings from // element to ref. element const unsigned n_index2 = basis.nindex2(); for (unsigned i = 0; i < n_index2; i++) { for (unsigned l = 0; l < n_q_basis_edge; l++) { basis(l, i) *= (length[l / (ORDER + 1)] / ref_length[l / (ORDER + 1)]); } } } /// Accessor for the unit normal sign of edge n (const version) const short& sign_edge(const unsigned& n) const { return Sign_edge[n]; } /// Accessor for the unit normal sign of edge n short& sign_edge(const unsigned& n) { return Sign_edge[n]; } /// Output with default number of plot points void output(std::ostream& outfile) { AxisymmetricPoroelasticityEquations::output(outfile); } /// Output FE representation of soln: x,y,u1,u2,div_q,p at /// Nplot^DIM plot points void output(std::ostream& outfile, const unsigned& Nplot) { AxisymmetricPoroelasticityEquations::output(outfile, Nplot); } /// Number of vertex nodes in the element unsigned nvertex_node() const { return TElement<2, 3>::nvertex_node(); } /// Pointer to the j-th vertex node in the element Node* vertex_node_pt(const unsigned& j) const { return TElement<2, 3>::vertex_node_pt(j); } /// Recovery order for Z2 error estimator unsigned nrecovery_order() { return 2; // need to experiment with this... } protected: /// Returns the geometric basis, and the u, p and divergence basis /// functions and test functions at local coordinate s double shape_basis_test_local(const Vector<double>& s, Shape& psi, DShape& dpsi, Shape& u_basis, Shape& u_test, DShape& du_basis_dx, DShape& du_test_dx, Shape& q_basis, Shape& q_test, Shape& p_basis, Shape& p_test, Shape& div_q_basis_ds, Shape& div_q_test_ds) const { const unsigned n_q_basis = this->nq_basis(); Shape q_basis_local(n_q_basis, 2); this->get_q_basis_local(s, q_basis_local); this->get_p_basis(s, p_basis); this->get_div_q_basis_local(s, div_q_basis_ds); double J = this->transform_basis(s, q_basis_local, psi, dpsi, q_basis); // u_basis consists of the normal Lagrangian shape functions u_basis = psi; du_basis_dx = dpsi; u_test = psi; du_test_dx = dpsi; q_test = q_basis; p_test = p_basis; div_q_test_ds = div_q_basis_ds; return J; } /// Returns the geometric basis, and the u, p and divergence basis /// functions and test functions at integration point ipt double shape_basis_test_local_at_knot(const unsigned& ipt, Shape& psi, DShape& dpsi, Shape& u_basis, Shape& u_test, DShape& du_basis_dx, DShape& du_test_dx, Shape& q_basis, Shape& q_test, Shape& p_basis, Shape& p_test, Shape& div_q_basis_ds, Shape& div_q_test_ds) const { Vector<double> s(2); for (unsigned i = 0; i < 2; i++) { s[i] = this->integral_pt()->knot(ipt, i); } return shape_basis_test_local(s, psi, dpsi, u_basis, u_test, du_basis_dx, du_test_dx, q_basis, q_test, p_basis, p_test, div_q_basis_ds, div_q_test_ds); } }; //================================================================ /// Face geometry for TAxisymmetricPoroelasticityElement<0> //================================================================ template<> class FaceGeometry<TAxisymmetricPoroelasticityElement<0>> : public virtual TElement<1, 3> { public: /// Constructor: Call constructor of base FaceGeometry() : TElement<1, 3>() {} }; //================================================================ /// Face geometry for TAxisymmetricPoroelasticityElement<1> //================================================================ template<> class FaceGeometry<TAxisymmetricPoroelasticityElement<1>> : public virtual TElement<1, 3> { public: /// Constructor: Call constructor of base class FaceGeometry() : TElement<1, 3>() {} }; } // namespace oomph #endif
35.026774
80
0.57145
cf2ff4e0b61dd84b4afde1879e6af262f2c64fb1
782
c
C
system/libs/sys/src/syscall.c
tonytsangzen/micro_kernel_os
e6e2bde5c64a9e703611ab47cc07a5cb6f670840
[ "Apache-2.0" ]
null
null
null
system/libs/sys/src/syscall.c
tonytsangzen/micro_kernel_os
e6e2bde5c64a9e703611ab47cc07a5cb6f670840
[ "Apache-2.0" ]
null
null
null
system/libs/sys/src/syscall.c
tonytsangzen/micro_kernel_os
e6e2bde5c64a9e703611ab47cc07a5cb6f670840
[ "Apache-2.0" ]
null
null
null
#include <syscall.h> inline int32_t syscall3(int32_t code, int32_t arg0, int32_t arg1, int32_t arg2) { volatile int32_t r; __asm__ volatile( "stmdb sp!, {lr}\n" "mrs r0, cpsr\n" "stmdb sp!, {r0}\n" "mov r0, %1 \n" "mov r1, %2 \n" "mov r2, %3 \n" "mov r3, %4 \n" "swi #0 \n" "mov %0, r0 \n" // assign r = r0 "ldmia sp!, {r1}\n" "ldmia sp!, {lr}\n" : "=r" (r) : "r" (code), "r" (arg0), "r" (arg1), "r" (arg2) : "r0", "r1", "r2", "r3" ); return r; } inline int32_t syscall2(int32_t code, int32_t arg0, int32_t arg1) { return syscall3(code, arg0, arg1, 0); } inline int32_t syscall1(int32_t code, int32_t arg0) { return syscall3(code, arg0, 0, 0); } inline int32_t syscall0(int32_t code) { return syscall3(code, 0, 0, 0); }
23
81
0.57289
682111928161411a64dba592f9d173ba32b3e729
428
c
C
chapter_7/projects/09/09.c
reinvanimschoot/c-programming-a-modern-approach-solutions
7aabcd763d231cc0af3a250383a97a335c24ac6c
[ "CC-BY-4.0" ]
null
null
null
chapter_7/projects/09/09.c
reinvanimschoot/c-programming-a-modern-approach-solutions
7aabcd763d231cc0af3a250383a97a335c24ac6c
[ "CC-BY-4.0" ]
null
null
null
chapter_7/projects/09/09.c
reinvanimschoot/c-programming-a-modern-approach-solutions
7aabcd763d231cc0af3a250383a97a335c24ac6c
[ "CC-BY-4.0" ]
null
null
null
#include <stdio.h> #include <ctype.h> int main(void) { int hours_in_12, hours_in_24, minutes; char indicator; printf("Enter a 12-hour time: "); scanf("%2d:%2d %c", &hours_in_12, &minutes, &indicator); if (tolower(indicator) == 'a') hours_in_24 = hours_in_12; else hours_in_24 = hours_in_12 + 12; printf("Equivalent in 24-time: %.2d:%.2d", hours_in_24, minutes); return 0; }
19.454545
69
0.614486
fd9ac90a477a60d5aef19dbefe42095716af23e1
378
h
C
SensorsSDK/SensorsAnalyticsDynamicDelegate.h
zhanghuixin815/SensorsSDK
94a9cc80bd89a52714bbf6e1d321deeac82eb39b
[ "MIT" ]
4
2021-03-24T06:53:10.000Z
2021-03-24T07:53:45.000Z
SensorsSDK/SensorsAnalyticsDynamicDelegate.h
zhanghuixin815/SensorsSDK
94a9cc80bd89a52714bbf6e1d321deeac82eb39b
[ "MIT" ]
null
null
null
SensorsSDK/SensorsAnalyticsDynamicDelegate.h
zhanghuixin815/SensorsSDK
94a9cc80bd89a52714bbf6e1d321deeac82eb39b
[ "MIT" ]
null
null
null
// // SensorsAnalyticsDynamicDelegate.h // SensorsSDK // // Created by 张慧鑫 on 2021/4/3. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SensorsAnalyticsDynamicDelegate : NSObject +(void)proxyWithTableViewDelegate:(id<UITableViewDelegate>)delegate; +(void)proxyWithCollectionViewDelegate:(id<UICollectionViewDelegate>)delegate; @end NS_ASSUME_NONNULL_END
18
78
0.798942
ca2d52c7d9dd641e6bd9e59539911a3bb6ea40c2
1,246
h
C
src/nodeMap/NodesMap.h
MatteoMaso/VisualSuffixTree
54aca4b2d6878982cd17f28f3d9645c1b70a8a4b
[ "MIT" ]
1
2018-12-18T13:19:33.000Z
2018-12-18T13:19:33.000Z
src/nodeMap/NodesMap.h
MatteoMaso/VisualSuffixTree
54aca4b2d6878982cd17f28f3d9645c1b70a8a4b
[ "MIT" ]
1
2018-12-17T23:07:20.000Z
2018-12-17T23:07:20.000Z
src/nodeMap/NodesMap.h
MatteoMaso/VisualSuffixTree
54aca4b2d6878982cd17f28f3d9645c1b70a8a4b
[ "MIT" ]
1
2021-01-31T23:23:54.000Z
2021-01-31T23:23:54.000Z
// // Created by root on 11/11/18. // #ifndef VISUALSUFFIXTREE_NODESMAP_H #define VISUALSUFFIXTREE_NODESMAP_H #include <map> #include "../node/Node_2.h" //for the levelDB attempt #include <cassert> #include "../leveldb/include/leveldb/db.h" //todo this is a new class for the Map /* * This class contains all the nodes and manage the memory storage of them */ class NodesMap { public: NodesMap(const char * fileName, std::string modeDb); ~NodesMap(); //deconstructor void showDBcontent(); void showContent(); void addNode(NodeNew * n); //add a node into the local map void removeNode(nodeNew::index idx); //remove the node required NodeNew * getNode(nodeNew::index idx); //return the Node required bool readFromMemory(); unsigned long getNumberOfElement(); private: std::string DBMODE; //Database reading or writing mode leveldb::DB* db; std::map<nodeNew::index, NodeNew *> local_map; //bool loadFile(const char * fileName); //Load the file from the memory into the local map bool writeToMemory(); //This method takes the node from the local map and put into the computer memory }; #endif //VISUALSUFFIXTREE_NODESMAP_H
20.766667
120
0.67817
30db5b13215f9aa56e86612dff2ca4e93f5f3338
955
h
C
cc/test/skia_common.h
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
cc/test/skia_common.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
cc/test/skia_common.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_TEST_SKIA_COMMON_H_ #define CC_TEST_SKIA_COMMON_H_ #include <memory> #include "base/memory/ref_counted.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkRefCnt.h" namespace gfx { class Rect; class Size; } namespace cc { class DisplayItemList; void DrawDisplayList(unsigned char* buffer, const gfx::Rect& layer_rect, scoped_refptr<const DisplayItemList> list); bool AreDisplayListDrawingResultsSame(const gfx::Rect& layer_rect, const DisplayItemList* list_a, const DisplayItemList* list_b); sk_sp<SkImage> CreateDiscardableImage(const gfx::Size& size); } // namespace cc #endif // CC_TEST_SKIA_COMMON_H_
27.285714
73
0.692147
aa26aad02c35ccad8acb10148efebe64b3cd065b
428
h
C
src/IUnknownImpl.h
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
1
2019-01-11T18:39:14.000Z
2019-01-11T18:39:14.000Z
src/IUnknownImpl.h
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
null
null
null
src/IUnknownImpl.h
itsuart/win-cpp-wrappers
a5c85c96cde46a043a2a2d90fe6671e21e8b6253
[ "Unlicense" ]
null
null
null
#pragma once #include <unknwn.h> namespace helpers { class IUnknownImpl : public IUnknown { public: IUnknownImpl() noexcept; virtual ~IUnknownImpl() {}; virtual ULONG __stdcall AddRef() override; virtual ULONG __stdcall Release() override; virtual HRESULT __stdcall QueryInterface(const IID& requestedIID, void** ppv) override; protected: ULONG m_refs; }; }
20.380952
95
0.651869
aa4bdb5dbdebadfe0eeb111b41d317131ebef35c
34,081
c
C
src/tss2-esys/esys_crypto_mbed.c
eckelmeckel/tpm2-tss
198201e726eb8bea3fa3c17efd2bda992355f6b3
[ "BSD-2-Clause" ]
1
2021-12-20T09:47:51.000Z
2021-12-20T09:47:51.000Z
src/tss2-esys/esys_crypto_mbed.c
eckelmeckel/tpm2-tss
198201e726eb8bea3fa3c17efd2bda992355f6b3
[ "BSD-2-Clause" ]
null
null
null
src/tss2-esys/esys_crypto_mbed.c
eckelmeckel/tpm2-tss
198201e726eb8bea3fa3c17efd2bda992355f6b3
[ "BSD-2-Clause" ]
null
null
null
/* SPDX-License-Identifier: BSD-2-Clause */ /******************************************************************************* * Copyright: 2020, Andreas Dröscher * All rights reserved. ******************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <string.h> #include <mbedtls/md.h> #include <mbedtls/rsa.h> #include <mbedtls/ecdh.h> #include <mbedtls/aes.h> #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #include "esys_iutil.h" #include "esys_mu.h" #define LOGMODULE esys_crypto #include "util/log.h" #include "util/aux_util.h" /** Context to hold temporary values for iesys_crypto */ typedef struct _IESYS_CRYPTO_CONTEXT { enum { IESYS_CRYPTMBED_TYPE_HASH = 1, IESYS_CRYPTMBED_TYPE_HMAC, } type; /**< The type of context to hold; hash or hmac */ union { struct { mbedtls_md_context_t mbed_context; size_t hash_len; } hash; /**< the state variables for a hash context */ struct { mbedtls_md_context_t mbed_context; size_t hmac_len; } hmac; /**< the state variables for an hmac context */ }; } IESYS_CRYPTMBED_CONTEXT; /** Provide the context for the computation of a hash digest. * * The context will be created and initialized according to the hash function. * @param[out] context The created context (callee-allocated). * @param[in] hashAlg The hash algorithm for the creation of the context. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_VALUE or TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. * @retval TSS2_ESYS_RC_MEMORY Memory cannot be allocated. * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_hash_start(IESYS_CRYPTO_CONTEXT_BLOB ** context, TPM2_ALG_ID hashAlg) { TSS2_RC r = TSS2_RC_SUCCESS; const mbedtls_md_info_t* md_info = NULL; if (context == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed in for context"); } IESYS_CRYPTMBED_CONTEXT *mycontext = calloc(1, sizeof(IESYS_CRYPTMBED_CONTEXT)); return_if_null(mycontext, "Out of Memory", TSS2_ESYS_RC_MEMORY); mbedtls_md_init(&mycontext->hash.mbed_context); switch(hashAlg) { case TPM2_ALG_SHA1: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1); break; case TPM2_ALG_SHA256: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); break; case TPM2_ALG_SHA384: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384); break; } if (md_info == NULL) { goto_error(r, TSS2_ESYS_RC_NOT_IMPLEMENTED, "Unsupported hash algorithm (%"PRIu16")", cleanup, hashAlg); } mycontext->hash.hash_len = mbedtls_md_get_size(md_info); if (mbedtls_md_setup(&mycontext->hash.mbed_context, md_info, true) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HASH setup", cleanup); } if (mbedtls_md_starts(&mycontext->hash.mbed_context) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HASH start", cleanup); } mycontext->type = IESYS_CRYPTMBED_TYPE_HASH; *context = (IESYS_CRYPTO_CONTEXT_BLOB *) mycontext; return TSS2_RC_SUCCESS; cleanup: mbedtls_md_free(&mycontext->hash.mbed_context); SAFE_FREE(mycontext); return r; } /** Update the digest value of a digest object from a byte buffer. * * The context of a digest object will be updated according to the hash * algorithm of the context. < * @param[in,out] context The context of the digest object which will be updated. * @param[in] buffer The data for the update. * @param[in] size The size of the data buffer. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. */ TSS2_RC iesys_cryptmbed_hash_update(IESYS_CRYPTO_CONTEXT_BLOB * context, const uint8_t * buffer, size_t size) { if (context == NULL || buffer == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HASH) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "bad context"); } if (mbedtls_md_update(&mycontext->hash.mbed_context, buffer, size) != 0) { return_error(TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HASH update"); } return TSS2_RC_SUCCESS; } /** Update the digest value of a digest object from a TPM2B object. * * The context of a digest object will be updated according to the hash * algorithm of the context. * @param[in,out] context The context of the digest object which will be updated. * @param[in] b The TPM2B object for the update. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. */ TSS2_RC iesys_cryptmbed_hash_update2b(IESYS_CRYPTO_CONTEXT_BLOB * context, TPM2B * b) { if (context == NULL || b == NULL) { return TSS2_ESYS_RC_BAD_REFERENCE; } TSS2_RC ret = iesys_cryptmbed_hash_update(context, &b->buffer[0], b->size); return ret; } /** Get the digest value of a digest object and close the context. * * The digest value will written to a passed buffer and the resources of the * digest object are released. * @param[in,out] context The context of the digest object to be released * @param[out] buffer The buffer for the digest value (caller-allocated). * @param[out] size The size of the digest. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_hash_finish(IESYS_CRYPTO_CONTEXT_BLOB ** context, uint8_t * buffer, size_t * size) { TSS2_RC r = TSS2_RC_SUCCESS; if (context == NULL || *context == NULL || buffer == NULL || size == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) * context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HASH) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "bad context"); } if (*size < mycontext->hash.hash_len) { return_error(TSS2_ESYS_RC_BAD_SIZE, "Buffer too small"); } if (mbedtls_md_finish(&mycontext->hmac.mbed_context, buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HASH finish", cleanup); } *size = mycontext->hash.hash_len; cleanup: mbedtls_md_free(&mycontext->hash.mbed_context); SAFE_FREE(mycontext); *context = NULL; return r; } /** Release the resources of a digest object. * * The assigned resources will be released and the context will be set to NULL. * @param[in,out] context The context of the digest object. */ void iesys_cryptmbed_hash_abort(IESYS_CRYPTO_CONTEXT_BLOB ** context) { if (context == NULL || *context == NULL) { return; } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) * context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HASH) { return; } mbedtls_md_free(&mycontext->hash.mbed_context); free(mycontext); *context = NULL; } /* HMAC */ /** Provide the context an HMAC digest object from a byte buffer key. * * The context will be created and initialized according to the hash function * and the used HMAC key. * @param[out] context The created context (callee-allocated). * @param[in] hmacAlg The hash algorithm for the HMAC computation. * @param[in] key The byte buffer of the HMAC key. * @param[in] size The size of the HMAC key. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. * @retval TSS2_ESYS_RC_MEMORY Memory cannot be allocated. * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_hmac_start(IESYS_CRYPTO_CONTEXT_BLOB ** context, TPM2_ALG_ID hashAlg, const uint8_t * key, size_t size) { TSS2_RC r = TSS2_RC_SUCCESS; const mbedtls_md_info_t* md_info = NULL; if (context == NULL || key == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed in for context"); } IESYS_CRYPTMBED_CONTEXT *mycontext = calloc(1, sizeof(IESYS_CRYPTMBED_CONTEXT)); return_if_null(mycontext, "Out of Memory", TSS2_ESYS_RC_MEMORY); mbedtls_md_init(&mycontext->hash.mbed_context); switch(hashAlg) { case TPM2_ALG_SHA1: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1); break; case TPM2_ALG_SHA256: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); break; case TPM2_ALG_SHA384: md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384); break; } if (md_info == NULL) { goto_error(r, TSS2_ESYS_RC_NOT_IMPLEMENTED, "Unsupported hash algorithm (%"PRIu16")", cleanup, hashAlg); } mycontext->hmac.hmac_len = mbedtls_md_get_size(md_info); if (mbedtls_md_setup(&mycontext->hash.mbed_context, md_info, true) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HMAC setup", cleanup); } if (mbedtls_md_hmac_starts(&mycontext->hash.mbed_context, key, size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HMAC start", cleanup); } mycontext->type = IESYS_CRYPTMBED_TYPE_HMAC; *context = (IESYS_CRYPTO_CONTEXT_BLOB *) mycontext; return TSS2_RC_SUCCESS; cleanup: mbedtls_md_free(&mycontext->hmac.mbed_context); SAFE_FREE(mycontext); return r; } /** Update and HMAC digest value from a byte buffer. * * The context of a digest object will be updated according to the hash * algorithm and the key of the context. * @param[in,out] context The context of the digest object which will be updated. * @param[in] buffer The data for the update. * @param[in] size The size of the data buffer. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. */ TSS2_RC iesys_cryptmbed_hmac_update(IESYS_CRYPTO_CONTEXT_BLOB * context, const uint8_t * buffer, size_t size) { if (context == NULL || buffer == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HMAC) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "bad context"); } if (mbedtls_md_hmac_update(&mycontext->hmac.mbed_context, buffer, size) != 0) { return_error(TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HMAC update"); } return TSS2_RC_SUCCESS; } /** Update and HMAC digest value from a TPM2B object. * * The context of a digest object will be updated according to the hash * algorithm and the key of the context. * @param[in,out] context The context of the digest object which will be updated. * @param[in] b The TPM2B object for the update. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. */ TSS2_RC iesys_cryptmbed_hmac_update2b(IESYS_CRYPTO_CONTEXT_BLOB * context, TPM2B * b) { if (context == NULL || b == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } TSS2_RC ret = iesys_cryptmbed_hmac_update(context, &b->buffer[0], b->size); return ret; } /** Write the HMAC digest value to a byte buffer and close the context. * * The digest value will written to a passed buffer and the resources of the * HMAC object are released. * @param[in,out] context The context of the HMAC object. * @param[out] buffer The buffer for the digest value (caller-allocated). * @param[out] size The size of the digest. * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. * @retval TSS2_ESYS_RC_BAD_SIZE If the size passed is lower than the HMAC length. * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_hmac_finish(IESYS_CRYPTO_CONTEXT_BLOB ** context, uint8_t * buffer, size_t * size) { TSS2_RC r = TSS2_RC_SUCCESS; if (context == NULL || *context == NULL || buffer == NULL || size == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) * context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HMAC) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "bad context"); } if (*size < mycontext->hmac.hmac_len) { return_error(TSS2_ESYS_RC_BAD_SIZE, "Buffer too small"); } if (mbedtls_md_hmac_finish(&mycontext->hmac.mbed_context, buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "MBED HMAC finish", cleanup); } *size = mycontext->hmac.hmac_len; cleanup: mbedtls_md_free(&mycontext->hmac.mbed_context); SAFE_FREE(mycontext); *context = NULL; return r; } /** Write the HMAC digest value to a TPM2B object and close the context. * * The digest value will written to a passed TPM2B object and the resources of * the HMAC object are released. * @param[in,out] context The context of the HMAC object. * @param[out] hmac The buffer for the digest value (caller-allocated). * @retval TSS2_RC_SUCCESS on success. * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters. * @retval TSS2_ESYS_RC_BAD_SIZE if the size passed is lower than the HMAC length. * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_hmac_finish2b(IESYS_CRYPTO_CONTEXT_BLOB ** context, TPM2B * hmac) { if (context == NULL || *context == NULL || hmac == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Null-Pointer passed"); } size_t s = hmac->size; TSS2_RC ret = iesys_cryptmbed_hmac_finish(context, &hmac->buffer[0], &s); hmac->size = s; return ret; } /** Release the resources of an HAMC object. * * The assigned resources will be released and the context will be set to NULL. * @param[in,out] context The context of the HMAC object. */ void iesys_cryptmbed_hmac_abort(IESYS_CRYPTO_CONTEXT_BLOB ** context) { if (context == NULL || *context == NULL) { return; } IESYS_CRYPTMBED_CONTEXT *mycontext = (IESYS_CRYPTMBED_CONTEXT *) * context; if (mycontext->type != IESYS_CRYPTMBED_TYPE_HMAC) { return; } mbedtls_md_free(&mycontext->hmac.mbed_context); free(mycontext); *context = NULL; } /** Wrapper for mbedtls random number generator * * @param[in] context Optional unused parameter. * @param[out] buffer Buffer to write randomness to. * @param[om] buf_size Number of bytes to write to buffer. */ static int get_random(void* context, unsigned char * buffer, size_t buf_size) { (void)context; int r = 0; //success in terms of mbedtls mbedtls_entropy_context entropy_context; mbedtls_entropy_init(&entropy_context); mbedtls_ctr_drbg_context drbg_context; mbedtls_ctr_drbg_init(&drbg_context); if (mbedtls_ctr_drbg_seed(&drbg_context, mbedtls_entropy_func, &entropy_context, NULL, 0) != 0) { goto_error(r, MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, "Could not seed random number generator.", cleanup); } if (mbedtls_ctr_drbg_random(&drbg_context, &buffer[0], buf_size) != 0) { goto_error(r, MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG, "Failure in random number generator.", cleanup); } cleanup: mbedtls_ctr_drbg_free(&drbg_context); mbedtls_entropy_free(&entropy_context); return r; } /** Compute random TPM2B data. * * The random data will be generated and written to a passed TPM2B structure. * @param[out] nonce The TPM2B structure for the random data (caller-allocated). * @param[in] num_bytes The number of bytes to be generated. * @retval TSS2_RC_SUCCESS on success. * * NOTE: the TPM should not be used to obtain the random data */ TSS2_RC iesys_cryptmbed_random2b(TPM2B_NONCE * nonce, size_t num_bytes) { if (num_bytes == 0) { nonce->size = sizeof(TPMU_HA); } else { nonce->size = num_bytes; } if (get_random(NULL, &nonce->buffer[0], nonce->size) != 0) { return_error(TSS2_ESYS_RC_GENERAL_FAILURE, "Hash algorithm not supported"); } return TSS2_RC_SUCCESS; } /** Encryption of a buffer using a public (RSA) key. * * Encrypting a buffer using a public key is used for example during * Esys_StartAuthSession in order to encrypt the salt value. * @param[in] key The key to be used for encryption. * @param[in] in_size The size of the buffer to be encrypted. * @param[in] in_buffer The data buffer to be encrypted. * @param[in] max_out_size The maximum size for the output encrypted buffer. * @param[out] out_buffer The encrypted buffer. * @param[out] out_size The size of the encrypted output. * @param[in] label The label used in the encryption scheme. * @retval TSS2_RC_SUCCESS on success * @retval TSS2_ESYS_RC_BAD_VALUE The algorithm of key is not implemented. * @retval TSS2_ESYS_RC_GENERAL_FAILURE The internal crypto engine failed. */ TSS2_RC iesys_cryptmbed_pk_encrypt(TPM2B_PUBLIC * pub_tpm_key, size_t in_size, BYTE * in_buffer, size_t max_out_size, BYTE * out_buffer, size_t * out_size, const char *label) { TSS2_RC r = TSS2_RC_SUCCESS; mbedtls_rsa_context rsa_context; switch(pub_tpm_key->publicArea.nameAlg) { case TPM2_ALG_SHA1: mbedtls_rsa_init(&rsa_context, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA1); break; case TPM2_ALG_SHA256: mbedtls_rsa_init(&rsa_context, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256); break; case TPM2_ALG_SHA384: mbedtls_rsa_init(&rsa_context, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA384); break; case TPM2_ALG_SHA512: mbedtls_rsa_init(&rsa_context, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA512); break; default: return_error(TSS2_ESYS_RC_NOT_IMPLEMENTED, "Hash algorithm not supported"); } if (pub_tpm_key->publicArea.unique.rsa.size == 0) { goto_error(r, TSS2_ESYS_RC_BAD_VALUE, "Public key size may not be 0", cleanup); } UINT8 exp[sizeof(UINT32)] = { 0x00, 0x01, 0x00, 0x01 }; //big-endian 65537 UINT32 exp_as_int = pub_tpm_key->publicArea.parameters.rsaDetail.exponent; if (exp_as_int != 0) { exp[0] = (exp_as_int >> 24) & 0xff; exp[1] = (exp_as_int >> 16) & 0xff; exp[2] = (exp_as_int >> 8) & 0xff; exp[3] = (exp_as_int >> 0) & 0xff; } if (mbedtls_rsa_import_raw(&rsa_context, pub_tpm_key->publicArea.unique.rsa.buffer, pub_tpm_key->publicArea.unique.rsa.size, NULL /* p */, 0, NULL /* q */, 0, NULL /* d */, 0, &exp[0], sizeof(UINT32)) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Could not import public key", cleanup); } if (mbedtls_rsa_complete(&rsa_context) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Could not complete key import", cleanup); } if (mbedtls_rsa_get_len(&rsa_context) > max_out_size) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Encrypted data too big", cleanup); } switch (pub_tpm_key->publicArea.parameters.rsaDetail.scheme.scheme) { case TPM2_ALG_RSAES: if (mbedtls_rsa_pkcs1_encrypt(&rsa_context, get_random, NULL, MBEDTLS_RSA_PUBLIC, in_size, in_buffer, out_buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Could not encrypt data.", cleanup); } break; case TPM2_ALG_OAEP: if (mbedtls_rsa_rsaes_oaep_encrypt(&rsa_context, get_random, NULL, MBEDTLS_RSA_PUBLIC, (const UINT8*)label, strlen(label) + 1, in_size, in_buffer, out_buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Could not encrypt data.", cleanup); } break; default: goto_error(r, TSS2_ESYS_RC_BAD_VALUE, "Illegal RSA scheme", cleanup); break; } *out_size = mbedtls_rsa_get_len(&rsa_context); r = TSS2_RC_SUCCESS; cleanup: mbedtls_rsa_free(&rsa_context); return r; } /** Computation of ephemeral ECC key and shared secret Z. * * According to the description in TPM spec part 1 C 6.1 a shared secret * between application and TPM is computed (ECDH). An ephemeral ECC key and a * TPM key are used for the ECDH key exchange. * @param[in] key The key to be used for ECDH key exchange. * @param[in] max_out_size the max size for the output of the public key of the * computed ephemeral key. * @param[out] Z The computed shared secret. * @param[out] Q The public part of the ephemeral key in TPM format. * @param[out] out_buffer The public part of the ephemeral key will be marshaled * to this buffer. * @param[out] out_size The size of the marshaled output. * @retval TSS2_RC_SUCCESS on success * @retval TSS2_ESYS_RC_BAD_VALUE The algorithm of key is not implemented. * @retval TSS2_ESYS_RC_GENERAL_FAILURE The internal crypto engine failed. */ TSS2_RC iesys_cryptmbed_get_ecdh_point(TPM2B_PUBLIC *key, size_t max_out_size, TPM2B_ECC_PARAMETER *Z, TPMS_ECC_POINT *Q, BYTE * out_buffer, size_t * out_size) { TSS2_RC r = TSS2_RC_SUCCESS; mbedtls_ecdh_context ecdh_context; mbedtls_ecdh_init(&ecdh_context); /* Load named curve */ switch (key->publicArea.parameters.eccDetail.curveID) { case TPM2_ECC_NIST_P192: if(mbedtls_ecp_group_load(&ecdh_context.grp, MBEDTLS_ECP_DP_SECP192R1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECP group load failed", cleanup); } break; case TPM2_ECC_NIST_P224: if(mbedtls_ecp_group_load(&ecdh_context.grp, MBEDTLS_ECP_DP_SECP224R1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECP group load failed", cleanup); } break; case TPM2_ECC_NIST_P256: if(mbedtls_ecp_group_load(&ecdh_context.grp, MBEDTLS_ECP_DP_SECP256R1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECP group load failed", cleanup); } break; case TPM2_ECC_NIST_P384: if(mbedtls_ecp_group_load(&ecdh_context.grp, MBEDTLS_ECP_DP_SECP384R1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECP group load failed", cleanup); } break; case TPM2_ECC_NIST_P521: if(mbedtls_ecp_group_load(&ecdh_context.grp, MBEDTLS_ECP_DP_SECP521R1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECP group load failed", cleanup); } break; default: return_error(TSS2_ESYS_RC_NOT_IMPLEMENTED, "ECC curve not implemented."); } /* Generate ephemeral key */ if (mbedtls_ecdh_gen_public(&ecdh_context.grp, &ecdh_context.d, &ecdh_context.Q, get_random, NULL) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECDH gen failed", cleanup); } /* Write affine coordinates of ephemeral pub key to TPM point Q * * Note * mpi_write_bin prepends numbers with 0 if they are smaller as * TPM2_MAX_ECC_KEY_BYTES. This is for big-endian mathematicaly * correct but breaks the interface if we want to set bignum.size * to anything but TPM2_MAX_ECC_KEY_BYTES. The easiest fix is * to shrink out_size to mpi_size. */ Q->x.size = mbedtls_mpi_size(&ecdh_context.Q.X); if (Q->x.size > TPM2_MAX_ECC_KEY_BYTES) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Q.x does not fit into byte buffer", cleanup); } if (mbedtls_mpi_write_binary(&ecdh_context.Q.X, &Q->x.buffer[0], Q->x.size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Q.x to byte buffer failed", cleanup); } Q->y.size = mbedtls_mpi_size(&ecdh_context.Q.Y); if (Q->y.size > TPM2_MAX_ECC_KEY_BYTES) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Q.y does not fit into byte buffer", cleanup); } if (mbedtls_mpi_write_binary(&ecdh_context.Q.Y, &Q->y.buffer[0], Q->y.size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Q.y to byte buffer failed", cleanup); } /* Initialise Qp.Z (Qp would be zero, or "at infinity", if Z == 0) */ if (mbedtls_mpi_lset(&ecdh_context.Qp.Z, 1) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Init of Qp.z to 1 failed", cleanup); } /* Read ephemeral pub key from TPM to Qp */ if (mbedtls_mpi_read_binary(&ecdh_context.Qp.X, &key->publicArea.unique.ecc.x.buffer[0], key->publicArea.unique.ecc.x.size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Read of Qp.x from byte buffer failed", cleanup); } if (mbedtls_mpi_read_binary(&ecdh_context.Qp.Y, &key->publicArea.unique.ecc.y.buffer[0], key->publicArea.unique.ecc.y.size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Read of Qp.y from byte buffer failed", cleanup); } /* Validate TPM's pub key */ if (mbedtls_ecp_check_pubkey(&ecdh_context.grp, &ecdh_context.Qp) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Point Qp is invalid", cleanup); } /* Calculate shared secret */ if (mbedtls_ecdh_compute_shared(&ecdh_context.grp, &ecdh_context.z, &ecdh_context.Qp, &ecdh_context.d, get_random, NULL) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "ECDH compute shared failed", cleanup); } /* Write shared secret to TPM ECC param Z */ Z->size = mbedtls_mpi_size(&ecdh_context.z); if (Z->size > TPM2_MAX_ECC_KEY_BYTES) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Q.y does not fit into byte buffer", cleanup); } if (mbedtls_mpi_write_binary(&ecdh_context.z, &Z->buffer[0], Z->size) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Write Z to byte buffer failed", cleanup); } /* Write the public ephemeral key in TPM format to out buffer */ size_t offset = 0; r = Tss2_MU_TPMS_ECC_POINT_Marshal(Q, &out_buffer[0], max_out_size, &offset); goto_if_error(r, "Error marshaling Q", cleanup); *out_size = offset; cleanup: mbedtls_ecdh_free(&ecdh_context); return r; } /** Encrypt data with AES. * * @param[in] key key used for AES. * @param[in] tpm_sym_alg AES type in TSS2 notation (must be TPM2_ALG_AES). * @param[in] key_bits Key size in bits. * @param[in] tpm_mode Block cipher mode of opertion in TSS2 notation (CFB). * For parameter encryption only CFB can be used. * @param[in] blk_len Length Block length of AES. * @param[in,out] buffer Data to be encrypted. The encrypted date will be stored * in this buffer. * @param[in] buffer_size size of data to be encrypted. * @param[in] iv The initialization vector. The size is equal to blk_len. * @retval TSS2_RC_SUCCESS on success, or TSS2_ESYS_RC_BAD_VALUE and * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters, * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_sym_aes_encrypt(uint8_t * key, TPM2_ALG_ID tpm_sym_alg, TPMI_AES_KEY_BITS key_bits, TPM2_ALG_ID tpm_mode, size_t blk_len, uint8_t * buffer, size_t buffer_size, uint8_t * iv) { /* Parameter blk_len needed for other crypto libraries */ (void)blk_len; TSS2_RC r = TSS2_RC_SUCCESS; mbedtls_aes_context aes_ctx; if (key == NULL || buffer == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Bad reference"); } mbedtls_aes_init(&aes_ctx); if (tpm_sym_alg != TPM2_ALG_AES || tpm_mode != TPM2_ALG_CFB) { goto_error(r, TSS2_ESYS_RC_BAD_VALUE, "AES encrypt called with wrong algorithm.", cleanup); } if (mbedtls_aes_setkey_enc(&aes_ctx, key, key_bits) != 0) { goto_error(r, TSS2_ESYS_RC_BAD_VALUE, "Key size not not implemented.", cleanup); } size_t iv_off = 0; if (mbedtls_aes_crypt_cfb128(&aes_ctx, MBEDTLS_AES_ENCRYPT, buffer_size, &iv_off, iv, buffer, buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Enncrypt", cleanup); } cleanup: mbedtls_aes_free(&aes_ctx); return r; } /** Decrypt data with AES. * * @param[in] key key used for AES. * @param[in] tpm_sym_alg AES type in TSS2 notation (must be TPM2_ALG_AES). * @param[in] key_bits Key size in bits. * @param[in] tpm_mode Block cipher mode of opertion in TSS2 notation (CFB). * For parameter encryption only CFB can be used. * @param[in] blk_len Length Block length of AES. * @param[in,out] buffer Data to be decrypted. The decrypted date will be stored * in this buffer. * @param[in] buffer_size size of data to be encrypted. * @param[in] iv The initialization vector. The size is equal to blk_len. * @retval TSS2_RC_SUCCESS on success, or TSS2_ESYS_RC_BAD_VALUE and * @retval TSS2_ESYS_RC_BAD_REFERENCE for invalid parameters, * @retval TSS2_ESYS_RC_GENERAL_FAILURE for errors of the crypto library. */ TSS2_RC iesys_cryptmbed_sym_aes_decrypt(uint8_t * key, TPM2_ALG_ID tpm_sym_alg, TPMI_AES_KEY_BITS key_bits, TPM2_ALG_ID tpm_mode, size_t blk_len, uint8_t * buffer, size_t buffer_size, uint8_t * iv) { /* Parameter blk_len needed for other crypto libraries */ (void)blk_len; TSS2_RC r = TSS2_RC_SUCCESS; mbedtls_aes_context aes_ctx; if (key == NULL || buffer == NULL) { return_error(TSS2_ESYS_RC_BAD_REFERENCE, "Bad reference"); } mbedtls_aes_init(&aes_ctx); if (tpm_sym_alg != TPM2_ALG_AES || tpm_mode != TPM2_ALG_CFB) { goto_error(r, TSS2_ESYS_RC_BAD_VALUE, "AES encrypt called with wrong algorithm.", cleanup); } /* Note in mbedTLS Documentation: * For CFB, you must set up the context with mbedtls_aes_setkey_enc(), * regardless of whether you are performing an encryption or decryption * operation, that is, regardless of the mode parameter. This is because * CFB mode uses the same key schedule for encryption and decryption. */ if (mbedtls_aes_setkey_enc(&aes_ctx, key, key_bits) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Key size not not implemented.", cleanup); } size_t iv_off = 0; if (mbedtls_aes_crypt_cfb128(&aes_ctx, MBEDTLS_AES_DECRYPT, buffer_size, &iv_off, iv, buffer, buffer) != 0) { goto_error(r, TSS2_ESYS_RC_GENERAL_FAILURE, "Dencrypt", cleanup); } cleanup: mbedtls_aes_free(&aes_ctx); return r; }
36.685684
87
0.624512
802e05a131e86a5e430cc9060af34c2f3e9e3e28
2,668
c
C
main/gamefont.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
2
2022-01-15T17:56:45.000Z
2022-02-16T17:58:02.000Z
main/gamefont.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
1
2022-02-16T18:08:42.000Z
2022-02-21T07:42:27.000Z
main/gamefont.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
null
null
null
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ /* * $Source: f:/miner/source/main/rcs/gamefont.c $ * $Revision: 2.0 $ * $Author: john $ * $Date: 1995/02/27 11:30:14 $ * * Fonts for the game. * * $Log: gamefont.c $ * Revision 2.0 1995/02/27 11:30:14 john * New version 2.0, which has no anonymous unions, builds with * Watcom 10.0, and doesn't require parsing BITMAPS.TBL. * * Revision 1.8 1994/11/18 16:41:39 adam * trimmed some meat * * Revision 1.7 1994/11/17 13:07:11 adam * removed unused font * * Revision 1.6 1994/11/03 21:36:12 john * Added code for credit fonts. * * Revision 1.5 1994/08/17 20:20:02 matt * Took out alternate-color versions of font3, since this is a mono font * * Revision 1.4 1994/08/12 12:03:44 adam * tweaked fonts. * * Revision 1.3 1994/08/11 12:43:40 adam * changed font filenames * * Revision 1.2 1994/08/10 19:57:15 john * Changed font stuff; Took out old menu; messed up lots of * other stuff like game sequencing messages, etc. * * Revision 1.1 1994/08/10 17:20:09 john * Initial revision * * */ #pragma off (unreferenced) static char rcsid[] = "$Id: gamefont.c 2.0 1995/02/27 11:30:14 john Exp $"; #pragma on (unreferenced) #include <stdlib.h> #include "gr.h" #include "gamefont.h" char * Gamefont_filenames[] = { "font1-1.fnt", // Font 0 "font2-1.fnt", // Font 1 "font2-2.fnt", // Font 2 "font2-3.fnt", // Font 3 "font3-1.fnt", // Font 4 }; grs_font *Gamefonts[MAX_FONTS]; int Gamefont_installed=0; void gamefont_init() { int i; if (Gamefont_installed) return; Gamefont_installed = 1; for (i=0; i<MAX_FONTS; i++ ) Gamefonts[i] = gr_init_font(Gamefont_filenames[i]); atexit( gamefont_close ); } void gamefont_close() { int i; if (!Gamefont_installed) return; Gamefont_installed = 0; for (i=0; i<MAX_FONTS; i++ ) { gr_close_font( Gamefonts[i] ); Gamefonts[i] = NULL; } }
25.902913
75
0.673913
43bbf48cb2105ed51a1d589a95fb7dec3fdfd90f
1,308
h
C
src/parser/metadata/JsonKeys.h
daphne-eu/daphne
64d4040132cf4059efaf184c4e363dbb921c87d6
[ "Apache-2.0" ]
10
2022-03-31T21:49:35.000Z
2022-03-31T23:37:06.000Z
src/parser/metadata/JsonKeys.h
daphne-eu/daphne
64d4040132cf4059efaf184c4e363dbb921c87d6
[ "Apache-2.0" ]
3
2022-03-31T22:10:10.000Z
2022-03-31T22:46:30.000Z
src/parser/metadata/JsonKeys.h
daphne-eu/daphne
64d4040132cf4059efaf184c4e363dbb921c87d6
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 The DAPHNE Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SRC_PARSER_METADATA_JSONPARAMS_H #define SRC_PARSER_METADATA_JSONPARAMS_H #include <string> /** * @brief A container that contains names of JSON keys for a file * metadata. * */ struct JsonKeys { // mandatory keys inline static const std::string NUM_ROWS = "numRows"; // int inline static const std::string NUM_COLS = "numCols"; // int // should always contain exactly one of the following keys inline static const std::string VALUE_TYPE = "valueType"; // string inline static const std::string SCHEMA = "schema"; // array of objects // optional key inline static const std::string NUM_NON_ZEROS = "numNonZeros"; // int (default: -1) }; #endif
31.902439
88
0.716361
43bd7b84fa6624b53f0edbcfd766a3de90e1b1e6
18,772
h
C
src/core/hw/gfxip/rpm/gfx9/gfx9RsrcProcMgr.h
dnovillo/pal
f924a4fb84efde321f7754031f8cfa5ab35055d3
[ "MIT" ]
null
null
null
src/core/hw/gfxip/rpm/gfx9/gfx9RsrcProcMgr.h
dnovillo/pal
f924a4fb84efde321f7754031f8cfa5ab35055d3
[ "MIT" ]
null
null
null
src/core/hw/gfxip/rpm/gfx9/gfx9RsrcProcMgr.h
dnovillo/pal
f924a4fb84efde321f7754031f8cfa5ab35055d3
[ "MIT" ]
null
null
null
/* *********************************************************************************************************************** * * Copyright (c) 2015-2018 Advanced Micro Devices, Inc. All Rights Reserved. * * 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. * **********************************************************************************************************************/ #pragma once #include "core/hw/gfxip/rpm/rsrcProcMgr.h" namespace Pal { class GfxCmdBuffer; class QueryPool; namespace Gfx9 { class CmdUtil; class Device; class Gfx9MaskRam; class Image; struct SyncReqs; enum class DccClearPurpose : uint32; // ===================================================================================================================== // GFX9+10 common hardware layer implementation of the Resource Processing Manager. It is most known for handling // GFX9+10-specific resource operations like DCC decompression. class RsrcProcMgr : public Pal::RsrcProcMgr { public: static constexpr bool ForceGraphicsFillMemoryPath = false; void CmdCopyMemory( GfxCmdBuffer* pCmdBuffer, const GpuMemory& srcGpuMemory, const GpuMemory& dstGpuMemory, uint32 regionCount, const MemoryCopyRegion* pRegions) const; void CmdCloneImageData( GfxCmdBuffer* pCmdBuffer, const Image& srcImage, const Image& dstImage) const; void CmdUpdateMemory( GfxCmdBuffer* pCmdBuffer, const GpuMemory& dstMem, gpusize dstOffset, gpusize dataSize, const uint32* pData) const; void CmdResolveQuery( GfxCmdBuffer* pCmdBuffer, const Pal::QueryPool& queryPool, QueryResultFlags flags, QueryType queryType, uint32 startQuery, uint32 queryCount, const GpuMemory& dstGpuMemory, gpusize dstOffset, gpusize dstStride) const; void DccDecompress( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const IMsaaState* pMsaaState, const MsaaQuadSamplePattern* pQuadSamplePattern, const SubresRange& range) const; void FmaskColorExpand( GfxCmdBuffer* pCmdBuffer, const Image& image, const SubresRange& range) const; void FmaskDecompress( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const IMsaaState* pMsaaState, const MsaaQuadSamplePattern* pQuadSamplePattern, const SubresRange& range) const; bool InitMaskRam( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& range) const; void BuildHtileLookupTable( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range) const; virtual bool FastClearEliminate( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const IMsaaState* pMsaaState, const MsaaQuadSamplePattern* pQuadSamplePattern, const SubresRange& range) const; virtual void ExpandDepthStencil( GfxCmdBuffer* pCmdBuffer, const Pal::Image& image, const IMsaaState* pMsaaState, const MsaaQuadSamplePattern* pQuadSamplePattern, const SubresRange& range) const override; virtual void CmdCopyMemoryToImage( GfxCmdBuffer* pCmdBuffer, const GpuMemory& srcGpuMemory, const Pal::Image& dstImage, ImageLayout dstImageLayout, uint32 regionCount, const MemoryImageCopyRegion* pRegions, bool includePadding) const override; virtual void CmdCopyImageToMemory( GfxCmdBuffer* pCmdBuffer, const Pal::Image& srcImage, ImageLayout srcImageLayout, const GpuMemory& dstGpuMemory, uint32 regionCount, const MemoryImageCopyRegion* pRegions, bool includePadding) const override; bool WillDecompressWithCompute( const GfxCmdBuffer* pCmdBuffer, const Image& gfxImage, const SubresRange& range) const; protected: explicit RsrcProcMgr(Device* pDevice); virtual ~RsrcProcMgr() {} virtual void HwlCreateDecompressResolveSafeImageViewSrds( uint32 numSrds, const ImageViewInfo* pImageView, void* pSrdTable) const override; virtual const Pal::GraphicsPipeline* GetGfxPipelineByTargetIndexAndFormat( RpmGfxPipeline basePipeline, uint32 targetIndex, SwizzledFormat format) const override; virtual bool CopyImageUseMipLevelInSrd(bool isCompressed) const override { return (RsrcProcMgr::UseMipLevelInSrd && (isCompressed == false)); } bool ClearDcc( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange, uint8 clearCode, DccClearPurpose clearPurpose, const uint32* pPackedClearColor = nullptr) const; virtual void ClearDccCompute( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange, uint8 clearCode, DccClearPurpose clearPurpose, const uint32* pPackedClearColor = nullptr) const = 0; ImageAspect DecodeImageViewSrdAspect( const Pal::Image& image, gpusize srdBaseAddr) const; static uint32 ExpandClearCodeToDword(uint8 clearCode); virtual void FastDepthStencilClearCompute( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue, uint32 clearMask) const = 0; void FastDepthStencilClearComputeCommon( GfxCmdBuffer* pCmdBuffer, const Pal::Image* pPalImage, uint32 clearMask) const; uint32 GetClearDepth( const Image& dstImage, const SubresRange& clearRange, uint32 mipLevel) const; virtual bool HwlUseOptimizedImageCopy( const Pal::Image& srcImage, const Pal::Image& dstImage) const override; virtual void HwlUpdateDstImageFmaskMetaData( GfxCmdBuffer* pCmdBuffer, const Pal::Image& srcImage, const Pal::Image& dstImage, uint32 regionCount, const ImageCopyRegion* pRegions, uint32 flags) const override; virtual bool HwlImageUsesCompressedWrites( const uint32* pImageSrd) const override { return false; } virtual void HwlUpdateDstImageStateMetaData( GfxCmdBuffer* pCmdBuffer, const Pal::Image& dstImage, const SubresRange& range) const override {} virtual void HwlFixupResolveDstImage( GfxCmdBuffer* pCmdBuffer, const GfxImage& dstImage, ImageLayout dstImageLayout, const ImageResolveRegion* pRegions, uint32 regionCount, bool computeResolve ) const override; static void MetaDataDispatch( GfxCmdBuffer* pCmdBuffer, const Image& image, const Gfx9MaskRam* pMaskRam, uint32 width, uint32 height, uint32 depth, const uint32* pThreadsPerGroup); void CommitBeginEndGfxCopy( Pal::CmdStream* pCmdStream, uint32 paScTileSteeringOverride) const; Device*const m_pDevice; const CmdUtil& m_cmdUtil; private: void CmdCopyMemoryFromToImageViaPixels( GfxCmdBuffer* pCmdBuffer, const Pal::Image& image, const GpuMemory& memory, const MemoryImageCopyRegion& region, bool includePadding, bool imageIsSrc) const; static Extent3d GetCopyViaSrdCopyDims( const Pal::Image& image, const SubresId& subResId, bool includePadding); static bool UsePixelCopy( const Pal::Image& image, const MemoryImageCopyRegion& region); virtual void HwlFastColorClear( GfxCmdBuffer* pCmdBuffer, const GfxImage& dstImage, const uint32* pConvertedColor, const SubresRange& clearRange) const override; virtual void HwlDepthStencilClear( GfxCmdBuffer* pCmdBuffer, const GfxImage& dstImage, ImageLayout depthLayout, ImageLayout stencilLayout, float depth, uint8 stencil, uint32 rangeCount, const SubresRange* pRanges, bool fastClear, bool needComputeSync, uint32 boxCnt, const Box* pBox) const override; virtual bool HwlCanDoFixedFuncResolve( const Pal::Image& srcImage, const Pal::Image& dstImage, ResolveMode resolveMode, uint32 regionCount, const ImageResolveRegion* pRegions) const override; virtual bool HwlCanDoDepthStencilCopyResolve( const Pal::Image& srcImage, const Pal::Image& dstImage, uint32 regionCount, const ImageResolveRegion* pRegions) const override; void ClearFmask( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& clearRange, uint64 clearValue) const; virtual void InitCmask( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const SubresRange& range) const = 0; void InitHtile( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange) const; void InitDepthClearMetaData( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& range) const; void InitColorClearMetaData( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& range) const; void DepthStencilClearGraphics( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, float depth, uint8 stencil, uint32 clearMask, bool fastClear, ImageLayout depthLayout, ImageLayout stencilLayout, uint32 boxCnt, const Box* pBox) const; uint32* UpdateBoundFastClearColor( GfxCmdBuffer* pCmdBuffer, const GfxImage& dstImage, uint32 startMip, uint32 numMips, const uint32 color[4], CmdStream* pStream, uint32* pCmdSpace) const; void UpdateBoundFastClearDepthStencil( GfxCmdBuffer* pCmdBuffer, const GfxImage& dstImage, const SubresRange& range, uint32 metaDataClearFlags, float depth, uint8 stencil) const; void DccDecompressOnCompute( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const SubresRange& range) const; void CmdResolveQueryComputeShader( GfxCmdBuffer* pCmdBuffer, const Pal::QueryPool& queryPool, QueryResultFlags flags, QueryType queryType, uint32 startQuery, uint32 queryCount, const GpuMemory& dstGpuMemory, gpusize dstOffset, gpusize dstStride) const; const SPI_SHADER_EX_FORMAT DeterminePsExportFmt( SwizzledFormat format, bool blendEnabled, bool shaderExportsAlpha, bool blendSrcAlphaToColor, bool enableAlphaToCoverage) const; PAL_DISALLOW_DEFAULT_CTOR(RsrcProcMgr); PAL_DISALLOW_COPY_AND_ASSIGN(RsrcProcMgr); }; // ===================================================================================================================== // GFX9 specific implementation of RPM. class Gfx9RsrcProcMgr : public Pal::Gfx9::RsrcProcMgr { public: explicit Gfx9RsrcProcMgr(Device* pDevice) : Pal::Gfx9::RsrcProcMgr(pDevice) {} virtual ~Gfx9RsrcProcMgr() {} void HwlExpandHtileHiZRange( GfxCmdBuffer* pCmdBuffer, const GfxImage& image, const SubresRange& range) const override; protected: void ClearDccCompute( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange, uint8 clearCode, DccClearPurpose clearPurpose, const uint32* pPackedClearColor = nullptr) const override; void FastDepthStencilClearCompute( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue, uint32 clearMask) const override; virtual const Pal::ComputePipeline* GetCmdGenerationPipeline( const Pal::IndirectCmdGenerator& generator, const CmdBuffer& cmdBuffer) const override; void HwlDecodeBufferViewSrd( const void* pBufferViewSrd, BufferViewInfo* pViewInfo) const override; void HwlDecodeImageViewSrd( const void* pImageViewSrd, const Pal::Image& dstImage, SwizzledFormat* pSwizzledFormat, SubresRange* pSubresRange) const override; void InitCmask( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const SubresRange& range) const override; private: void ClearHtileAllBytes( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue) const; void ClearHtileSelectedBytes( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue, uint32 htileMask) const; void DoFastClear( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange, uint8 clearCode, DccClearPurpose clearPurpose) const; void DoOptimizedCmaskInit( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& image, const SubresRange& range, uint8 initValue ) const; void DoOptimizedFastClear( GfxCmdBuffer* pCmdBuffer, Pal::CmdStream* pCmdStream, const Image& dstImage, const SubresRange& clearRange, uint8 clearCode, DccClearPurpose clearPurpose) const; void DoOptimizedHtileFastClear( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue, uint32 htileMask) const; void ExecuteHtileEquation( GfxCmdBuffer* pCmdBuffer, const Image& dstImage, const SubresRange& range, uint32 htileValue, uint32 htileMask) const; void HwlHtileCopyAndFixUp( GfxCmdBuffer* pCmdBuffer, const Pal::Image& srcImage, const Pal::Image& dstImage, uint32 regionCount, const ImageResolveRegion* pRegions) const override; void HwlUpdateDstImageFmaskMetaData( GfxCmdBuffer* pCmdBuffer, const Pal::Image& srcImage, const Pal::Image& dstImage, uint32 regionCount, const ImageCopyRegion* pRegions, uint32 flags) const override; virtual uint32 HwlBeginGraphicsCopy( Pal::GfxCmdBuffer* pCmdBuffer, const Pal::GraphicsPipeline* pPipeline, const Pal::Image& dstImage, uint32 bpp) const override; virtual void HwlEndGraphicsCopy( Pal::CmdStream* pCmdStream, uint32 restoreMask) const override; PAL_DISALLOW_DEFAULT_CTOR(Gfx9RsrcProcMgr); PAL_DISALLOW_COPY_AND_ASSIGN(Gfx9RsrcProcMgr); }; } // Gfx9 } // Pal
35.418868
120
0.573034
4e2d9270ddaf2febb18c5654cb22a198d93f5bf8
3,051
h
C
src/musikcube/cursespp/cursespp/INavigationKeys.h
0mp/musikcube
ceed5a1c73b43783e13f6351d73d0f84e666094b
[ "BSD-3-Clause" ]
1
2020-07-17T01:36:05.000Z
2020-07-17T01:36:05.000Z
src/musikcube/cursespp/cursespp/INavigationKeys.h
0mp/musikcube
ceed5a1c73b43783e13f6351d73d0f84e666094b
[ "BSD-3-Clause" ]
null
null
null
src/musikcube/cursespp/cursespp/INavigationKeys.h
0mp/musikcube
ceed5a1c73b43783e13f6351d73d0f84e666094b
[ "BSD-3-Clause" ]
4
2020-05-22T00:29:07.000Z
2020-06-17T15:22:08.000Z
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <string> namespace cursespp { class INavigationKeys { public: virtual ~INavigationKeys() { } virtual bool Up(const std::string& key) = 0; virtual bool Down(const std::string& key) = 0; virtual bool Left(const std::string& key) = 0; virtual bool Right(const std::string& key) = 0; virtual bool Next(const std::string& key) = 0; virtual bool PageUp(const std::string& key) = 0; virtual bool PageDown(const std::string& key) = 0; virtual bool Home(const std::string& key) = 0; virtual bool End(const std::string& key) = 0; virtual bool Prev(const std::string& key) = 0; virtual bool Mode(const std::string& key) = 0; virtual std::string Up() = 0; virtual std::string Down() = 0; virtual std::string Left() = 0; virtual std::string Right() = 0; virtual std::string Next() = 0; virtual std::string PageUp() = 0; virtual std::string PageDown() = 0; virtual std::string Home() = 0; virtual std::string End() = 0; virtual std::string Prev() = 0; virtual std::string Mode() = 0; }; }
44.217391
78
0.621763
aebb41b1c60fc906f6343b51ba96f95b33916a84
1,267
c
C
Labs/pthreadlab/main-deadlock-global.c
gustycooper/cpsc405
f1479c2bc24f3c07972bbf34b6c26249d823e199
[ "CC0-1.0" ]
null
null
null
Labs/pthreadlab/main-deadlock-global.c
gustycooper/cpsc405
f1479c2bc24f3c07972bbf34b6c26249d823e199
[ "CC0-1.0" ]
null
null
null
Labs/pthreadlab/main-deadlock-global.c
gustycooper/cpsc405
f1479c2bc24f3c07972bbf34b6c26249d823e199
[ "CC0-1.0" ]
4
2022-01-13T13:23:43.000Z
2022-01-15T23:40:29.000Z
#include <stdio.h> #include "mythreads.h" pthread_mutex_t g = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; void* worker(void* arg) { Pthread_mutex_lock(&g); printf("worker%ld has mutex g.\n", (long)arg); if ((long) arg == 0) { Pthread_mutex_lock(&m1); printf("worker%ld has mutex m1.\n", (long)arg); sched_yield(); Pthread_mutex_lock(&m2); printf("worker%ld has mutex m2.\n", (long)arg); } else { Pthread_mutex_lock(&m2); printf("worker%ld has mutex m2.\n", (long)arg); sched_yield(); Pthread_mutex_lock(&m1); printf("worker%ld has mutex m1.\n", (long)arg); } Pthread_mutex_unlock(&m1); printf("worker%ld released mutex m1.\n", (long)arg); Pthread_mutex_unlock(&m2); printf("worker%ld released mutex m2.\n", (long)arg); Pthread_mutex_unlock(&g); printf("worker%ld released mutex g.\n", (long)arg); return NULL; } int main(int argc, char *argv[]) { pthread_t p1, p2; Pthread_create(&p1, NULL, worker, (void *) (long) 0); Pthread_create(&p2, NULL, worker, (void *) (long) 1); Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("All done!\n"); return 0; }
29.465116
57
0.641673
aec0bd064b4112fa08a4ee03b4278c074cfba16f
283
h
C
XMGBaseUICommonet/Classes/UIImage+extend.h
maweefeng/XMGBaseUICommonet
8ce9cfc59f5c41e49922e2b654cc223c41aaab60
[ "Apache-2.0" ]
null
null
null
XMGBaseUICommonet/Classes/UIImage+extend.h
maweefeng/XMGBaseUICommonet
8ce9cfc59f5c41e49922e2b654cc223c41aaab60
[ "Apache-2.0" ]
null
null
null
XMGBaseUICommonet/Classes/UIImage+extend.h
maweefeng/XMGBaseUICommonet
8ce9cfc59f5c41e49922e2b654cc223c41aaab60
[ "Apache-2.0" ]
null
null
null
// // UIImage+extend.h // Sport // // Created by 小马科技 on 2020/12/2. // Copyright © 2020 iband. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UIImage (extend) - (UIImage *)drawRectWithRoundedCorner:(CGSize)size; @end NS_ASSUME_NONNULL_END
15.722222
52
0.720848
aeeaf14b8e038edad63128518c4976ca7354d2ea
1,581
h
C
open_lin_types.h
open-LIN/open-LIN-c
ae816c694e18650a779696b72aaa4bd4f797b90c
[ "MIT" ]
23
2018-03-19T09:30:52.000Z
2022-01-27T09:07:15.000Z
open_lin_types.h
open-LIN/open-LIN-c
ae816c694e18650a779696b72aaa4bd4f797b90c
[ "MIT" ]
2
2019-08-05T10:12:22.000Z
2021-07-15T21:03:11.000Z
open_lin_types.h
open-LIN/open-LIN-c
ae816c694e18650a779696b72aaa4bd4f797b90c
[ "MIT" ]
13
2018-10-23T01:53:36.000Z
2021-11-24T02:28:00.000Z
/** * @file open_lin_types.h * @brief LIN slave data layer implementation */ #ifndef OPEN_LIN_OPEN_LIN_TYPES_H_ #define OPEN_LIN_OPEN_LIN_TYPES_H_ #include "open_lin_cfg.h" #include <string.h> #include <stdbool.h> #define OPEN_LIN_MAX_FRAME_LEN 8u #define OPEN_LIN_MAX_FRAME_CHECK_SUM_SIZE 1u typedef bool l_bool; typedef uint8_t l_u8 ; typedef uint16_t l_u16; #define l_true true #define l_false false #define OPEN_LIN_MAX_FRAME_LENGTH 0x8u #define OPEN_LIN_SYNCH_BYTE 0x55u #define OPEN_LIN_GET_PID_BIT(x,y) (((x) >> (y)) & 0x01u) #define OPEN_LIN_ID_MASK 0x3Fu #define OPEN_LIN_P0_FLAG 6 #define OPEN_LIN_P1_FLAG 7 #define OPEN_LIN_DIAG_REQUEST 0x3C #define OPEN_LIN_DIAG_RESPONSE 0x3D #define open_lin_memcpy memcpy typedef l_u8 open_lin_pid_t; typedef l_u8 open_lin_checksum_t; typedef enum { OPEN_LIN_FRAME_TYPE_TRANSMIT, OPEN_LIN_FRAME_TYPE_RECEIVE } open_lin_frame_type_t; typedef enum { OPEN_LIN_NO_ERROR, OPEN_LIN_SLAVE_ERROR_INVALID_DATA_RX, OPEN_LIN_SLAVE_ERROR_INVALID_CHECKSUM, OPEN_LIN_SLAVE_ERROR_PID_PARITY, OPEN_LIN_SLAVE_ERROR_INVALID_SYNCH, OPEN_LIN_SLAVE_ERROR_INVALID_BREAK, OPEN_LIN_SLAVE_ERROR_ID_NOT_FOUND, OPEN_LIN_SLAVE_ERROR_HW_TX, OPEN_LIN_MASTER_ERROR_CHECKSUM, OPEN_LIN_MASTER_ERROR_HEADER_TX, OPEN_LIN_MASTER_ERROR_DATA_TX, OPEN_LIN_MASTER_ERROR_DATA_RX, OPEN_LIN_MASTER_ERROR_DATA_RX_TIMEOUT } t_open_lin_error; /** * @brief error handler function */ void open_lin_error_handler(t_open_lin_error error_code); #endif /* OPEN_LIN_OPEN_LIN_TYPES_H_ */
23.954545
58
0.804554
39fb4e8dd99f60d26565d25ed9977c16ad04ed53
3,178
c
C
Program/QCopterFC_FlightControl/Program_Algorithm/algorithm_moveAve.c
pcedison/QCopterFlightControl
658c0d67b66acc8317f0024a68cbd70e09ef7948
[ "MIT" ]
null
null
null
Program/QCopterFC_FlightControl/Program_Algorithm/algorithm_moveAve.c
pcedison/QCopterFlightControl
658c0d67b66acc8317f0024a68cbd70e09ef7948
[ "MIT" ]
null
null
null
Program/QCopterFC_FlightControl/Program_Algorithm/algorithm_moveAve.c
pcedison/QCopterFlightControl
658c0d67b66acc8317f0024a68cbd70e09ef7948
[ "MIT" ]
1
2019-09-09T09:27:23.000Z
2019-09-09T09:27:23.000Z
/*=====================================================================================================*/ /*=====================================================================================================*/ #include "stm32f4_system.h" #include "algorithm_moveAve.h" /*=====================================================================================================*/ /*=====================================================================================================* **函數 : MoveAve_SMA **功能 : Simple Moving Average **輸入 : NewData, MoveAve_FIFO, SampleNum **輸出 : AveData **使用 : MoveAve_SMA(NewData, MoveAve_FIFO, SampleNum) **=====================================================================================================*/ /*=====================================================================================================*/ s16 MoveAve_SMA( s16 NewData, s16 *MoveAve_FIFO, u8 SampleNum ) { u8 i = 0; s16 AveData = 0; s32 MoveAve_Sum = 0; for(i=0; i<SampleNum-1; i++) // 陣列移動 MoveAve_FIFO[i] = MoveAve_FIFO[i+1]; MoveAve_FIFO[SampleNum-1] = NewData; // 加入新數據 for(i=0; i<SampleNum; i++) // 求和 MoveAve_Sum += MoveAve_FIFO[i]; AveData = (s16)(MoveAve_Sum/SampleNum); // 計算平均值 return AveData; } /*=====================================================================================================*/ /*=====================================================================================================* **函數 : MoveAve_WMA **功能 : Weighted Moving Average **輸入 : NewData, MoveAve_FIFO, SampleNum **輸出 : AveData **使用 : MoveAve_WMA(NewData, MoveAve_FIFO, SampleNum) **=====================================================================================================*/ /*=====================================================================================================*/ s16 MoveAve_WMA( s16 NewData, s16 *MoveAve_FIFO, u8 SampleNum ) { u8 i = 0; s16 AveData = 0; u16 SampleSum = 0; s32 MoveAve_Sum = 0; for(i=0; i<SampleNum-1; i++) // 陣列移動 MoveAve_FIFO[i] = MoveAve_FIFO[i+1]; MoveAve_FIFO[SampleNum-1] = NewData; // 加入新數據 for(i=0; i<SampleNum; i++) // 求和 & 加權 MoveAve_Sum += MoveAve_FIFO[i]*(i+1); SampleSum = (SampleNum*(SampleNum+1))/2; // 計算加權除數 AveData = (s16)(MoveAve_Sum/SampleSum); // 計算平均值 return AveData; } /*=====================================================================================================*/ /*=====================================================================================================* **函數 : MoveAve_EMA **功能 : Exponential Moving Average **輸入 : NewData, MoveAve_FIFO, SampleNum **輸出 : AveData **使用 : MoveAve_EMA(NewData, MoveAve_FIFO, SampleNum) **=====================================================================================================*/ /*=====================================================================================================*/ /*=====================================================================================================*/ /*=====================================================================================================*/
47.432836
105
0.299559
d3e68401e96681319f0a07cd86d0b3749d10b9b4
1,507
h
C
BG-Tourist-Guide/Common/TMAlertControllerFactory.h
TsvetanMilanov/BG-Tourist-Guide
e9ebeb7c80e227afa76b350c5e9368a8558cc865
[ "MIT" ]
null
null
null
BG-Tourist-Guide/Common/TMAlertControllerFactory.h
TsvetanMilanov/BG-Tourist-Guide
e9ebeb7c80e227afa76b350c5e9368a8558cc865
[ "MIT" ]
null
null
null
BG-Tourist-Guide/Common/TMAlertControllerFactory.h
TsvetanMilanov/BG-Tourist-Guide
e9ebeb7c80e227afa76b350c5e9368a8558cc865
[ "MIT" ]
null
null
null
// // AlertControllerFactory.h // BG-Tourist-Guide // // Created by Hakintosh on 1/30/16. // Copyright © 2016 Hakintosh. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "TMProgressAlertDialog.h" @interface TMAlertControllerFactory : NSObject +(UIAlertController* _Nonnull) alertControllerWithTitle: (NSString* _Nullable) title message: (NSString* _Nullable) message andHandler: (void (^ __nullable)(UIAlertAction* _Nonnull action))handler; +(void) showAlertDialogWithTitle: (NSString* _Nullable) title message: (NSString* _Nullable) message uiViewController: (UIViewController* _Nonnull) controller andHandler: (void (^ __nullable)(UIAlertAction* _Nonnull action))handler; +(void) showCancelableAlertDialogWithTitle: (NSString* _Nullable) title message: (NSString* _Nullable) message uiViewController: (UIViewController* _Nonnull) controller andHandler: (void (^ __nullable)(UIAlertAction* _Nonnull action))handler; +(void) showTextInputDialogWithTitle: (NSString* _Nonnull) title controller: (UIViewController* _Nonnull) controller andHandler: (void (^ __nullable)(NSString* _Nonnull textField))handler; +(TMProgressAlertDialog* _Nonnull) progressAlertDialogWithTitle: (NSString* _Nullable) title; @end
43.057143
109
0.661579
236b89704ddd4b3ad974d89e96269f4731ace33c
1,299
h
C
usr/libexec/nanoregistryd/EPCharacteristicWriterWriteEntry.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
usr/libexec/nanoregistryd/EPCharacteristicWriterWriteEntry.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
usr/libexec/nanoregistryd/EPCharacteristicWriterWriteEntry.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> @class EPCharacteristicWriter, NSData; @protocol OS_dispatch_source; @interface EPCharacteristicWriterWriteEntry : NSObject { _Bool _written; // 8 = 0x8 NSData *_data; // 16 = 0x10 CDUnknownBlockType _begin; // 24 = 0x18 CDUnknownBlockType _completion; // 32 = 0x20 NSObject<OS_dispatch_source> *_timer; // 40 = 0x28 EPCharacteristicWriter *_writer; // 48 = 0x30 double _timeout; // 56 = 0x38 } - (void).cxx_destruct; // IMP=0x00000001000d39ec @property(nonatomic) double timeout; // @synthesize timeout=_timeout; @property(retain, nonatomic) EPCharacteristicWriter *writer; // @synthesize writer=_writer; @property(nonatomic) _Bool written; // @synthesize written=_written; @property(retain, nonatomic) NSObject<OS_dispatch_source> *timer; // @synthesize timer=_timer; @property(copy, nonatomic) CDUnknownBlockType completion; // @synthesize completion=_completion; @property(copy, nonatomic) CDUnknownBlockType begin; // @synthesize begin=_begin; @property(retain, nonatomic) NSData *data; // @synthesize data=_data; - (void)dealloc; // IMP=0x00000001000d3910 @end
37.114286
120
0.74057
2ffff1ccd27f8c35984bdf9b391a97b83312ff4e
24,736
c
C
DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/ArmPciConfigSpaceParser.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
3,012
2015-01-01T19:58:18.000Z
2022-03-31T22:07:14.000Z
DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/ArmPciConfigSpaceParser.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
1,199
2015-01-12T08:00:01.000Z
2022-03-29T18:14:42.000Z
DynamicTablesPkg/Library/FdtHwInfoParserLib/Pci/ArmPciConfigSpaceParser.c
mefff/edk2
0a4019ec9de64c6565ea545dc8d847afe2b30d6c
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
1,850
2015-01-01T11:28:12.000Z
2022-03-31T18:10:59.000Z
/** @file Arm PCI Configuration Space Parser. Copyright (c) 2021, ARM Limited. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): - linux/Documentation/devicetree/bindings/pci/host-generic-pci.yaml - PCI Firmware Specification - Revision 3.0 - Open Firmware Recommended Practice: Interrupt Mapping, Version 0.9 - Devicetree Specification Release v0.3 - linux kernel code **/ #include "CmObjectDescUtility.h" #include <Library/DebugLib.h> #include "FdtHwInfoParser.h" #include "Pci/ArmPciConfigSpaceParser.h" #include "Gic/ArmGicDispatcher.h" /** List of "compatible" property values for host PCIe bridges nodes. Any other "compatible" value is not supported by this module. */ STATIC CONST COMPATIBILITY_STR PciCompatibleStr[] = { { "pci-host-ecam-generic" } }; /** COMPATIBILITY_INFO structure for the PCIe. */ STATIC CONST COMPATIBILITY_INFO PciCompatibleInfo = { ARRAY_SIZE (PciCompatibleStr), PciCompatibleStr }; /** Get the Segment group (also called: Domain Id) of a host-pci node. kernel/Documentation/devicetree/bindings/pci/pci.txt: "It is required to either not set this property at all or set it for all host bridges in the system" The function checks the "linux,pci-domain" property of the host-pci node. Either all host-pci nodes must have this property, or none of them. If the property is available, read it. Otherwise dynamically assign the Ids. @param [in] Fdt Pointer to a Flattened Device Tree (Fdt). @param [in] HostPciNode Offset of a host-pci node. @param [out] SegGroup Segment group assigned to the host-pci controller. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. **/ STATIC EFI_STATUS EFIAPI GetPciSegGroup ( IN CONST VOID *Fdt, IN INT32 HostPciNode, OUT INT32 *SegGroup ) { CONST UINT8 *Data; INT32 DataSize; STATIC INT32 LocalSegGroup = 0; if ((Fdt == NULL) || (SegGroup == NULL)) { ASSERT (0); return EFI_INVALID_PARAMETER; } Data = fdt_getprop (Fdt, HostPciNode, "linux,pci-domain", &DataSize); if ((Data == NULL) || (DataSize < 0)) { // Did not find property, assign the DomainIds ourselves. if (LocalSegGroup < 0) { // "linux,pci-domain" property was defined for another node. ASSERT (0); return EFI_ABORTED; } *SegGroup = LocalSegGroup++; return EFI_SUCCESS; } if ((DataSize > sizeof (UINT32)) || (LocalSegGroup > 0)) { // Property on more than 1 cell or // "linux,pci-domain" property was not defined for a node. ASSERT (0); return EFI_ABORTED; } // If one node has the "linux,pci-domain" property, then all the host-pci // nodes must have it. LocalSegGroup = -1; *SegGroup = fdt32_to_cpu (*(UINT32 *)Data); return EFI_SUCCESS; } /** Parse the bus-range controlled by this host-pci node. @param [in] Fdt Pointer to a Flattened Device Tree (Fdt). @param [in] HostPciNode Offset of a host-pci node. @param [in, out] PciInfo PCI_PARSER_TABLE structure storing information about the current host-pci. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. **/ STATIC EFI_STATUS EFIAPI PopulateBusRange ( IN CONST VOID *Fdt, IN INT32 HostPciNode, IN OUT PCI_PARSER_TABLE *PciInfo ) { CONST UINT8 *Data; INT32 DataSize; UINT32 StartBus; UINT32 EndBus; if ((Fdt == NULL) || (PciInfo == NULL)) { ASSERT (0); return EFI_INVALID_PARAMETER; } Data = fdt_getprop (Fdt, HostPciNode, "bus-range", &DataSize); if ((Data == NULL) || (DataSize < 0)) { // No evidence this property is mandatory. Use default values. StartBus = 0; EndBus = 255; } else if (DataSize == (2 * sizeof (UINT32))) { // If available, the property is on two integers. StartBus = fdt32_to_cpu (((UINT32 *)Data)[0]); EndBus = fdt32_to_cpu (((UINT32 *)Data)[1]); } else { ASSERT (0); return EFI_ABORTED; } PciInfo->PciConfigSpaceInfo.StartBusNumber = StartBus; PciInfo->PciConfigSpaceInfo.EndBusNumber = EndBus; return EFI_SUCCESS; } /** Parse the PCI address map. The PCI address map is available in the "ranges" device-tree property. @param [in] Fdt Pointer to a Flattened Device Tree (Fdt). @param [in] HostPciNode Offset of a host-pci node. @param [in] AddressCells # of cells used to encode an address on the parent bus. @param [in, out] PciInfo PCI_PARSER_TABLE structure storing information about the current host-pci. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. @retval EFI_OUT_OF_RESOURCES An allocation has failed. **/ STATIC EFI_STATUS EFIAPI ParseAddressMap ( IN CONST VOID *Fdt, IN INT32 HostPciNode, IN INT32 AddressCells, IN OUT PCI_PARSER_TABLE *PciInfo ) { CONST UINT8 *Data; INT32 DataSize; UINT32 Index; UINT32 Offset; UINT32 AddressMapSize; UINT32 Count; UINT32 PciAddressAttr; CM_ARM_PCI_ADDRESS_MAP_INFO *PciAddressMapInfo; UINT32 BufferSize; // The mapping is done on AddressMapSize bytes. AddressMapSize = (PCI_ADDRESS_CELLS + AddressCells + PCI_SIZE_CELLS) * sizeof (UINT32); Data = fdt_getprop (Fdt, HostPciNode, "ranges", &DataSize); if ((Data == NULL) || (DataSize < 0) || ((DataSize % AddressMapSize) != 0)) { // If error or not on AddressMapSize bytes. ASSERT (0); return EFI_ABORTED; } Count = DataSize / AddressMapSize; // Allocate a buffer to store each address mapping. BufferSize = Count * sizeof (CM_ARM_PCI_ADDRESS_MAP_INFO); PciAddressMapInfo = AllocateZeroPool (BufferSize); if (PciAddressMapInfo == NULL) { ASSERT (0); return EFI_OUT_OF_RESOURCES; } for (Index = 0; Index < Count; Index++) { Offset = Index * AddressMapSize; // Pci address attributes PciAddressAttr = fdt32_to_cpu (*(UINT32 *)&Data[Offset]); PciAddressMapInfo[Index].SpaceCode = READ_PCI_SS (PciAddressAttr); Offset += sizeof (UINT32); // Pci address PciAddressMapInfo[Index].PciAddress = fdt64_to_cpu (*(UINT64 *)&Data[Offset]); Offset += (PCI_ADDRESS_CELLS - 1) * sizeof (UINT32); // Cpu address if (AddressCells == 2) { PciAddressMapInfo[Index].CpuAddress = fdt64_to_cpu (*(UINT64 *)&Data[Offset]); } else { PciAddressMapInfo[Index].CpuAddress = fdt32_to_cpu (*(UINT32 *)&Data[Offset]); } Offset += AddressCells * sizeof (UINT32); // Address size PciAddressMapInfo[Index].AddressSize = fdt64_to_cpu (*(UINT64 *)&Data[Offset]); Offset += PCI_SIZE_CELLS * sizeof (UINT32); } // for PciInfo->Mapping[PciMappingTableAddress].ObjectId = CREATE_CM_ARM_OBJECT_ID (EArmObjPciAddressMapInfo); PciInfo->Mapping[PciMappingTableAddress].Size = sizeof (CM_ARM_PCI_ADDRESS_MAP_INFO) * Count; PciInfo->Mapping[PciMappingTableAddress].Data = PciAddressMapInfo; PciInfo->Mapping[PciMappingTableAddress].Count = Count; return EFI_SUCCESS; } /** Parse the PCI interrupt map. The PCI interrupt map is available in the "interrupt-map" and "interrupt-map-mask" device-tree properties. Cf Devicetree Specification Release v0.3, s2.4.3 Interrupt Nexus Properties An interrupt-map must be as: interrupt-map = < [child unit address] [child interrupt specifier] [interrupt-parent] [parent unit address] [parent interrupt specifier] > @param [in] Fdt Pointer to a Flattened Device Tree (Fdt). @param [in] HostPciNode Offset of a host-pci node. @param [in, out] PciInfo PCI_PARSER_TABLE structure storing information about the current host-pci. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. @retval EFI_NOT_FOUND Not found. @retval EFI_OUT_OF_RESOURCES An allocation has failed. **/ STATIC EFI_STATUS EFIAPI ParseIrqMap ( IN CONST VOID *Fdt, IN INT32 HostPciNode, IN OUT PCI_PARSER_TABLE *PciInfo ) { EFI_STATUS Status; CONST UINT8 *Data; INT32 DataSize; UINT32 Index; UINT32 Offset; INT32 IntcNode; INT32 IntcAddressCells; INT32 IntcCells; INT32 PciIntCells; INT32 IntcPhandle; INT32 IrqMapSize; UINT32 IrqMapCount; CONST UINT8 *IrqMapMask; INT32 IrqMapMaskSize; INT32 PHandleOffset; UINT32 GicVersion; UINT32 PciAddressAttr; CM_ARM_PCI_INTERRUPT_MAP_INFO *PciInterruptMapInfo; UINT32 BufferSize; Data = fdt_getprop (Fdt, HostPciNode, "interrupt-map", &DataSize); if ((Data == NULL) || (DataSize <= 0)) { DEBUG (( DEBUG_WARN, "Fdt parser: No Legacy interrupts found for PCI configuration space at " "address: 0x%lx, group segment: %d\n", PciInfo->PciConfigSpaceInfo.BaseAddress, PciInfo->PciConfigSpaceInfo.PciSegmentGroupNumber )); return EFI_NOT_FOUND; } // PCI interrupts are expected to be on 1 cell. Check it. Status = FdtGetInterruptCellsInfo (Fdt, HostPciNode, &PciIntCells); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } if (PciIntCells != PCI_INTERRUPTS_CELLS) { ASSERT (0); return EFI_ABORTED; } IrqMapMask = fdt_getprop ( Fdt, HostPciNode, "interrupt-map-mask", &IrqMapMaskSize ); if ((IrqMapMask == NULL) || (IrqMapMaskSize != (PCI_ADDRESS_CELLS + PCI_INTERRUPTS_CELLS) * sizeof (UINT32))) { ASSERT (0); return EFI_ABORTED; } // Get the interrupt-controller of the first irq mapping. PHandleOffset = (PCI_ADDRESS_CELLS + PciIntCells) * sizeof (UINT32); if (PHandleOffset > DataSize) { ASSERT (0); return EFI_ABORTED; } IntcPhandle = fdt32_to_cpu (*(UINT32 *)&Data[PHandleOffset]); IntcNode = fdt_node_offset_by_phandle (Fdt, IntcPhandle); if (IntcNode < 0) { ASSERT (0); return EFI_ABORTED; } // Only support Gic(s) for now. Status = GetGicVersion (Fdt, IntcNode, &GicVersion); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // Get the "address-cells" property of the IntcNode. Status = FdtGetAddressInfo (Fdt, IntcNode, &IntcAddressCells, NULL); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // Get the "interrupt-cells" property of the IntcNode. Status = FdtGetInterruptCellsInfo (Fdt, IntcNode, &IntcCells); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // An irq mapping is done on IrqMapSize bytes // (which includes 1 cell for the PHandle). IrqMapSize = (PCI_ADDRESS_CELLS + PciIntCells + 1 + IntcAddressCells + IntcCells) * sizeof (UINT32); if ((DataSize % IrqMapSize) != 0) { // The mapping is not done on IrqMapSize bytes. ASSERT (0); return EFI_ABORTED; } IrqMapCount = DataSize / IrqMapSize; // We assume the same interrupt-controller is used for all the mappings. // Check this is correct. for (Index = 0; Index < IrqMapCount; Index++) { if (IntcPhandle != fdt32_to_cpu ( *(UINT32 *)&Data[(Index * IrqMapSize) + PHandleOffset] )) { ASSERT (0); return EFI_ABORTED; } } // Allocate a buffer to store each interrupt mapping. IrqMapCount = DataSize / IrqMapSize; BufferSize = IrqMapCount * sizeof (CM_ARM_PCI_ADDRESS_MAP_INFO); PciInterruptMapInfo = AllocateZeroPool (BufferSize); if (PciInterruptMapInfo == NULL) { ASSERT (0); return EFI_OUT_OF_RESOURCES; } for (Index = 0; Index < IrqMapCount; Index++) { Offset = Index * IrqMapSize; // Pci address attributes PciAddressAttr = fdt32_to_cpu ( (*(UINT32 *)&Data[Offset]) & (*(UINT32 *)&IrqMapMask[0]) ); PciInterruptMapInfo[Index].PciBus = READ_PCI_BBBBBBBB (PciAddressAttr); PciInterruptMapInfo[Index].PciDevice = READ_PCI_DDDDD (PciAddressAttr); Offset += PCI_ADDRESS_CELLS * sizeof (UINT32); // Pci irq PciInterruptMapInfo[Index].PciInterrupt = fdt32_to_cpu ( (*(UINT32 *)&Data[Offset]) & (*(UINT32 *)&IrqMapMask[3 * sizeof (UINT32)]) ); // -1 to translate from device-tree (INTA=1) to ACPI (INTA=0) irq IDs. PciInterruptMapInfo[Index].PciInterrupt -= 1; Offset += PCI_INTERRUPTS_CELLS * sizeof (UINT32); // PHandle (skip it) Offset += sizeof (UINT32); // "Parent unit address" (skip it) Offset += IntcAddressCells * sizeof (UINT32); // Interrupt controller interrupt and flags PciInterruptMapInfo[Index].IntcInterrupt.Interrupt = FdtGetInterruptId ((UINT32 *)&Data[Offset]); PciInterruptMapInfo[Index].IntcInterrupt.Flags = FdtGetInterruptFlags ((UINT32 *)&Data[Offset]); } // for PciInfo->Mapping[PciMappingTableInterrupt].ObjectId = CREATE_CM_ARM_OBJECT_ID (EArmObjPciInterruptMapInfo); PciInfo->Mapping[PciMappingTableInterrupt].Size = sizeof (CM_ARM_PCI_INTERRUPT_MAP_INFO) * IrqMapCount; PciInfo->Mapping[PciMappingTableInterrupt].Data = PciInterruptMapInfo; PciInfo->Mapping[PciMappingTableInterrupt].Count = IrqMapCount; return Status; } /** Parse a Host-pci node. @param [in] Fdt Pointer to a Flattened Device Tree (Fdt). @param [in] HostPciNode Offset of a host-pci node. @param [in, out] PciInfo The CM_ARM_PCI_CONFIG_SPACE_INFO to populate. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. @retval EFI_OUT_OF_RESOURCES An allocation has failed. **/ STATIC EFI_STATUS EFIAPI PciNodeParser ( IN CONST VOID *Fdt, IN INT32 HostPciNode, IN OUT PCI_PARSER_TABLE *PciInfo ) { EFI_STATUS Status; INT32 AddressCells; INT32 SizeCells; CONST UINT8 *Data; INT32 DataSize; INT32 SegGroup; if ((Fdt == NULL) || (PciInfo == NULL)) { ASSERT (0); return EFI_INVALID_PARAMETER; } // Segment Group / DomainId Status = GetPciSegGroup (Fdt, HostPciNode, &SegGroup); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } PciInfo->PciConfigSpaceInfo.PciSegmentGroupNumber = SegGroup; // Bus range Status = PopulateBusRange (Fdt, HostPciNode, PciInfo); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } Status = FdtGetParentAddressInfo ( Fdt, HostPciNode, &AddressCells, &SizeCells ); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // Only support 32/64 bits addresses. if ((AddressCells < 1) || (AddressCells > 2) || (SizeCells < 1) || (SizeCells > 2)) { ASSERT (0); return EFI_ABORTED; } Data = fdt_getprop (Fdt, HostPciNode, "reg", &DataSize); if ((Data == NULL) || (DataSize != ((AddressCells + SizeCells) * sizeof (UINT32)))) { // If error or wrong size. ASSERT (0); return EFI_ABORTED; } // Base address if (AddressCells == 2) { PciInfo->PciConfigSpaceInfo.BaseAddress = fdt64_to_cpu (*(UINT64 *)Data); } else { PciInfo->PciConfigSpaceInfo.BaseAddress = fdt32_to_cpu (*(UINT32 *)Data); } // Address map Status = ParseAddressMap ( Fdt, HostPciNode, AddressCells, PciInfo ); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // Irq map Status = ParseIrqMap ( Fdt, HostPciNode, PciInfo ); if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { ASSERT (0); } return EFI_SUCCESS; } /** Add the parsed Pci information to the Configuration Manager. CmObj of the following types are concerned: - EArmObjPciConfigSpaceInfo - EArmObjPciAddressMapInfo - EArmObjPciInterruptMapInfo @param [in] FdtParserHandle A handle to the parser instance. @param [in] PciTableInfo PCI_PARSER_TABLE structure containing the CmObjs to add. @retval EFI_SUCCESS The function completed successfully. @retval EFI_INVALID_PARAMETER Invalid parameter. @retval EFI_OUT_OF_RESOURCES An allocation has failed. **/ STATIC EFI_STATUS EFIAPI PciInfoAdd ( IN CONST FDT_HW_INFO_PARSER_HANDLE FdtParserHandle, IN PCI_PARSER_TABLE *PciTableInfo ) { EFI_STATUS Status; CM_ARM_PCI_CONFIG_SPACE_INFO *PciConfigSpaceInfo; if ((FdtParserHandle == NULL) || (PciTableInfo == NULL)) { ASSERT (0); return EFI_INVALID_PARAMETER; } PciConfigSpaceInfo = &PciTableInfo->PciConfigSpaceInfo; // Add the address map space CmObj to the Configuration Manager. Status = AddMultipleCmObjWithCmObjRef ( FdtParserHandle, &PciTableInfo->Mapping[PciMappingTableAddress], &PciConfigSpaceInfo->AddressMapToken ); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } // Add the interrupt map space CmObj to the Configuration Manager. // Possible to have no legacy interrupts, or no device described and // thus no interrupt-mapping. if (PciTableInfo->Mapping[PciMappingTableInterrupt].Count != 0) { Status = AddMultipleCmObjWithCmObjRef ( FdtParserHandle, &PciTableInfo->Mapping[PciMappingTableInterrupt], &PciConfigSpaceInfo->InterruptMapToken ); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } } // Add the configuration space CmObj to the Configuration Manager. Status = AddSingleCmObj ( FdtParserHandle, CREATE_CM_ARM_OBJECT_ID (EArmObjPciConfigSpaceInfo), &PciTableInfo->PciConfigSpaceInfo, sizeof (CM_ARM_PCI_CONFIG_SPACE_INFO), NULL ); ASSERT_EFI_ERROR (Status); return Status; } /** Free the CmObjDesc of the ParserTable. @param [in] PciTableInfo PCI_PARSER_TABLE structure containing the CmObjs to free. @retval EFI_SUCCESS The function completed successfully. @retval EFI_INVALID_PARAMETER Invalid parameter. **/ STATIC EFI_STATUS EFIAPI FreeParserTable ( IN PCI_PARSER_TABLE *PciTableInfo ) { UINT32 Index; VOID *Data; if (PciTableInfo == NULL) { ASSERT (0); return EFI_INVALID_PARAMETER; } for (Index = 0; Index < PciMappingTableMax; Index++) { Data = PciTableInfo->Mapping[Index].Data; if (Data != NULL) { FreePool (Data); } } return EFI_SUCCESS; } /** CM_ARM_PCI_CONFIG_SPACE_INFO parser function. The following structure is populated: typedef struct CmArmPciConfigSpaceInfo { UINT64 BaseAddress; // {Populated} UINT16 PciSegmentGroupNumber; // {Populated} UINT8 StartBusNumber; // {Populated} UINT8 EndBusNumber; // {Populated} } CM_ARM_PCI_CONFIG_SPACE_INFO; typedef struct CmArmPciAddressMapInfo { UINT8 SpaceCode; // {Populated} UINT64 PciAddress; // {Populated} UINT64 CpuAddress; // {Populated} UINT64 AddressSize; // {Populated} } CM_ARM_PCI_ADDRESS_MAP_INFO; typedef struct CmArmPciInterruptMapInfo { UINT8 PciBus; // {Populated} UINT8 PciDevice; // {Populated} UINT8 PciInterrupt; // {Populated} CM_ARM_GENERIC_INTERRUPT IntcInterrupt; // {Populated} } CM_ARM_PCI_INTERRUPT_MAP_INFO; A parser parses a Device Tree to populate a specific CmObj type. None, one or many CmObj can be created by the parser. The created CmObj are then handed to the parser's caller through the HW_INFO_ADD_OBJECT interface. This can also be a dispatcher. I.e. a function that not parsing a Device Tree but calling other parsers. @param [in] FdtParserHandle A handle to the parser instance. @param [in] FdtBranch When searching for DT node name, restrict the search to this Device Tree branch. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred. @retval EFI_INVALID_PARAMETER Invalid parameter. @retval EFI_NOT_FOUND Not found. @retval EFI_UNSUPPORTED Unsupported. **/ EFI_STATUS EFIAPI ArmPciConfigInfoParser ( IN CONST FDT_HW_INFO_PARSER_HANDLE FdtParserHandle, IN INT32 FdtBranch ) { EFI_STATUS Status; UINT32 Index; INT32 PciNode; UINT32 PciNodeCount; PCI_PARSER_TABLE PciTableInfo; VOID *Fdt; if (FdtParserHandle == NULL) { ASSERT (0); return EFI_INVALID_PARAMETER; } Fdt = FdtParserHandle->Fdt; // Only search host-pci devices. // PCI Firmware Specification Revision 3.0, s4.1.2. "MCFG Table Description": // "This table directly refers to PCI Segment Groups defined in the system // via the _SEG object in the ACPI name space for the applicable host bridge // device." Status = FdtCountCompatNodeInBranch ( Fdt, FdtBranch, &PciCompatibleInfo, &PciNodeCount ); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } if (PciNodeCount == 0) { return EFI_NOT_FOUND; } // Parse each host-pci node in the branch. PciNode = FdtBranch; for (Index = 0; Index < PciNodeCount; Index++) { ZeroMem (&PciTableInfo, sizeof (PCI_PARSER_TABLE)); Status = FdtGetNextCompatNodeInBranch ( Fdt, FdtBranch, &PciCompatibleInfo, &PciNode ); if (EFI_ERROR (Status)) { ASSERT (0); if (Status == EFI_NOT_FOUND) { // Should have found the node. Status = EFI_ABORTED; } return Status; } Status = PciNodeParser (Fdt, PciNode, &PciTableInfo); if (EFI_ERROR (Status)) { ASSERT (0); goto error_handler; } // Add Pci information to the Configuration Manager. Status = PciInfoAdd (FdtParserHandle, &PciTableInfo); if (EFI_ERROR (Status)) { ASSERT (0); goto error_handler; } Status = FreeParserTable (&PciTableInfo); if (EFI_ERROR (Status)) { ASSERT (0); return Status; } } // for return Status; error_handler: FreeParserTable (&PciTableInfo); return Status; }
30.388206
94
0.606121
e7f3c5291ca1685fdcb32b63d48518dd0e682006
1,213
h
C
BullCowGame/FBullCowGame.h
jiaxuanc/BullCowGame
b63b1ba8c9cec38e251bf0bcd663519532a2d515
[ "MIT" ]
null
null
null
BullCowGame/FBullCowGame.h
jiaxuanc/BullCowGame
b63b1ba8c9cec38e251bf0bcd663519532a2d515
[ "MIT" ]
null
null
null
BullCowGame/FBullCowGame.h
jiaxuanc/BullCowGame
b63b1ba8c9cec38e251bf0bcd663519532a2d515
[ "MIT" ]
null
null
null
/* The game logic (no view code or direct user interaction) The game is a simple guess the word game based on Mastermind */ #pragma once #include <string> // don't use namespace in header files since it's easy to lose track of // to make syntax Unreal friendly using FString = std::string; using int32 = int; // strongly-typed enum enum class EGuessStatus { Invalid_Status, OK, Not_Isogram, Wrong_Length, Not_Lowercase }; enum class EResetStatus { Invalid_Status, Set_Hidden_Word, Exit }; // all values intialized to 0 struct FBullCowCount { int32 Bulls = 0; int32 Cows = 0; }; struct FDiffLevel { // TODO initialize int32 WordLength = 0; // int32 MaxTries = 0; // int32 NumHints = 0; }; class FBullCowGame { public: FBullCowGame(); int32 GetMaxTries() const; int32 GetCurrentTry() const; int32 GetHiddenWordLength() const; bool IsGameWon() const; EGuessStatus CheckGuessValidity(FString) const; void Reset(FDiffLevel); FBullCowCount SubmitValidGuess(FString); private: // see constructor for initialization int32 MyCurrentTry; FString MyHiddenWord; bool bGameIsWon; FString GenerateHiddenWord(int32); bool IsIsogram(FString) const; bool IsLowercase(FString) const; };
17.57971
71
0.74526
0049be9c1b79d3be59b201e980595725a2163acb
3,199
h
C
Middlewares/Third_Party/PolarSSL/include/polarssl/padlock.h
ghsecuritylab/stm32f4xx
dc8088883a33fe68790070e1dce7a3ce68d21b2a
[ "MIT" ]
2
2021-02-04T22:54:52.000Z
2022-01-31T22:12:39.000Z
Middlewares/Third_Party/PolarSSL/include/polarssl/padlock.h
ghsecuritylab/stm32f4xx
dc8088883a33fe68790070e1dce7a3ce68d21b2a
[ "MIT" ]
null
null
null
Middlewares/Third_Party/PolarSSL/include/polarssl/padlock.h
ghsecuritylab/stm32f4xx
dc8088883a33fe68790070e1dce7a3ce68d21b2a
[ "MIT" ]
1
2020-03-08T01:27:36.000Z
2020-03-08T01:27:36.000Z
/** * \file padlock.h * * \brief VIA PadLock ACE for HW encryption/decryption supported by some processors * * Copyright (C) 2006-2010, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef POLARSSL_PADLOCK_H #define POLARSSL_PADLOCK_H #include "aes.h" #define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED -0x0030 /**< Input data should be aligned. */ #if defined(POLARSSL_HAVE_ASM) && defined(__GNUC__) && defined(__i386__) #ifndef POLARSSL_HAVE_X86 #define POLARSSL_HAVE_X86 #endif #ifdef _MSC_VER #include <basetsd.h> typedef INT32 int32_t; #else #include <inttypes.h> #endif #define PADLOCK_RNG 0x000C #define PADLOCK_ACE 0x00C0 #define PADLOCK_PHE 0x0C00 #define PADLOCK_PMM 0x3000 #define PADLOCK_ALIGN16(x) (uint32_t *) (16 + ((int32_t) x & ~15)) #ifdef __cplusplus extern "C" { #endif /** * \brief PadLock detection routine * * \param The feature to detect * * \return 1 if CPU has support for the feature, 0 otherwise */ int padlock_supports( int feature ); /** * \brief PadLock AES-ECB block en(de)cryption * * \param ctx AES context * \param mode AES_ENCRYPT or AES_DECRYPT * \param input 16-byte input block * \param output 16-byte output block * * \return 0 if success, 1 if operation failed */ int padlock_xcryptecb( aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16] ); /** * \brief PadLock AES-CBC buffer en(de)cryption * * \param ctx AES context * \param mode AES_ENCRYPT or AES_DECRYPT * \param length length of the input data * \param iv initialization vector (updated after use) * \param input buffer holding the input data * \param output buffer holding the output data * * \return 0 if success, 1 if operation failed */ int padlock_xcryptcbc( aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output ); #ifdef __cplusplus } #endif #endif /* HAVE_X86 */ #endif /* padlock.h */
29.348624
106
0.639575
534fe09cf251080de59d1cf8be6f5072f96b28c8
2,366
h
C
curveAndSurface/ui_curveAndSurface.h
lishaohsuai/sweepVolume
3a7c0e876868451bee6dffb194bfae3e53f75c6e
[ "MIT" ]
null
null
null
curveAndSurface/ui_curveAndSurface.h
lishaohsuai/sweepVolume
3a7c0e876868451bee6dffb194bfae3e53f75c6e
[ "MIT" ]
null
null
null
curveAndSurface/ui_curveAndSurface.h
lishaohsuai/sweepVolume
3a7c0e876868451bee6dffb194bfae3e53f75c6e
[ "MIT" ]
null
null
null
/******************************************************************************** ** Form generated from reading UI file 'curveAndSurface.ui' ** ** Created by: Qt User Interface Compiler version 5.9.7 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_CURVEANDSURFACE_H #define UI_CURVEANDSURFACE_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_curveAndSurfaceClass { public: QMenuBar *menuBar; QToolBar *mainToolBar; QWidget *centralWidget; QStatusBar *statusBar; void setupUi(QMainWindow *curveAndSurfaceClass) { if (curveAndSurfaceClass->objectName().isEmpty()) curveAndSurfaceClass->setObjectName(QStringLiteral("curveAndSurfaceClass")); curveAndSurfaceClass->resize(600, 400); menuBar = new QMenuBar(curveAndSurfaceClass); menuBar->setObjectName(QStringLiteral("menuBar")); curveAndSurfaceClass->setMenuBar(menuBar); mainToolBar = new QToolBar(curveAndSurfaceClass); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); curveAndSurfaceClass->addToolBar(mainToolBar); centralWidget = new QWidget(curveAndSurfaceClass); centralWidget->setObjectName(QStringLiteral("centralWidget")); curveAndSurfaceClass->setCentralWidget(centralWidget); statusBar = new QStatusBar(curveAndSurfaceClass); statusBar->setObjectName(QStringLiteral("statusBar")); curveAndSurfaceClass->setStatusBar(statusBar); retranslateUi(curveAndSurfaceClass); QMetaObject::connectSlotsByName(curveAndSurfaceClass); } // setupUi void retranslateUi(QMainWindow *curveAndSurfaceClass) { curveAndSurfaceClass->setWindowTitle(QApplication::translate("curveAndSurfaceClass", "curveAndSurface", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class curveAndSurfaceClass: public Ui_curveAndSurfaceClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_CURVEANDSURFACE_H
33.8
124
0.695689
53758eac2ef8b9620dc2e05b85436da6273f0843
5,923
c
C
src/connection.c
lylhw13/tcp-server
5d01019737bc3aa228877713c4cea5c276545caf
[ "MIT" ]
null
null
null
src/connection.c
lylhw13/tcp-server
5d01019737bc3aa228877713c4cea5c276545caf
[ "MIT" ]
null
null
null
src/connection.c
lylhw13/tcp-server
5d01019737bc3aa228877713c4cea5c276545caf
[ "MIT" ]
null
null
null
#include "generic.h" #include "tree.h" #include <sys/time.h> #include <string.h> /* * read * read complete * write * write complete */ static tcp_session_t * create_session(int fd, int epfd, server_t *serv) { tcp_session_t* session = (tcp_session_t*)calloc(1, sizeof(tcp_session_t)); session->fd = fd; session->epfd = epfd; session->server = serv; if (serv->add_info_size != 0) { session->add_info_size = serv->add_info_size; session->additional_info = calloc(1, session->add_info_size); memcpy(session->additional_info, serv->additional_info, serv->add_info_size); } return session; } static void free_session(tcp_session_t *session) { LOGD("%s\n", __FUNCTION__); if (session->additional_info) free(session->additional_info); free(session); } static void remove_session(struct event_tree *head, tcp_session_t *session) { close(session->fd); timeout_remove(head, session); epoll_ctl(session->epfd, EPOLL_CTL_DEL, session->fd, NULL); free_session(session); } static int read_cb(tcp_session_t *session) { int nread; int fd = session->fd; char *buf = session->read_buf; errno = 0; nread = read(fd, buf + session->read_pos, BUFSIZE - session->read_pos); if (nread < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) return nread; error("read in read_cb"); } if (nread == 0) return nread; session->read_pos += nread; return nread; } static int write_cb(tcp_session_t* session) { int nwrite; int length; int fd = session->fd; if (session->write_buf == NULL) return 0; length = session->write_size - session->write_pos; if (length == 0) return 0; errno = 0; nwrite = write(fd, session->write_buf + session->write_pos, length); if (nwrite < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) return 0; error("write in write_cb\n"); } session->write_pos += nwrite; return nwrite; } static void add_new_session(int epfd, channel_t *channel_ptr, struct event_tree *head) { int err; connection_t *conn_ptr; struct epoll_event ev; err = pthread_mutex_trylock(&(channel_ptr->lock)); LOGD("lock in thread\n"); LOGD("address %p, len %d\n", channel_ptr, channel_ptr->len); if (err == EBUSY) return; if (err != 0) error("try lock in thread"); if (channel_ptr->len == 0) { pthread_mutex_unlock(&(channel_ptr->lock)); return; } conn_ptr = channel_ptr->head; channel_ptr->head = conn_ptr->next; channel_ptr->len --; LOGD("loop get fd %d\n", conn_ptr->fd); pthread_mutex_unlock(&(channel_ptr->lock)); tcp_session_t* session_new = create_session(conn_ptr->fd, epfd, channel_ptr->serv); ev.data.ptr = session_new; ev.events = EPOLLIN | EPOLLOUT; if (epoll_ctl(epfd, EPOLL_CTL_ADD, session_new->fd, &ev) != 0) error("add fd to epoll in thread"); timeout_set(head, session_new); timeout_insert(head, session_new); free(conn_ptr); } /* infinite loop */ void connect_cb(void *argus) { channel_t *channel_ptr = (channel_t *)argus; int i, res; int epfd, nr_events; int nread, nwrite,read_write_state = 0; tcp_session_t *session; server_t *serv; on_read_complete_fun parse_message_cb; on_write_complete_fun write_message_cb; struct event_tree head; RB_INIT(&head); serv = channel_ptr->serv; epfd = epoll_create1(0); if (epfd < 0) error("epoll_create1"); struct epoll_event *events; events = (struct epoll_event *)xmalloc(sizeof(struct epoll_event) * MAX_EVENTS); while (1) { nr_events = epoll_wait(epfd, events, MAX_EVENTS, 0); if (nr_events < 0) { free(events); error("epoll_wait"); } for (i = 0; i < nr_events; ++i) { read_write_state = 0; session = (tcp_session_t*)events[i].data.ptr; if (events[i].events & EPOLLIN) { /* normal read */ if ((nread = read_cb(events[i].data.ptr)) == 0) { remove_session(&head, session); continue; } if (nread > 0) read_write_state = 1; /* read_message_cb */ parse_message_cb = serv->read_complete_cb; if (parse_message_cb != NULL) { res = parse_message_cb(session); switch(res) { case RCB_AGAIN: if (session->read_pos < BUFSIZE) break; LOGD("TOO LONG MESSAGE\n"); /* fall through */ case RCB_ERROR: remove_session(&head, session); continue; default: break; } } } if (events[i].events & EPOLLOUT) { /* normal write */ nwrite = write_cb(session); write_message_cb = serv->write_complete_cb; if (write_message_cb != NULL) { res = write_message_cb(session); if (res == WCB_ERROR) { remove_session(&head, session); continue; } } if (nwrite > 0) read_write_state = 1; } if (read_write_state) timeout_update(&head, session); } /* end for */ timeout_process(&head, remove_session); if (channel_ptr->len > 0) add_new_session(epfd, channel_ptr, &head); } /* end while */ }
27.67757
87
0.546514
185efbb615cc1d64da1225ed533c58e52b8353df
6,595
c
C
sdk/modules/bluetooth/hal/bcm20706/bcm20706_bt_hfp.c
ShinjiShinozaki/spresense-1
fdbe88b8f63c247c57b2f5c2c54cf4664f9bb645
[ "Apache-2.0" ]
null
null
null
sdk/modules/bluetooth/hal/bcm20706/bcm20706_bt_hfp.c
ShinjiShinozaki/spresense-1
fdbe88b8f63c247c57b2f5c2c54cf4664f9bb645
[ "Apache-2.0" ]
null
null
null
sdk/modules/bluetooth/hal/bcm20706/bcm20706_bt_hfp.c
ShinjiShinozaki/spresense-1
fdbe88b8f63c247c57b2f5c2c54cf4664f9bb645
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * modules/bluetooth/hal/bcm20706/bcm20706_bt_hfp.c * * Copyright 2018 Sony Semiconductor Solutions Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Sony Semiconductor Solutions Corporation nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include "bt_util.h" #include <bt/bt_hfp_hf.h> #include "manager/bt_uart_manager.h" /**************************************************************************** * Private Functions ****************************************************************************/ static int btHfConnect(BT_ADDR *addr) { uint8_t buff[BT_SHORT_COMMAND_LEN] = {0}; uint8_t *p = buff; UINT8_TO_STREAM(p, PACKET_CONTROL); UINT16_TO_STREAM(p, BT_CONTROL_HF_COMMAND_CONNECT); UINT16_TO_STREAM(p, BT_ADDR_LEN); memcpy(p, addr, BT_ADDR_LEN); p += BT_ADDR_LEN; return btUartSendData(buff, p-buff); } static int btHfDisconnect(uint16_t handle) { uint8_t buff[BT_SHORT_COMMAND_LEN] = {0}; uint8_t *p = buff; UINT8_TO_STREAM(p, PACKET_CONTROL); UINT16_TO_STREAM(p, BT_CONTROL_HF_COMMAND_DISCONNECT); UINT16_TO_STREAM(p, sizeof(uint16_t)); UINT16_TO_STREAM(p, handle); return btUartSendData(buff, p-buff); } static int btHfConnectAudio(uint16_t handle) { uint8_t buff[BT_SHORT_COMMAND_LEN] = {0}; uint8_t *p = buff; UINT8_TO_STREAM(p, PACKET_CONTROL); UINT16_TO_STREAM(p, BT_CONTROL_HF_COMMAND_OPEN_AUDIO); UINT16_TO_STREAM(p, sizeof(uint16_t)); UINT16_TO_STREAM(p, handle); return btUartSendData(buff, p-buff); } static int btHfDisconnectAudio(uint16_t handle) { uint8_t buff[BT_SHORT_COMMAND_LEN] = {0}; uint8_t *p = buff; UINT8_TO_STREAM(p, PACKET_CONTROL); UINT16_TO_STREAM(p, BT_CONTROL_HF_COMMAND_CLOSE_AUDIO); UINT16_TO_STREAM(p, sizeof(uint16_t)); UINT16_TO_STREAM(p, handle); return btUartSendData(buff, p-buff); } static int btHfSetSupportedFeature(uint32_t *btHfFeature) { uint8_t buff[BT_SHORT_COMMAND_LEN] = {0}; uint8_t *p = buff; UINT8_TO_STREAM(p, PACKET_CONTROL); UINT16_TO_STREAM(p, BT_CONTROL_HF_COMMAND_SET_FEATURE); UINT16_TO_STREAM(p, sizeof(uint32_t)); UINT32_TO_STREAM(p, *btHfFeature); btUartSendData(buff, p - buff); return 0; } /**************************************************************************** * Name: bcm20706_bt_hfp_connect * * Description: * Bluetooth HFP connect/disconnect. * Connect/Disconnect HFP with target device address. * ****************************************************************************/ static int bcm20706_bt_hfp_connect(BT_ADDR *addr, uint16_t handle, bool connect) { int ret = BT_SUCCESS; if (connect) { /* Connect */ ret = btHfConnect(addr); } else { /* Disconnect */ ret = btHfDisconnect(handle); } return ret; } /**************************************************************************** * Name: bcm20706_bt_hfp_audio_connect * * Description: * Bluetooth HFP audio connect/disconnect. * Connect/Disconnect HFP audio (This function must call after * bcm20706_bt_hfp_connect). * ****************************************************************************/ static int bcm20706_bt_hfp_audio_connect(BT_ADDR *addr, uint16_t handle, bool connect) { int ret = BT_SUCCESS; if (connect) { /* Connect */ ret = btHfConnectAudio(handle); } else { /* Disconnect */ ret = btHfDisconnectAudio(handle); } return ret; } /**************************************************************************** * Name: bcm20706_bt_hfp_hf_feature * * Description: * Bluetooth HFP set HF feature. * Set hf feature by support flag. * ****************************************************************************/ static int bcm20706_bt_hfp_hf_feature(BT_HFP_HF_FEATURE_FLAG hf_heature) { int ret = BT_SUCCESS; uint32_t flag = (uint32_t) hf_heature; /* Flag structure is same as official */ ret = btHfSetSupportedFeature(&flag); return ret; } /**************************************************************************** * Name: bcm20706_bt_inquiry_cancel * * Description: * Bluetooth cancel inquiry. * Cancel inquiry to stop search. * ****************************************************************************/ static int bcm20706_bt_hfp_send_at_command(BT_ADDR *addr, char *at_str, uint16_t handle) { int ret = BT_SUCCESS; /* Not supported yet */ return ret; } /**************************************************************************** * Public Data ****************************************************************************/ struct bt_hal_hfp_ops_s bt_hal_hfp_ops = { .connect = bcm20706_bt_hfp_connect, .audio_connect = bcm20706_bt_hfp_audio_connect, .set_hf_feature = bcm20706_bt_hfp_hf_feature, .send_at_command = bcm20706_bt_hfp_send_at_command };
30.252294
88
0.595754
359e3533cd7a4607a91ff509650088ad7e49ef9a
12,553
h
C
src/base/bind.h
kiss2u/naiveproxy
724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a
[ "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
src/base/bind.h
kiss2u/naiveproxy
724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a
[ "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
src/base/bind.h
kiss2u/naiveproxy
724caf7f3c8bc2d2d0dcdf090e97429a3c88a85a
[ "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_BIND_H_ #define BASE_BIND_H_ #include <functional> #include <memory> #include <type_traits> #include <utility> #include "base/bind_internal.h" #include "base/compiler_specific.h" #include "base/template_util.h" #include "build/build_config.h" #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) #include "base/mac/scoped_block.h" #endif // ----------------------------------------------------------------------------- // Usage documentation // ----------------------------------------------------------------------------- // // Overview: // base::BindOnce() and base::BindRepeating() are helpers for creating // base::OnceCallback and base::RepeatingCallback objects respectively. // // For a runnable object of n-arity, the base::Bind*() family allows partial // application of the first m arguments. The remaining n - m arguments must be // passed when invoking the callback with Run(). // // // The first argument is bound at callback creation; the remaining // // two must be passed when calling Run() on the callback object. // base::OnceCallback<long(int, long)> cb = base::BindOnce( // [](short x, int y, long z) { return x * y * z; }, 42); // // When binding to a method, the receiver object must also be specified at // callback creation time. When Run() is invoked, the method will be invoked on // the specified receiver object. // // class C : public base::RefCounted<C> { void F(); }; // auto instance = base::MakeRefCounted<C>(); // auto cb = base::BindOnce(&C::F, instance); // std::move(cb).Run(); // Identical to instance->F() // // base::Bind is currently a type alias for base::BindRepeating(). In the // future, we expect to flip this to default to base::BindOnce(). // // See //docs/callback.md for the full documentation. // // ----------------------------------------------------------------------------- // Implementation notes // ----------------------------------------------------------------------------- // // If you're reading the implementation, before proceeding further, you should // read the top comment of base/bind_internal.h for a definition of common // terms and concepts. namespace base { // Bind as OnceCallback. template <typename Functor, typename... Args> inline OnceCallback<internal::MakeUnboundRunType<Functor, Args...>> BindOnce( Functor&& functor, Args&&... args) { static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() || (std::is_rvalue_reference<Functor&&>() && !std::is_const<std::remove_reference_t<Functor>>()), "BindOnce requires non-const rvalue for OnceCallback binding." " I.e.: base::BindOnce(std::move(callback))."); static_assert( conjunction< internal::AssertBindArgIsNotBasePassed<std::decay_t<Args>>...>::value, "Use std::move() instead of base::Passed() with base::BindOnce()"); return internal::BindImpl<OnceCallback>(std::forward<Functor>(functor), std::forward<Args>(args)...); } // Bind as RepeatingCallback. template <typename Functor, typename... Args> inline RepeatingCallback<internal::MakeUnboundRunType<Functor, Args...>> BindRepeating(Functor&& functor, Args&&... args) { static_assert( !internal::IsOnceCallback<std::decay_t<Functor>>(), "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move()."); return internal::BindImpl<RepeatingCallback>(std::forward<Functor>(functor), std::forward<Args>(args)...); } // Unannotated Bind. // TODO(tzik): Deprecate this and migrate to OnceCallback and // RepeatingCallback, once they get ready. template <typename Functor, typename... Args> inline Callback<internal::MakeUnboundRunType<Functor, Args...>> Bind( Functor&& functor, Args&&... args) { return base::BindRepeating(std::forward<Functor>(functor), std::forward<Args>(args)...); } // Special cases for binding to a base::Callback without extra bound arguments. // We CHECK() the validity of callback to guard against null pointers // accidentally ending up in posted tasks, causing hard-to-debug crashes. template <typename Signature> OnceCallback<Signature> BindOnce(OnceCallback<Signature> callback) { CHECK(callback); return callback; } template <typename Signature> OnceCallback<Signature> BindOnce(RepeatingCallback<Signature> callback) { CHECK(callback); return callback; } template <typename Signature> RepeatingCallback<Signature> BindRepeating( RepeatingCallback<Signature> callback) { CHECK(callback); return callback; } template <typename Signature> Callback<Signature> Bind(Callback<Signature> callback) { CHECK(callback); return callback; } // Unretained() allows binding a non-refcounted class, and to disable // refcounting on arguments that are refcounted objects. // // EXAMPLE OF Unretained(): // // class Foo { // public: // void func() { cout << "Foo:f" << endl; } // }; // // // In some function somewhere. // Foo foo; // OnceClosure foo_callback = // BindOnce(&Foo::func, Unretained(&foo)); // std::move(foo_callback).Run(); // Prints "Foo:f". // // Without the Unretained() wrapper on |&foo|, the above call would fail // to compile because Foo does not support the AddRef() and Release() methods. template <typename T> inline internal::UnretainedWrapper<T> Unretained(T* o) { return internal::UnretainedWrapper<T>(o); } // RetainedRef() accepts a ref counted object and retains a reference to it. // When the callback is called, the object is passed as a raw pointer. // // EXAMPLE OF RetainedRef(): // // void foo(RefCountedBytes* bytes) {} // // scoped_refptr<RefCountedBytes> bytes = ...; // OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes)); // std::move(callback).Run(); // // Without RetainedRef, the scoped_refptr would try to implicitly convert to // a raw pointer and fail compilation: // // OnceClosure callback = BindOnce(&foo, bytes); // ERROR! template <typename T> inline internal::RetainedRefWrapper<T> RetainedRef(T* o) { return internal::RetainedRefWrapper<T>(o); } template <typename T> inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) { return internal::RetainedRefWrapper<T>(std::move(o)); } // Owned() transfers ownership of an object to the callback resulting from // bind; the object will be deleted when the callback is deleted. // // EXAMPLE OF Owned(): // // void foo(int* arg) { cout << *arg << endl } // // int* pn = new int(1); // RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn)); // // foo_callback.Run(); // Prints "1" // foo_callback.Run(); // Prints "1" // *pn = 2; // foo_callback.Run(); // Prints "2" // // foo_callback.Reset(); // |pn| is deleted. Also will happen when // // |foo_callback| goes out of scope. // // Without Owned(), someone would have to know to delete |pn| when the last // reference to the callback is deleted. template <typename T> inline internal::OwnedWrapper<T> Owned(T* o) { return internal::OwnedWrapper<T>(o); } template <typename T, typename Deleter> inline internal::OwnedWrapper<T, Deleter> Owned( std::unique_ptr<T, Deleter>&& ptr) { return internal::OwnedWrapper<T, Deleter>(std::move(ptr)); } // OwnedRef() stores an object in the callback resulting from // bind and passes a reference to the object to the bound function. // // EXAMPLE OF OwnedRef(): // // void foo(int& arg) { cout << ++arg << endl } // // int counter = 0; // RepeatingClosure foo_callback = BindRepeating(&foo, OwnedRef(counter)); // // foo_callback.Run(); // Prints "1" // foo_callback.Run(); // Prints "2" // foo_callback.Run(); // Prints "3" // // cout << counter; // Prints "0", OwnedRef creates a copy of counter. // // Supports OnceCallbacks as well, useful to pass placeholder arguments: // // void bar(int& ignore, const std::string& s) { cout << s << endl } // // OnceClosure bar_callback = BindOnce(&bar, OwnedRef(0), "Hello"); // // std::move(bar_callback).Run(); // Prints "Hello" // // Without OwnedRef() it would not be possible to pass a mutable reference to an // object owned by the callback. template <typename T> internal::OwnedRefWrapper<std::decay_t<T>> OwnedRef(T&& t) { return internal::OwnedRefWrapper<std::decay_t<T>>(std::forward<T>(t)); } // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr) // through a RepeatingCallback. Logically, this signifies a destructive transfer // of the state of the argument into the target function. Invoking // RepeatingCallback::Run() twice on a callback that was created with a Passed() // argument will CHECK() because the first invocation would have already // transferred ownership to the target function. // // Note that Passed() is not necessary with BindOnce(), as std::move() does the // same thing. Avoid Passed() in favor of std::move() with BindOnce(). // // EXAMPLE OF Passed(): // // void TakesOwnership(std::unique_ptr<Foo> arg) { } // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>(); // } // // auto f = std::make_unique<Foo>(); // // // |cb| is given ownership of Foo(). |f| is now NULL. // // You can use std::move(f) in place of &f, but it's more verbose. // RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f)); // // // Run was never called so |cb| still owns Foo() and deletes // // it on Reset(). // cb.Reset(); // // // |cb| is given a new Foo created by CreateFoo(). // cb = BindRepeating(&TakesOwnership, Passed(CreateFoo())); // // // |arg| in TakesOwnership() is given ownership of Foo(). |cb| // // no longer owns Foo() and, if reset, would not delete Foo(). // cb.Run(); // Foo() is now transferred to |arg| and deleted. // cb.Run(); // This CHECK()s since Foo() already been used once. // // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is // best suited for use with the return value of a function or other temporary // rvalues. The second takes a pointer to the scoper and is just syntactic sugar // to avoid having to write Passed(std::move(scoper)). // // Both versions of Passed() prevent T from being an lvalue reference. The first // via use of enable_if, and the second takes a T* which will not bind to T&. template <typename T, std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr> inline internal::PassedWrapper<T> Passed(T&& scoper) { return internal::PassedWrapper<T>(std::move(scoper)); } template <typename T> inline internal::PassedWrapper<T> Passed(T* scoper) { return internal::PassedWrapper<T>(std::move(*scoper)); } // IgnoreResult() is used to adapt a function or callback with a return type to // one with a void return. This is most useful if you have a function with, // say, a pesky ignorable bool return that you want to use with PostTask or // something else that expect a callback with a void return. // // EXAMPLE OF IgnoreResult(): // // int DoSomething(int arg) { cout << arg << endl; } // // // Assign to a callback with a void return type. // OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething)); // std::move(cb).Run(1); // Prints "1". // // // Prints "2" on |ml|. // ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2); template <typename T> inline internal::IgnoreResultHelper<T> IgnoreResult(T data) { return internal::IgnoreResultHelper<T>(std::move(data)); } #if defined(OS_APPLE) && !HAS_FEATURE(objc_arc) // RetainBlock() is used to adapt an Objective-C block when Automated Reference // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the // BindOnce and BindRepeating already support blocks then. // // EXAMPLE OF RetainBlock(): // // // Wrap the block and bind it to a callback. // OnceCallback<void(int)> cb = // BindOnce(RetainBlock(^(int n) { NSLog(@"%d", n); })); // std::move(cb).Run(1); // Logs "1". template <typename R, typename... Args> base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) { return base::mac::ScopedBlock<R (^)(Args...)>(block, base::scoped_policy::RETAIN); } #endif // defined(OS_APPLE) && !HAS_FEATURE(objc_arc) } // namespace base #endif // BASE_BIND_H_
37.360119
80
0.661675
89465bc9ec15490450b3799c2810128618bf96f5
20,966
h
C
evolve4src/src/evolve_3d/mathlib.h
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
evolve4src/src/evolve_3d/mathlib.h
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
evolve4src/src/evolve_3d/mathlib.h
ilyar/Evolve
f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88
[ "EFL-2.0" ]
null
null
null
#pragma once //----------------------------------------------------------------------------- // Copyright (c) 2005-2006 dhpoware. All Rights Reserved. // // 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. //----------------------------------------------------------------------------- // // This is a stripped down version of the dhpoware 3D Math Library. To download // the full version visit: http://www.dhpoware.com/source/mathlib.html // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Common math functions and constants. //----------------------------------------------------------------------------- class Math { public: static const float PI; static const float HALF_PI; static const float EPSILON; static bool closeEnough(float f1, float f2) { // Determines whether the two floating-point values f1 and f2 are // close enough together that they can be considered equal. return fabsf((f1 - f2) / ((f2 == 0.0f) ? 1.0f : f2)) < EPSILON; } static float degreesToRadians(float degrees) { return (degrees * PI) / 180.0f; } static float radiansToDegrees(float radians) { return (radians * 180.0f) / PI; } }; //----------------------------------------------------------------------------- // A 3-component vector class that represents a row vector. //----------------------------------------------------------------------------- class Vector3 { friend Vector3 operator*(float lhs, const Vector3 &rhs); friend Vector3 operator-(const Vector3 &v); public: float x, y, z; static Vector3 cross(const Vector3 &p, const Vector3 &q); static float dot(const Vector3 &p, const Vector3 &q); Vector3() {} Vector3(float x_, float y_, float z_); ~Vector3() {} bool operator==(const Vector3 &rhs) const; bool operator!=(const Vector3 &rhs) const; Vector3 &operator+=(const Vector3 &rhs); Vector3 &operator-=(const Vector3 &rhs); Vector3 &operator*=(float scalar); Vector3 &operator/=(float scalar); Vector3 operator+(const Vector3 &rhs) const; Vector3 operator-(const Vector3 &rhs) const; Vector3 operator*(float scalar) const; Vector3 operator/(float scalar) const; float magnitude() const; float magnitudeSq() const; Vector3 inverse() const; void normalize(); void set(float x_, float y_, float z_); }; inline Vector3 operator*(float lhs, const Vector3 &rhs) { return Vector3(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } inline Vector3 operator-(const Vector3 &v) { return Vector3(-v.x, -v.y, -v.z); } inline Vector3 Vector3::cross(const Vector3 &p, const Vector3 &q) { return Vector3((p.y * q.z) - (p.z * q.y), (p.z * q.x) - (p.x * q.z), (p.x * q.y) - (p.y * q.x)); } inline float Vector3::dot(const Vector3 &p, const Vector3 &q) { return (p.x * q.x) + (p.y * q.y) + (p.z * q.z); } inline Vector3::Vector3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {} inline Vector3 &Vector3::operator+=(const Vector3 &rhs) { x += rhs.x, y += rhs.y, z += rhs.z; return *this; } inline bool Vector3::operator==(const Vector3 &rhs) const { return Math::closeEnough(x, rhs.x) && Math::closeEnough(y, rhs.y) && Math::closeEnough(z, rhs.z); } inline bool Vector3::operator!=(const Vector3 &rhs) const { return !(*this == rhs); } inline Vector3 &Vector3::operator-=(const Vector3 &rhs) { x -= rhs.x, y -= rhs.y, z -= rhs.z; return *this; } inline Vector3 &Vector3::operator*=(float scalar) { x *= scalar, y *= scalar, z *= scalar; return *this; } inline Vector3 &Vector3::operator/=(float scalar) { x /= scalar, y /= scalar, z /= scalar; return *this; } inline Vector3 Vector3::operator+(const Vector3 &rhs) const { Vector3 tmp(*this); tmp += rhs; return tmp; } inline Vector3 Vector3::operator-(const Vector3 &rhs) const { Vector3 tmp(*this); tmp -= rhs; return tmp; } inline Vector3 Vector3::operator*(float scalar) const { return Vector3(x * scalar, y * scalar, z * scalar); } inline Vector3 Vector3::operator/(float scalar) const { return Vector3(x / scalar, y / scalar, z / scalar); } inline float Vector3::magnitude() const { return sqrtf((x * x) + (y * y) + (z * z)); } inline float Vector3::magnitudeSq() const { return (x * x) + (y * y) + (z * z); } inline Vector3 Vector3::inverse() const { return Vector3(-x, -y, -z); } inline void Vector3::normalize() { float invMag = 1.0f / magnitude(); x *= invMag, y *= invMag, z *= invMag; } inline void Vector3::set(float x_, float y_, float z_) { x = x_, y = y_, z = z_; } //----------------------------------------------------------------------------- // A homogeneous row-major 4x4 matrix class. // // Matrices are concatenated in a left to right order. // Multiplies Vector3s to the left of the matrix. //----------------------------------------------------------------------------- class Matrix4 { friend Vector3 operator*(const Vector3 &lhs, const Matrix4 &rhs); friend Matrix4 operator*(float scalar, const Matrix4 &rhs); public: static const Matrix4 IDENTITY; Matrix4() {} Matrix4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); ~Matrix4() {} float *operator[](int row); const float *operator[](int row) const; bool operator==(const Matrix4 &rhs) const; bool operator!=(const Matrix4 &rhs) const; Matrix4 &operator+=(const Matrix4 &rhs); Matrix4 &operator-=(const Matrix4 &rhs); Matrix4 &operator*=(const Matrix4 &rhs); Matrix4 &operator*=(float scalar); Matrix4 &operator/=(float scalar); Matrix4 operator+(const Matrix4 &rhs) const; Matrix4 operator-(const Matrix4 &rhs) const; Matrix4 operator*(const Matrix4 &rhs) const; Matrix4 operator*(float scalar) const; Matrix4 operator/(float scalar) const; void fromHeadPitchRoll(float headDegrees, float pitchDegrees, float rollDegrees); void identity(); void rotate(const Vector3 &axis, float degrees); void toHeadPitchRoll(float &headDegrees, float &pitchDegrees, float &rollDegrees) const; private: float mtx[4][4]; }; inline Vector3 operator*(const Vector3 &lhs, const Matrix4 &rhs) { return Vector3((lhs.x * rhs.mtx[0][0]) + (lhs.y * rhs.mtx[1][0]) + (lhs.z * rhs.mtx[2][0]), (lhs.x * rhs.mtx[0][1]) + (lhs.y * rhs.mtx[1][1]) + (lhs.z * rhs.mtx[2][1]), (lhs.x * rhs.mtx[0][2]) + (lhs.y * rhs.mtx[1][2]) + (lhs.z * rhs.mtx[2][2])); } inline Matrix4 operator*(float scalar, const Matrix4 &rhs) { return rhs * scalar; } inline Matrix4::Matrix4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { mtx[0][0] = m11, mtx[0][1] = m12, mtx[0][2] = m13, mtx[0][3] = m14; mtx[1][0] = m21, mtx[1][1] = m22, mtx[1][2] = m23, mtx[1][3] = m24; mtx[2][0] = m31, mtx[2][1] = m32, mtx[2][2] = m33, mtx[2][3] = m34; mtx[3][0] = m41, mtx[3][1] = m42, mtx[3][2] = m43, mtx[3][3] = m44; } inline float *Matrix4::operator[](int row) { return mtx[row]; } inline const float *Matrix4::operator[](int row) const { return mtx[row]; } inline bool Matrix4::operator==(const Matrix4 &rhs) const { return Math::closeEnough(mtx[0][0], rhs.mtx[0][0]) && Math::closeEnough(mtx[0][1], rhs.mtx[0][1]) && Math::closeEnough(mtx[0][2], rhs.mtx[0][2]) && Math::closeEnough(mtx[0][3], rhs.mtx[0][3]) && Math::closeEnough(mtx[1][0], rhs.mtx[1][0]) && Math::closeEnough(mtx[1][1], rhs.mtx[1][1]) && Math::closeEnough(mtx[1][2], rhs.mtx[1][2]) && Math::closeEnough(mtx[1][3], rhs.mtx[1][3]) && Math::closeEnough(mtx[2][0], rhs.mtx[2][0]) && Math::closeEnough(mtx[2][1], rhs.mtx[2][1]) && Math::closeEnough(mtx[2][2], rhs.mtx[2][2]) && Math::closeEnough(mtx[2][3], rhs.mtx[2][3]) && Math::closeEnough(mtx[3][0], rhs.mtx[3][0]) && Math::closeEnough(mtx[3][1], rhs.mtx[3][1]) && Math::closeEnough(mtx[3][2], rhs.mtx[3][2]) && Math::closeEnough(mtx[3][3], rhs.mtx[3][3]); } inline bool Matrix4::operator!=(const Matrix4 &rhs) const { return !(*this == rhs); } inline Matrix4 &Matrix4::operator+=(const Matrix4 &rhs) { mtx[0][0] += rhs.mtx[0][0], mtx[0][1] += rhs.mtx[0][1], mtx[0][2] += rhs.mtx[0][2], mtx[0][3] += rhs.mtx[0][3]; mtx[1][0] += rhs.mtx[1][0], mtx[1][1] += rhs.mtx[1][1], mtx[1][2] += rhs.mtx[1][2], mtx[1][3] += rhs.mtx[1][3]; mtx[2][0] += rhs.mtx[2][0], mtx[2][1] += rhs.mtx[2][1], mtx[2][2] += rhs.mtx[2][2], mtx[2][3] += rhs.mtx[2][3]; mtx[3][0] += rhs.mtx[3][0], mtx[3][1] += rhs.mtx[3][1], mtx[3][2] += rhs.mtx[3][2], mtx[3][3] += rhs.mtx[3][3]; return *this; } inline Matrix4 &Matrix4::operator-=(const Matrix4 &rhs) { mtx[0][0] -= rhs.mtx[0][0], mtx[0][1] -= rhs.mtx[0][1], mtx[0][2] -= rhs.mtx[0][2], mtx[0][3] -= rhs.mtx[0][3]; mtx[1][0] -= rhs.mtx[1][0], mtx[1][1] -= rhs.mtx[1][1], mtx[1][2] -= rhs.mtx[1][2], mtx[1][3] -= rhs.mtx[1][3]; mtx[2][0] -= rhs.mtx[2][0], mtx[2][1] -= rhs.mtx[2][1], mtx[2][2] -= rhs.mtx[2][2], mtx[2][3] -= rhs.mtx[2][3]; mtx[3][0] -= rhs.mtx[3][0], mtx[3][1] -= rhs.mtx[3][1], mtx[3][2] -= rhs.mtx[3][2], mtx[3][3] -= rhs.mtx[3][3]; return *this; } inline Matrix4 &Matrix4::operator*=(const Matrix4 &rhs) { Matrix4 tmp; // Row 1. tmp.mtx[0][0] = (mtx[0][0] * rhs.mtx[0][0]) + (mtx[0][1] * rhs.mtx[1][0]) + (mtx[0][2] * rhs.mtx[2][0]) + (mtx[0][3] * rhs.mtx[3][0]); tmp.mtx[0][1] = (mtx[0][0] * rhs.mtx[0][1]) + (mtx[0][1] * rhs.mtx[1][1]) + (mtx[0][2] * rhs.mtx[2][1]) + (mtx[0][3] * rhs.mtx[3][1]); tmp.mtx[0][2] = (mtx[0][0] * rhs.mtx[0][2]) + (mtx[0][1] * rhs.mtx[1][2]) + (mtx[0][2] * rhs.mtx[2][2]) + (mtx[0][3] * rhs.mtx[3][2]); tmp.mtx[0][3] = (mtx[0][0] * rhs.mtx[0][3]) + (mtx[0][1] * rhs.mtx[1][3]) + (mtx[0][2] * rhs.mtx[2][3]) + (mtx[0][3] * rhs.mtx[3][3]); // Row 2. tmp.mtx[1][0] = (mtx[1][0] * rhs.mtx[0][0]) + (mtx[1][1] * rhs.mtx[1][0]) + (mtx[1][2] * rhs.mtx[2][0]) + (mtx[1][3] * rhs.mtx[3][0]); tmp.mtx[1][1] = (mtx[1][0] * rhs.mtx[0][1]) + (mtx[1][1] * rhs.mtx[1][1]) + (mtx[1][2] * rhs.mtx[2][1]) + (mtx[1][3] * rhs.mtx[3][1]); tmp.mtx[1][2] = (mtx[1][0] * rhs.mtx[0][2]) + (mtx[1][1] * rhs.mtx[1][2]) + (mtx[1][2] * rhs.mtx[2][2]) + (mtx[1][3] * rhs.mtx[3][2]); tmp.mtx[1][3] = (mtx[1][0] * rhs.mtx[0][3]) + (mtx[1][1] * rhs.mtx[1][3]) + (mtx[1][2] * rhs.mtx[2][3]) + (mtx[1][3] * rhs.mtx[3][3]); // Row 3. tmp.mtx[2][0] = (mtx[2][0] * rhs.mtx[0][0]) + (mtx[2][1] * rhs.mtx[1][0]) + (mtx[2][2] * rhs.mtx[2][0]) + (mtx[2][3] * rhs.mtx[3][0]); tmp.mtx[2][1] = (mtx[2][0] * rhs.mtx[0][1]) + (mtx[2][1] * rhs.mtx[1][1]) + (mtx[2][2] * rhs.mtx[2][1]) + (mtx[2][3] * rhs.mtx[3][1]); tmp.mtx[2][2] = (mtx[2][0] * rhs.mtx[0][2]) + (mtx[2][1] * rhs.mtx[1][2]) + (mtx[2][2] * rhs.mtx[2][2]) + (mtx[2][3] * rhs.mtx[3][2]); tmp.mtx[2][3] = (mtx[2][0] * rhs.mtx[0][3]) + (mtx[2][1] * rhs.mtx[1][3]) + (mtx[2][2] * rhs.mtx[2][3]) + (mtx[2][3] * rhs.mtx[3][3]); // Row 4. tmp.mtx[3][0] = (mtx[3][0] * rhs.mtx[0][0]) + (mtx[3][1] * rhs.mtx[1][0]) + (mtx[3][2] * rhs.mtx[2][0]) + (mtx[3][3] * rhs.mtx[3][0]); tmp.mtx[3][1] = (mtx[3][0] * rhs.mtx[0][1]) + (mtx[3][1] * rhs.mtx[1][1]) + (mtx[3][2] * rhs.mtx[2][1]) + (mtx[3][3] * rhs.mtx[3][1]); tmp.mtx[3][2] = (mtx[3][0] * rhs.mtx[0][2]) + (mtx[3][1] * rhs.mtx[1][2]) + (mtx[3][2] * rhs.mtx[2][2]) + (mtx[3][3] * rhs.mtx[3][2]); tmp.mtx[3][3] = (mtx[3][0] * rhs.mtx[0][3]) + (mtx[3][1] * rhs.mtx[1][3]) + (mtx[3][2] * rhs.mtx[2][3]) + (mtx[3][3] * rhs.mtx[3][3]); *this = tmp; return *this; } inline Matrix4 &Matrix4::operator*=(float scalar) { mtx[0][0] *= scalar, mtx[0][1] *= scalar, mtx[0][2] *= scalar, mtx[0][3] *= scalar; mtx[1][0] *= scalar, mtx[1][1] *= scalar, mtx[1][2] *= scalar, mtx[1][3] *= scalar; mtx[2][0] *= scalar, mtx[2][1] *= scalar, mtx[2][2] *= scalar, mtx[2][3] *= scalar; mtx[3][0] *= scalar, mtx[3][1] *= scalar, mtx[3][2] *= scalar, mtx[3][3] *= scalar; return *this; } inline Matrix4 &Matrix4::operator/=(float scalar) { mtx[0][0] /= scalar, mtx[0][1] /= scalar, mtx[0][2] /= scalar, mtx[0][3] /= scalar; mtx[1][0] /= scalar, mtx[1][1] /= scalar, mtx[1][2] /= scalar, mtx[1][3] /= scalar; mtx[2][0] /= scalar, mtx[2][1] /= scalar, mtx[2][2] /= scalar, mtx[2][3] /= scalar; mtx[3][0] /= scalar, mtx[3][1] /= scalar, mtx[3][2] /= scalar, mtx[3][3] /= scalar; return *this; } inline Matrix4 Matrix4::operator+(const Matrix4 &rhs) const { Matrix4 tmp(*this); tmp += rhs; return tmp; } inline Matrix4 Matrix4::operator-(const Matrix4 &rhs) const { Matrix4 tmp(*this); tmp -= rhs; return tmp; } inline Matrix4 Matrix4::operator*(const Matrix4 &rhs) const { Matrix4 tmp(*this); tmp *= rhs; return tmp; } inline Matrix4 Matrix4::operator*(float scalar) const { Matrix4 tmp(*this); tmp *= scalar; return tmp; } inline Matrix4 Matrix4::operator/(float scalar) const { Matrix4 tmp(*this); tmp /= scalar; return tmp; } inline void Matrix4::identity() { mtx[0][0] = 1.0f, mtx[0][1] = 0.0f, mtx[0][2] = 0.0f, mtx[0][3] = 0.0f; mtx[1][0] = 0.0f, mtx[1][1] = 1.0f, mtx[1][2] = 0.0f, mtx[1][3] = 0.0f; mtx[2][0] = 0.0f, mtx[2][1] = 0.0f, mtx[2][2] = 1.0f, mtx[2][3] = 0.0f; mtx[3][0] = 0.0f, mtx[3][1] = 0.0f, mtx[3][2] = 0.0f, mtx[3][3] = 1.0f; } //----------------------------------------------------------------------------- // This Quaternion class will concatenate quaternions in a left to right order. // The reason for this is to maintain the same multiplication semantics as the // Matrix4 classes. //----------------------------------------------------------------------------- class Quaternion { friend Quaternion operator*(float lhs, const Quaternion &rhs); public: static const Quaternion IDENTITY; float w, x, y, z; Quaternion() {} Quaternion(float w_, float x_, float y_, float z_); Quaternion(float headDegrees, float pitchDegrees, float rollDegrees); Quaternion(const Vector3 &axis, float degrees); explicit Quaternion(const Matrix4 &m); ~Quaternion() {} bool operator==(const Quaternion &rhs) const; bool operator!=(const Quaternion &rhs) const; Quaternion &operator+=(const Quaternion &rhs); Quaternion &operator-=(const Quaternion &rhs); Quaternion &operator*=(const Quaternion &rhs); Quaternion &operator*=(float scalar); Quaternion &operator/=(float scalar); Quaternion operator+(const Quaternion &rhs) const; Quaternion operator-(const Quaternion &rhs) const; Quaternion operator*(const Quaternion &rhs) const; Quaternion operator*(float scalar) const; Quaternion operator/(float scalar) const; Quaternion conjugate() const; void fromAxisAngle(const Vector3 &axis, float degrees); void fromHeadPitchRoll(float headDegrees, float pitchDegrees, float rollDegrees); void fromMatrix(const Matrix4 &m); void identity(); Quaternion inverse() const; float magnitude() const; void normalize(); void set(float w_, float x_, float y_, float z_); void toAxisAngle(Vector3 &axis, float &degrees) const; void toHeadPitchRoll(float &headDegrees, float &pitchDegrees, float &rollDegrees) const; Matrix4 toMatrix4() const; }; inline Quaternion operator*(float lhs, const Quaternion &rhs) { return rhs * lhs; } inline Quaternion::Quaternion(float w_, float x_, float y_, float z_) : w(w_), x(x_), y(y_), z(z_) {} inline Quaternion::Quaternion(float headDegrees, float pitchDegrees, float rollDegrees) { fromHeadPitchRoll(headDegrees, pitchDegrees, rollDegrees); } inline Quaternion::Quaternion(const Vector3 &axis, float degrees) { fromAxisAngle(axis, degrees); } inline Quaternion::Quaternion(const Matrix4 &m) { fromMatrix(m); } inline bool Quaternion::operator==(const Quaternion &rhs) const { return Math::closeEnough(w, rhs.w) && Math::closeEnough(x, rhs.x) && Math::closeEnough(y, rhs.y) && Math::closeEnough(z, rhs.z); } inline bool Quaternion::operator!=(const Quaternion &rhs) const { return !(*this == rhs); } inline Quaternion &Quaternion::operator+=(const Quaternion &rhs) { w += rhs.w, x += rhs.x, y += rhs.y, z += rhs.z; return *this; } inline Quaternion &Quaternion::operator-=(const Quaternion &rhs) { w -= rhs.w, x -= rhs.x, y -= rhs.y, z -= rhs.z; return *this; } inline Quaternion &Quaternion::operator*=(const Quaternion &rhs) { // Multiply so that rotations are applied in a left to right order. Quaternion tmp( (w * rhs.w) - (x * rhs.x) - (y * rhs.y) - (z * rhs.z), (w * rhs.x) + (x * rhs.w) - (y * rhs.z) + (z * rhs.y), (w * rhs.y) + (x * rhs.z) + (y * rhs.w) - (z * rhs.x), (w * rhs.z) - (x * rhs.y) + (y * rhs.x) + (z * rhs.w)); /* // Multiply so that rotations are applied in a right to left order. Quaternion tmp( (w * rhs.w) - (x * rhs.x) - (y * rhs.y) - (z * rhs.z), (w * rhs.x) + (x * rhs.w) + (y * rhs.z) - (z * rhs.y), (w * rhs.y) - (x * rhs.z) + (y * rhs.w) + (z * rhs.x), (w * rhs.z) + (x * rhs.y) - (y * rhs.x) + (z * rhs.w)); */ *this = tmp; return *this; } inline Quaternion &Quaternion::operator*=(float scalar) { w *= scalar, x *= scalar, y *= scalar, z *= scalar; return *this; } inline Quaternion &Quaternion::operator/=(float scalar) { w /= scalar, x /= scalar, y /= scalar, z /= scalar; return *this; } inline Quaternion Quaternion::operator+(const Quaternion &rhs) const { Quaternion tmp(*this); tmp += rhs; return tmp; } inline Quaternion Quaternion::operator-(const Quaternion &rhs) const { Quaternion tmp(*this); tmp -= rhs; return tmp; } inline Quaternion Quaternion::operator*(const Quaternion &rhs) const { Quaternion tmp(*this); tmp *= rhs; return tmp; } inline Quaternion Quaternion::operator*(float scalar) const { Quaternion tmp(*this); tmp *= scalar; return tmp; } inline Quaternion Quaternion::operator/(float scalar) const { Quaternion tmp(*this); tmp /= scalar; return tmp; } inline Quaternion Quaternion::conjugate() const { Quaternion tmp(w, -x, -y, -z); return tmp; } inline void Quaternion::fromAxisAngle(const Vector3 &axis, float degrees) { float halfTheta = Math::degreesToRadians(degrees) * 0.5f; float s = sinf(halfTheta); w = cosf(halfTheta), x = axis.x * s, y = axis.y * s, z = axis.z * s; } inline void Quaternion::fromHeadPitchRoll(float headDegrees, float pitchDegrees, float rollDegrees) { Matrix4 m; m.fromHeadPitchRoll(headDegrees, pitchDegrees, rollDegrees); fromMatrix(m); } inline void Quaternion::identity() { w = 1.0f, x = y = z = 0.0f; } inline Quaternion Quaternion::inverse() const { float invMag = 1.0f / magnitude(); return conjugate() * invMag; } inline float Quaternion::magnitude() const { return sqrtf(w * w + x * x + y * y + z * z); } inline void Quaternion::normalize() { float invMag = 1.0f / magnitude(); w *= invMag, x *= invMag, y *= invMag, z *= invMag; } inline void Quaternion::set(float w_, float x_, float y_, float z_) { w = w_, x = x_, y = y_, z = z_; } inline void Quaternion::toHeadPitchRoll(float &headDegrees, float &pitchDegrees, float &rollDegrees) const { Matrix4 m = toMatrix4(); m.toHeadPitchRoll(headDegrees, pitchDegrees, rollDegrees); }
32.555901
138
0.57288
81875cdbed952b86f7bf9b13d24aea40158e8c0d
8,490
h
C
src/reflect/_MulleFoundation-import.h
mulle-nat/MulleFoundation
61592dc5121dbf783f9e9190cbd50d39c8ebaa51
[ "BSD-3-Clause" ]
null
null
null
src/reflect/_MulleFoundation-import.h
mulle-nat/MulleFoundation
61592dc5121dbf783f9e9190cbd50d39c8ebaa51
[ "BSD-3-Clause" ]
null
null
null
src/reflect/_MulleFoundation-import.h
mulle-nat/MulleFoundation
61592dc5121dbf783f9e9190cbd50d39c8ebaa51
[ "BSD-3-Clause" ]
null
null
null
/* * This file will be regenerated by `mulle-sourcetree-to-c --project-dialect objc` via * `mulle-sde reflect` and any edits will be lost. * Suppress generation of this file with: * * mulle-sde environment set MULLE_SOURCETREE_TO_C_IMPORT_FILE DISABLE * * To not let mulle-sourcetree-to-c generate any header files: * * mulle-sde environment set MULLE_SOURCETREE_TO_C_RUN DISABLE * */ // You can tweak the following #import with these commands. // (Use DACD462C-D0AC-4D93-81A6-4E0972215046 instead of MulleObjCOSFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCOSFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCOSFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCOSFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCOSFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCOSFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCOSFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCOSFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCOSFoundation/MulleObjCOSFoundation.h>) # import <MulleObjCOSFoundation/MulleObjCOSFoundation.h> // MulleObjCOSFoundation # define HAVE_LIB_MULLE_OBJC_OS_FOUNDATION # endif #endif // You can tweak the following #import with these commands. // (Use 3C6EAD75-99C0-482F-AAA7-CFB194733AEC instead of MulleObjCKVCFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCKVCFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCKVCFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCKVCFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCKVCFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCKVCFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCKVCFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCKVCFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCKVCFoundation/MulleObjCKVCFoundation.h>) # import <MulleObjCKVCFoundation/MulleObjCKVCFoundation.h> // MulleObjCKVCFoundation # define HAVE_LIB_MULLE_OBJC_KVC_FOUNDATION # endif #endif // You can tweak the following #import with these commands. // (Use 41549518-5DAC-4A6A-82A9-E2CAABE3828F instead of MulleObjCDecimalFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCDecimalFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCDecimalFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCDecimalFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCDecimalFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCDecimalFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCDecimalFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCDecimalFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCDecimalFoundation/MulleObjCDecimalFoundation.h>) # import <MulleObjCDecimalFoundation/MulleObjCDecimalFoundation.h> // MulleObjCDecimalFoundation # define HAVE_LIB_MULLE_OBJC_DECIMAL_FOUNDATION # endif #endif // You can tweak the following #import with these commands. // (Use 1D103583-A637-4819-9255-3A265C80E49A instead of MulleObjCCalendarFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCCalendarFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCCalendarFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCCalendarFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCCalendarFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCCalendarFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCCalendarFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCCalendarFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCCalendarFoundation/MulleObjCCalendarFoundation.h>) # import <MulleObjCCalendarFoundation/MulleObjCCalendarFoundation.h> // MulleObjCCalendarFoundation # define HAVE_LIB_MULLE_OBJC_CALENDAR_FOUNDATION # endif #endif // You can tweak the following #import with these commands. // (Use C48EE179-39A6-466D-A07E-37ECC02D20A4 instead of MulleObjCMathFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCMathFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCMathFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCMathFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCMathFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCMathFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCMathFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCMathFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCMathFoundation/MulleObjCMathFoundation.h>) # import <MulleObjCMathFoundation/MulleObjCMathFoundation.h> // MulleObjCMathFoundation # define HAVE_LIB_MULLE_OBJC_MATH_FOUNDATION # endif #endif // You can tweak the following #import with these commands. // (Use df7054ac-99cd-4386-b5fc-cbce1eaf009e instead of MulleObjCUnicodeFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCUnicodeFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCUnicodeFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCUnicodeFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCUnicodeFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCUnicodeFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCUnicodeFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCUnicodeFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #import <MulleObjCUnicodeFoundation/MulleObjCUnicodeFoundation.h> // MulleObjCUnicodeFoundation // You can tweak the following #import with these commands. // (Use CC33FA59-ACA8-47AF-861D-6036B12CA9C9 instead of MulleObjCArchiverFoundation if there are duplicate entries) // remove: `mulle-sde dependency mark MulleObjCArchiverFoundation no-header` // rename: `mulle-sde dependency|library set MulleObjCArchiverFoundation include whatever.h` // reorder: `mulle-sde dependency move MulleObjCArchiverFoundation <up|down>` // toggle #import: `mulle-sde dependency mark MulleObjCArchiverFoundation [no-]import` // toggle public: `mulle-sde dependency mark MulleObjCArchiverFoundation [no-]public` // toggle optional: `mulle-sde dependency mark MulleObjCArchiverFoundation [no-]require` // remove for platform:`mulle-sde dependency mark MulleObjCArchiverFoundation no-platform-<uname>` // (use `mulle-sourcetree-to-c --unames` to list known values) #ifdef __has_include # if __has_include(<MulleObjCArchiverFoundation/MulleObjCArchiverFoundation.h>) # import <MulleObjCArchiverFoundation/MulleObjCArchiverFoundation.h> // MulleObjCArchiverFoundation # define HAVE_LIB_MULLE_OBJC_ARCHIVER_FOUNDATION # endif #endif #ifdef __has_include # if __has_include( "_MulleFoundation-include.h") # include "_MulleFoundation-include.h" # endif #endif
63.358209
115
0.753239
54583d3171fcdc9fcaa9136b21fc2ba663dc59f8
26,391
h
C
prop-src/matchcom.h
AaronNGray/prop-cc-new
3d9660f55c94c5bd260f6b7cc902fa19109d35a9
[ "BSD-2-Clause" ]
1
2018-03-23T20:32:09.000Z
2018-03-23T20:32:09.000Z
prop-src/matchcom.h
AaronNGray/prop-cc-new
3d9660f55c94c5bd260f6b7cc902fa19109d35a9
[ "BSD-2-Clause" ]
null
null
null
prop-src/matchcom.h
AaronNGray/prop-cc-new
3d9660f55c94c5bd260f6b7cc902fa19109d35a9
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // This file is generated automatically using Prop (version 2.4.0), // last updated on Jul 1, 2011. // The original source file is "matchcom.ph". /////////////////////////////////////////////////////////////////////////////// #line 1 "matchcom.ph" /////////////////////////////////////////////////////////////////////////////// // // This file describes the interface to the pattern matching compiler. // /////////////////////////////////////////////////////////////////////////////// #ifndef match_compiler_h #define match_compiler_h #include <iostream> #include "ir.h" #include "ast.h" #include "patenv.h" #include "hashtab.h" #include "labelgen.h" #include "codegen.h" /////////////////////////////////////////////////////////////////////////////// // // Forward type declarations. // /////////////////////////////////////////////////////////////////////////////// class BitSet; // bit sets /////////////////////////////////////////////////////////////////////////////// // // Pattern matching decision tree (dag) // /////////////////////////////////////////////////////////////////////////////// struct MatchBase : public MEM { int shared; Id label; MatchBase(); }; #line 40 "matchcom.ph" #line 76 "matchcom.ph" /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Match // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Match_defined #define datatype_Match_defined class a_Match; typedef a_Match * Match; #endif # define v_FAILmatch 0 # define v_DONTCAREmatch 1 # define FAILmatch (Match)v_FAILmatch # define DONTCAREmatch (Match)v_DONTCAREmatch /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Cost // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Cost_defined #define datatype_Cost_defined class a_Cost; typedef a_Cost * Cost; #endif # define v_NOcost 0 # define NOcost (Cost)v_NOcost /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Pos // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Pos_defined #define datatype_Pos_defined class a_Pos; typedef a_Pos * Pos; #endif # define v_POSzero 0 # define v_POSinfinity 1 # define POSzero (Pos)v_POSzero # define POSinfinity (Pos)v_POSinfinity /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Match // /////////////////////////////////////////////////////////////////////////////// class a_Match : public MatchBase { public: enum Tag_Match { tag_SUCCESSmatch = 0, tag_SUCCESSESmatch = 1, tag_COSTmatch = 2, tag_GUARDmatch = 3, tag_LITERALmatch = 4, tag_RANGEmatch = 5, tag_CONSmatch = 6, tag_TREECOSTmatch = 7, tag_TREELABELmatch = 8, tag_BACKEDGEmatch = 9 }; public: const Tag_Match tag__; // variant tag protected: inline a_Match(Tag_Match t__) : tag__(t__) {} public: }; inline int boxed(const a_Match * x) { return (unsigned long)x >= 2; } inline int untag(const a_Match * x) { return boxed(x) ? x->tag__ + 2 : (int)x; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::SUCCESSmatch // /////////////////////////////////////////////////////////////////////////////// class Match_SUCCESSmatch : public a_Match { public: #line 42 "matchcom.ph" int _1; MatchRule _2; Match_SUCCESSmatch (int x_1, MatchRule x_2); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::SUCCESSESmatch // /////////////////////////////////////////////////////////////////////////////// class Match_SUCCESSESmatch : public a_Match { public: #line 43 "matchcom.ph" int _1; BitSet * _2; MatchRules _3; Match_SUCCESSESmatch (int x_1, BitSet * x_2, MatchRules x_3); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::COSTmatch // /////////////////////////////////////////////////////////////////////////////// class Match_COSTmatch : public a_Match { public: #line 44 "matchcom.ph" int _1; Cost * _2; BitSet * _3; MatchRules _4; Match_COSTmatch (int x_1, Cost * x_2, BitSet * x_3, MatchRules x_4); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::GUARDmatch // /////////////////////////////////////////////////////////////////////////////// class Match_GUARDmatch : public a_Match { public: #line 45 "matchcom.ph" Exp _1; Match _2; Match _3; Match_GUARDmatch (Exp x_1, Match x_2, Match x_3); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::LITERALmatch // /////////////////////////////////////////////////////////////////////////////// class Match_LITERALmatch : public a_Match { public: #line 46 "matchcom.ph" Pos _1; Exp _2; Literal * _3; int _4; Match * _5; Match _6; Match_LITERALmatch (Pos x_1, Exp x_2, Literal * x_3, int x_4, Match * x_5, Match x_6); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::RANGEmatch // /////////////////////////////////////////////////////////////////////////////// class Match_RANGEmatch : public a_Match { public: #line 47 "matchcom.ph" Pos _1; Exp _2; int _3; int _4; Match _5; Match _6; Match_RANGEmatch (Pos x_1, Exp x_2, int x_3, int x_4, Match x_5, Match x_6); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::CONSmatch // /////////////////////////////////////////////////////////////////////////////// class Match_CONSmatch : public a_Match { public: #line 48 "matchcom.ph" Pos _1; Exp _2; Ty _3; Ty _4; int _5; Match * _6; Match _7; Match_CONSmatch (Pos x_1, Exp x_2, Ty x_3, Ty x_4, int x_5, Match * x_6, Match x_7); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::TREECOSTmatch // /////////////////////////////////////////////////////////////////////////////// class Match_TREECOSTmatch : public a_Match { public: #line 50 "matchcom.ph" Match _1; BitSet * _2; MatchRules _3; Match_TREECOSTmatch (Match x_1, BitSet * x_2, MatchRules x_3); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::TREELABELmatch // /////////////////////////////////////////////////////////////////////////////// class Match_TREELABELmatch : public a_Match { public: #line 51 "matchcom.ph" Match _1; Ty _2; Ty _3; int _4; Match_TREELABELmatch (Match x_1, Ty x_2, Ty x_3, int x_4); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Match::BACKEDGEmatch // /////////////////////////////////////////////////////////////////////////////// class Match_BACKEDGEmatch : public a_Match { public: #line 53 "matchcom.ph" int _1; Id _2; Match _3; Match_BACKEDGEmatch (int x_1, Id x_2, Match x_3); }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Match // /////////////////////////////////////////////////////////////////////////////// extern a_Match * SUCCESSmatch (int x_1, MatchRule x_2); extern a_Match * SUCCESSESmatch (int x_1, BitSet * x_2, MatchRules x_3); extern a_Match * COSTmatch (int x_1, Cost * x_2, BitSet * x_3, MatchRules x_4); extern a_Match * GUARDmatch (Exp x_1, Match x_2, Match x_3); extern a_Match * LITERALmatch (Pos x_1, Exp x_2, Literal * x_3, int x_4, Match * x_5, Match x_6); extern a_Match * RANGEmatch (Pos x_1, Exp x_2, int x_3, int x_4, Match x_5, Match x_6); extern a_Match * CONSmatch (Pos x_1, Exp x_2, Ty x_3, Ty x_4, int x_5, Match * x_6, Match x_7); extern a_Match * TREECOSTmatch (Match x_1, BitSet * x_2, MatchRules x_3); extern a_Match * TREELABELmatch (Match x_1, Ty x_2, Ty x_3, int x_4); extern a_Match * BACKEDGEmatch (int x_1, Id x_2, Match x_3); /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Cost // /////////////////////////////////////////////////////////////////////////////// class a_Cost : public MEM { public: enum Tag_Cost { tag_EXPcost = 0, tag_INTcost = 1 }; public: }; inline int boxed(const a_Cost * x) { return x != 0; } /////////////////////////////////////////////////////////////////////////////// // // Embbeded tag extraction functions // /////////////////////////////////////////////////////////////////////////////// inline int untagp(const a_Cost * x) { return (unsigned long)x & 3; } inline a_Cost * derefp(const a_Cost * x) { return (a_Cost*)((unsigned long)x & ~3); } inline int untag(const a_Cost * x) { return x ? untagp(x)+1 : 0; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Cost::EXPcost // /////////////////////////////////////////////////////////////////////////////// class Cost_EXPcost : public a_Cost { public: #line 62 "matchcom.ph" Exp _1; Ty _2; Cost_EXPcost (Exp x_1, Ty x_2 = NOty); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Cost::INTcost // /////////////////////////////////////////////////////////////////////////////// class Cost_INTcost : public a_Cost { public: #line 63 "matchcom.ph" int INTcost; Cost_INTcost (int x_INTcost); }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Cost // /////////////////////////////////////////////////////////////////////////////// extern a_Cost * EXPcost (Exp x_1, Ty x_2 = NOty); extern a_Cost * INTcost (int x_INTcost); /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Pos // /////////////////////////////////////////////////////////////////////////////// class a_Pos : public MEM { public: enum Tag_Pos { tag_POSint = 0, tag_POSlabel = 1, tag_POSadaptive = 2 }; public: }; inline int boxed(const a_Pos * x) { return (unsigned long)x >= 2; } /////////////////////////////////////////////////////////////////////////////// // // Embbeded tag extraction functions // /////////////////////////////////////////////////////////////////////////////// inline int untagp(const a_Pos * x) { return (unsigned long)x & 3; } inline a_Pos * derefp(const a_Pos * x) { return (a_Pos*)((unsigned long)x & ~3); } inline int untag(const a_Pos * x) { return boxed(x) ? untagp(x) + 2 : (int)x; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Pos::POSint // /////////////////////////////////////////////////////////////////////////////// class Pos_POSint : public a_Pos { public: #line 73 "matchcom.ph" int _1; Pos _2; Pos_POSint (int x_1, Pos x_2); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Pos::POSlabel // /////////////////////////////////////////////////////////////////////////////// class Pos_POSlabel : public a_Pos { public: #line 74 "matchcom.ph" Id _1; Pos _2; Pos_POSlabel (Id x_1, Pos x_2); }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Pos::POSadaptive // /////////////////////////////////////////////////////////////////////////////// class Pos_POSadaptive : public a_Pos { public: #line 75 "matchcom.ph" int _1; int * _2; Pos _3; Pos_POSadaptive (int x_1, int * x_2, Pos x_3); }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Pos // /////////////////////////////////////////////////////////////////////////////// extern a_Pos * POSint (int x_1, Pos x_2); extern a_Pos * POSlabel (Id x_1, Pos x_2); extern a_Pos * POSadaptive (int x_1, int * x_2, Pos x_3); #line 76 "matchcom.ph" #line 76 "matchcom.ph" /////////////////////////////////////////////////////////////////////////////// // // Pretty printer for matching trees. // /////////////////////////////////////////////////////////////////////////////// extern std::ostream& operator << (std::ostream&, Match); /////////////////////////////////////////////////////////////////////////////// // // Function to reverse the polarity of a pattern. // /////////////////////////////////////////////////////////////////////////////// extern Polarity rev( Polarity); /////////////////////////////////////////////////////////////////////////////// // // Function to compute the match variables for a list of match expressions. // Match variables are temporaries generated for complex expressions to // prevent redundent evaluations. // /////////////////////////////////////////////////////////////////////////////// extern void compute_match_variables( MatchExps); /////////////////////////////////////////////////////////////////////////////// // // Function to convert a string into an array pattern. This converts string // patterns to be decomposed into a web of character patterns, allowing // (potentially) more efficient matching. // /////////////////////////////////////////////////////////////////////////////// extern Pats make_string_pattern( const char *); /////////////////////////////////////////////////////////////////////////////// // // Functions to decorate the pattern for projection bindings. // These are called to annotate a pattern with pattern variable bindings. // The new bindings are entered into the pattern variable environments. // These are called from the parser. // /////////////////////////////////////////////////////////////////////////////// extern void decor( Pat, Exp, Polarity, Bool, PatternVarEnv&, int&); extern void decor( MatchExps, Pat, Polarity, Bool, PatternVarEnv&, int&); extern void decor( MatchExps&, Pat, PatternVarEnv&, int&, int = -1); /////////////////////////////////////////////////////////////////////////////// // // Functions to decorate the pattern for attribute and cost bindings // inside rewrite rules. These are also called from the parser. // /////////////////////////////////////////////////////////////////////////////// extern int decor_rewrite( Pat, int, int, PatternVarEnv&); extern int decor_rewrite( Pats, int, int, PatternVarEnv&); extern int decor_rewrite( Pat, int, PatternVarEnv&); /////////////////////////////////////////////////////////////////////////////// // // Auxiliary function to retrieve the position vector of a decision tree. // This is used during the pattern matching compilation process. // /////////////////////////////////////////////////////////////////////////////// extern Pos get_pos( Match); /////////////////////////////////////////////////////////////////////////////// // // Auxiliary functions to compute information on a matching tree. // These are used during the pattern matching compilation process to // eliminate redundant tests and for error detection. // /////////////////////////////////////////////////////////////////////////////// Bool refutable( Match); // Is the pattern refutable? void matchables( Match, BitSet&); // Set of matchable rules. void always_matchables( Match, BitSet&); // Set of always matching const BitSet& always_matchables( Match, int); // rules. /////////////////////////////////////////////////////////////////////////////// // // Functions to perform substitutions on expressions. // All INDexp(i) nodes are substituted with the corresponding replacement. // /////////////////////////////////////////////////////////////////////////////// extern Exp subst (Exp, Exp replacements[]); extern Exps subst (Exps, Exp replacements[]); extern LabExps subst (LabExps, Exp replacements[]); /////////////////////////////////////////////////////////////////////////////// // // Hashing and equality for literals. // These are used in the matching tree -> dag conversion process. // /////////////////////////////////////////////////////////////////////////////// extern unsigned int literal_hash (HashTable::Key); extern Bool literal_equal (HashTable::Key, HashTable::Key); /////////////////////////////////////////////////////////////////////////////// // // Hashing and equality for position vectors. // These are used in the matching tree -> dag conversion process. // /////////////////////////////////////////////////////////////////////////////// extern unsigned int pos_hash (HashTable::Key); extern Bool pos_equal (HashTable::Key, HashTable::Key); /////////////////////////////////////////////////////////////////////////////// // // Functions to check for refutability of a pattern. These are used // in the pattern sindexing scheme. // /////////////////////////////////////////////////////////////////////////////// extern Bool is_refutable (Pat); extern Bool is_refutable (Pats); extern Bool is_refutable (LabPats); /////////////////////////////////////////////////////////////////////////////// // // The current index map. This map is computed when using the adaptive // pattern matching scheme. // /////////////////////////////////////////////////////////////////////////////// extern HashTable * current_index_map; /////////////////////////////////////////////////////////////////////////////// // // Methods for compute indexing information of a pattern. These are // used in the adaptive scheme. // /////////////////////////////////////////////////////////////////////////////// extern void indexing (int, Pat, Pos, HashTable&); extern void indexing (int, Pats, Pos, HashTable&); extern void indexing (MatchRules, HashTable&); extern Bool same_selectors; extern Exp select (Exp, Cons, Ty = NOty); /////////////////////////////////////////////////////////////////////////////// // // Equality on expressions. // /////////////////////////////////////////////////////////////////////////////// extern Bool equal (Exp, Exp); extern Bool equal (Exps, Exps); extern Bool equal (LabExps, LabExps); /////////////////////////////////////////////////////////////////////////////// // // Substitution functions on patterns. These are used to implement // pattern laws. // /////////////////////////////////////////////////////////////////////////////// extern Pat subst (Pat, Pat [], Bool); extern Pats subst (Pats, Pat [], Bool); extern LabPats subst (LabPats, Pat [], Bool); /////////////////////////////////////////////////////////////////////////////// // // Methods to translate a match tree into an anotated tree with tree parsing // cost. // /////////////////////////////////////////////////////////////////////////////// extern Match translate_treecost (Match, MatchRules); /////////////////////////////////////////////////////////////////////////////// // // Methods to enter and lookup a pattern constructor. // These interact with the pattern/constructor environment. // Called from the parser. // /////////////////////////////////////////////////////////////////////////////// extern Pat apply_pat (Pat, Pat); /////////////////////////////////////////////////////////////////////////////// // // The following is the interface definition of the pattern matching compiler. // /////////////////////////////////////////////////////////////////////////////// class MatchCompiler : virtual public CodeGen { MatchCompiler(const MatchCompiler&); // no copy constructor void operator = (const MatchCompiler&); // no assignment protected: LabelGen vars, labels; // labels generators int merges, ifs, switches, gotos, goto_labels; // match compiler statistics MatchOptions current_options; MatchRule current_rule; static HashTable quark_map; static LabelGen quark_labels; public: //////////////////////////////////////////////////////////////////////////// // // Constructor and destructor // //////////////////////////////////////////////////////////////////////////// MatchCompiler(); virtual ~MatchCompiler(); static Id quark_name(Id); //////////////////////////////////////////////////////////////////////////// // // Methods to compute the selection/projection function from a datatype // domain. This is used in the pattern binding annotation process. // //////////////////////////////////////////////////////////////////////////// static Exp untag(Exp, Ty); static Exp untag_one(Exp, Cons); static Exp make_select (Exp, Cons, Ty = NOty, Id = 0); static Exp tag_name_of (Cons, Bool normalized); protected: //////////////////////////////////////////////////////////////////////////// // // Methods to compile pattern matching. // //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // // Methods to for translation a pattern into a pattern matching tree. // //////////////////////////////////////////////////////////////////////////// Match trans (Pat, Pos, Bool, Match, Match); Match trans (Pats, int, Pos, Bool, Match, Match); Match trans (Pats, Pos, Bool, Match, Match, int []); Match trans (LabPats, Pos, Bool, Match, Match); Match trans_merge (int, MatchRules, int, Cost *); Match trans_no_merge (int, int, MatchRules, int, Cost *); //////////////////////////////////////////////////////////////////////////// // // Methods to for tree composition/merging and tree to dag conversion. // //////////////////////////////////////////////////////////////////////////// Match compose (Match, Match); Match merge (Match, Match); Match make_dag (Match, MatchOptions, MatchRules); Match match_of (int, MatchRules, MatchOptions); //////////////////////////////////////////////////////////////////////////// // // Methods for generating high level statements and trace instrumentation. // //////////////////////////////////////////////////////////////////////////// void gen_match_stmt (MatchExps, MatchRules, MatchOptions = MATCHnone, Ty = NOty); void gen_fun_def (FunDefs); void gen_match_variables (MatchExps, Ty); void gen (Match, MatchOptions=MATCHnone, Ty=NOty); void gen_matchall_suffix (int, Match, MatchRules, Bool); void gen_match_cost_minimization (int, Match, MatchRules, Bool); void gen_success_match (int, const BitSet *, MatchRules); void gen_cost_success_match (int, const BitSet *, MatchRules); virtual void gen_treecost_match (Match, const BitSet *, MatchRules) = 0; virtual void gen_treelabel_match (Match, Ty, Ty, int) = 0; void instrument_trace (MatchRules); //////////////////////////////////////////////////////////////////////////// // // Method for generating range matching // //////////////////////////////////////////////////////////////////////////// void gen_range_match (Pos, Exp, int, int, Match, Match, Match); //////////////////////////////////////////////////////////////////////////// // // Method for generating view matching // //////////////////////////////////////////////////////////////////////////// void gen_view_match (Id, Exp, Exp, int, Cons [], Match [], Match, TyOpt, TyQual); //////////////////////////////////////////////////////////////////////////// // // Low level methods for specific pattern matching constructs: // C/C++ switches, binary search on literals, regular expression matching, // and quarks matching code. // //////////////////////////////////////////////////////////////////////////// void gen_switch (Id, Exp, Ty, int, Cons [], Match [], Match, int shared, Bool, Bool, TyOpt, Bool); void gen_binary_search_on_literals(Exp, int, Literal [], Match [], Match); void gen_regexp_match (Exp, int, Literal [], Match [], Match, MatchOptions, Ty); void gen_quark_match (Exp, int, Literal [], Match [], Match, MatchOptions); //////////////////////////////////////////////////////////////////////////// // // Methods to generating debugging code. // //////////////////////////////////////////////////////////////////////////// int current_rule_line () const; const char * current_rule_text () const; private: /////////////////////////////////////////////////////////////////////////////// // // Functions for allocating arrays of Literal and Match. // Used during the pattern matching compilation process. // /////////////////////////////////////////////////////////////////////////////// Literal * Literals (int); Match * Matches (int); }; /////////////////////////////////////////////////////////////////////////////// // // Object to mark the current rule // /////////////////////////////////////////////////////////////////////////////// class MarkCurrentRule { MarkCurrentRule(); MarkCurrentRule(const MarkCurrentRule&); void operator = (const MarkCurrentRule&); MatchRule& current_rule; MatchRule old_rule; protected: MarkCurrentRule(MatchRule&, MatchRule); ~MarkCurrentRule(); friend class MatchCompiler; friend class RewritingCompiler; }; #endif #line 426 "matchcom.ph" /* ------------------------------- Statistics ------------------------------- Merge matching rules = yes Number of DFA nodes merged = 0 Number of ifs generated = 0 Number of switches generated = 0 Number of labels = 0 Number of gotos = 0 Adaptive matching = enabled Fast string matching = disabled Inline downcasts = enabled -------------------------------------------------------------------------- */
35.329317
97
0.431359
60c3f2af58bd42c29cff204de6da08888e0f65e5
2,836
h
C
bsp/stm32/stm32mp157a-st-ev1/board/CubeMX_Config/CM4/Inc/openamp_log.h
849679859/rt-thread
a73ae28109c5665739e2728080d20d6863bbc7be
[ "Apache-2.0" ]
7,482
2015-01-01T09:23:08.000Z
2022-03-31T19:34:05.000Z
bsp/stm32/stm32mp157a-st-ev1/board/CubeMX_Config/CM4/Inc/openamp_log.h
849679859/rt-thread
a73ae28109c5665739e2728080d20d6863bbc7be
[ "Apache-2.0" ]
2,543
2015-01-09T02:01:34.000Z
2022-03-31T23:10:14.000Z
bsp/stm32/stm32mp157a-st-ev1/board/CubeMX_Config/CM4/Inc/openamp_log.h
849679859/rt-thread
a73ae28109c5665739e2728080d20d6863bbc7be
[ "Apache-2.0" ]
4,645
2015-01-06T07:05:31.000Z
2022-03-31T18:21:50.000Z
/** ****************************************************************************** * @file log.h * @author MCD Application Team * @brief logging services ****************************************************************************** * * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * * ****************************************************************************** */ /** @addtogroup LOG * @{ */ /** @addtogroup stm32mp1xx_Log * @{ */ /** * @brief Define to prevent recursive inclusion */ #ifndef __LOG_STM32MP1XX_H #define __LOG_STM32MP1XX_H #ifdef __cplusplus extern "C" { #endif /** @addtogroup STM32MP1xx_Log_Includes * @{ */ #include "stm32mp1xx_hal.h" /** * @} */ /** @addtogroup STM32MP1xx_Log_Exported_Constants * @{ */ #if defined (__LOG_TRACE_IO_) #define SYSTEM_TRACE_BUF_SZ 2048 #endif #define LOGQUIET 0 #define LOGERR 1 #define LOGWARN 2 #define LOGINFO 3 #define LOGDBG 4 #ifndef LOGLEVEL #define LOGLEVEL LOGINFO #endif /** * @} */ /** @addtogroup STM32MP1xx_Log_Exported_types * @{ */ #if defined (__LOG_TRACE_IO_) extern char system_log_buf[SYSTEM_TRACE_BUF_SZ]; /*!< buffer for debug traces */ #endif /* __LOG_TRACE_IO_ */ /** * @} */ /** @addtogroup STM32MP1xx_Log_Exported_Macros * @{ */ #if defined (__LOG_TRACE_IO_) || defined(__LOG_UART_IO_) #if LOGLEVEL >= LOGDBG #define log_dbg(fmt, ...) printf("[%05ld.%03ld][DBG ]" fmt, HAL_GetTick()/1000, HAL_GetTick() % 1000, ##__VA_ARGS__) #else #define log_dbg(fmt, ...) #endif #if LOGLEVEL >= LOGINFO #define log_info(fmt, ...) printf("[%05ld.%03ld][INFO ]" fmt, HAL_GetTick()/1000, HAL_GetTick() % 1000, ##__VA_ARGS__) #else #define log_info(fmt, ...) #endif #if LOGLEVEL >= LOGWARN #define log_warn(fmt, ...) printf("[%05ld.%03ld][WARN ]" fmt, HAL_GetTick()/1000, HAL_GetTick() % 1000, ##__VA_ARGS__) #else #define log_warn(fmt, ...) #endif #if LOGLEVEL >= LOGERR #define log_err(fmt, ...) printf("[%05ld.%03ld][ERR ]" fmt, HAL_GetTick()/1000, HAL_GetTick() % 1000, ##__VA_ARGS__) #else #define log_err(fmt, ...) #endif #else #define log_dbg(fmt, ...) #define log_info(fmt, ...) #define log_warn(fmt, ...) #define log_err(fmt, ...) #endif /* __LOG_TRACE_IO_ */ /** * @} */ /** @addtogroup STM32MP1xx_Log_Exported_Functions * @{ */ /** * @} */ #ifdef __cplusplus } #endif #endif /*__LOG_STM32MP1XX_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
21.007407
118
0.582511
8818f42d11a2ee8953fa6dcaa0c0d07a4eb83842
6,212
h
C
lib/libphy/marvell_88x5123/serdes/include/spico.h
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
null
null
null
lib/libphy/marvell_88x5123/serdes/include/spico.h
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
null
null
null
lib/libphy/marvell_88x5123/serdes/include/spico.h
Gateworks/atf-newport
67f418ebe7ee6630f77c3ef7a10b7bf6c15c5ce3
[ "BSD-3-Clause" ]
1
2021-06-12T11:06:26.000Z
2021-06-12T11:06:26.000Z
/* AAPL CORE Revision: 2.1.0 */ /* Copyright 2014 Avago Technologies. All rights reserved. */ /* */ /* This file is part of the AAPL CORE library. */ /* */ /* AAPL CORE is free software: you can redistribute it and/or modify it */ /* under the terms of the GNU Lesser General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* AAPL CORE is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with AAPL CORE. If not, see http://www.gnu.org/licenses. */ /* AAPL (ASIC and ASSP Programming Layer) support for talking with SPICO */ /* processors in SBus master and SerDes slices. */ /** Doxygen File Header */ /** @file */ /** @brief Declarations for SPICO processor functions. */ #ifndef AVAGO_SPICO_H_ #define AVAGO_SPICO_H_ #define AVAGO_SPICO_HALT 2 #ifndef MV_HWS_REDUCED_BUILD_EXT_CM3 typedef enum { AVAGO_SPICO_RESET=0, AVAGO_SPICO_RUNNING=1, AVAGO_SPICO_PAUSE=2, AVAGO_SPICO_ERROR=3 } Avago_spico_state_t; /**@brief SPICO processor status values */ typedef struct { uint enabled; /**< Indicates if processor is enabled and runnning */ uint pc; /**< Program Counter value */ uint revision; /**< Revision of firmware */ uint build; /**< Build ID of firmware */ uint clk; /**< Clock Processor is running on */ Avago_spico_state_t state; /**< State the Processor is in */ } Avago_spico_status_t; #endif /* MV_HWS_REDUCED_BUILD_EXT_CM3 */ #ifndef MV_HWS_REDUCED_BUILD_EXT_CM3 EXT int avago_spico_status( Aapl_t *aapl, uint sbus_addr, Avago_spico_status_t *st); #endif /* MV_HWS_REDUCED_BUILD_EXT_CM3 */ EXT uint avago_spico_running(Aapl_t *aapl, uint sbus_addr); EXT int avago_spico_reset( Aapl_t *aapl, uint sbus_addr); /* uploads SPICO machine code. Returns number of words uploaded */ #ifndef SWIG /* disabling this routine from SWIG access to avoid supporting an unbounded array argument */ EXT void spico_burst_upload(Aapl_t *aapl, uint sbus, uint reg, uint rom_size, const short *rom); EXT int spico_upload_image(Aapl_t *aapl, uint sbus_addr, int words, const short rom[]); EXT int avago_spico_upload_swap_image(Aapl_t *aapl, uint sbus_addr, int words, const short rom[]); EXT int avago_spico_upload(Aapl_t *aapl, uint sbus_addr, BOOL ram_bist, int words, const short rom[]); EXT int avago_firmware_upload(Aapl_t *aapl, uint addr, int serdes_rom_size, const short *serdes_rom, int sbm_rom_size, const short *sbm_rom, int sdi_rom_size, const short *sdi_rom); #endif EXT void avago_spico_wait_for_upload(Aapl_t *aapl, uint sbus_addr); EXT void avago_twi_wait_for_complete(Aapl_t *aapl, uint sbus_addr); #ifndef MV_HWS_REDUCED_BUILD_EXT_CM3 #if AAPL_ENABLE_FILE_IO EXT int avago_load_rom_from_file(Aapl_t *aapl, const char *filename, int *rom_size, short **rom); EXT int avago_firmware_upload_file(Aapl_t *aapl, uint addr, const char *serdes_rom_file, const char *sbm_rom_file, const char *sdi_rom_file); EXT char *avago_find_swap_file(Aapl_t *aapl, const char *filename); EXT int avago_spico_upload_file(Aapl_t *aapl, uint sbus_addr, BOOL ram_bist, const char *filename); #endif #endif /* MV_HWS_REDUCED_BUILD_EXT_CM3 */ /* executes a serdes interrupt */ EXT uint avago_spico_int(Aapl_t *aapl, uint sbus_addr, int int_num, int param); #ifndef MV_HWS_REDUCED_BUILD EXT BOOL avago_spico_int_check_full(Aapl_t *aapl, const char *caller, int line, uint addr, int int_num, int param); #else EXT BOOL avago_spico_int_check_reduce(Aapl_t *aapl, uint addr, int int_num, int param); #endif /* MV_HWS_REDUCED_BUILD */ #ifndef MV_HWS_REDUCED_BUILD_EXT_CM3 EXT uint avago_spico_broadcast_int(Aapl_t *aapl, int int_num, int param, int args, ...); EXT uint avago_spico_broadcast_int_w_mask(Aapl_t *aapl, uint addr_mask, int int_num, int param, int args, ...); typedef enum { AVAGO_SPICO_INT_ALL=0, AVAGO_SPICO_INT_FIRST=1, AVAGO_SPICO_INT_NOT_FIRST=2 } Avago_spico_int_flags_t; typedef struct { int interrupt; int param; int ret; Avago_spico_int_flags_t flags; } Avago_spico_int_t; #endif /* MV_HWS_REDUCED_BUILD_EXT_CM3 */ #ifndef MV_HWS_REDUCED_BUILD EXT int avago_spico_int_array(Aapl_t *aapl, uint sbus_addr, int num_elements, Avago_spico_int_t *interrupts); #endif /* MV_HWS_REDUCED_BUILD */ EXT uint avago_firmware_get_rev( Aapl_t *aapl, uint sbus_addr); EXT uint avago_firmware_get_build_id(Aapl_t *aapl, uint sbus_addr); EXT uint avago_spico_crc( Aapl_t *aapl, uint sbus_addr); /* TBD write code for sram_reset */ EXT int avago_spico_ram_bist( Aapl_t *aapl, uint sbus_addr); #ifndef MV_HWS_REDUCED_BUILD # if AAPL_ENABLE_USER_SERDES_INT EXT unsigned int user_supplied_serdes_interrupt_function( Aapl_t *aapl, uint sbus_addr, int int_num, int param); # endif #endif /* MV_HWS_REDUCED_BUILD */ # ifdef AAPL_ENABLE_INTERNAL_FUNCTIONS EXT void aapl_crc_one_byte(int *crc_ptr, int value); EXT int aapl_crc_rom(short *memory, int length); EXT int avago_spico_halt(Aapl_t *aapl, uint addr); EXT int avago_spico_resume(Aapl_t *aapl, uint addr, int spico_run_state); # endif #endif
44.690647
115
0.660174
b080cd82d93c876570c895040b7edcb16a5c9e2c
12,935
h
C
source/Motel/motel.types.t.h
autopulous/innkeeper
4b5babf3bd154c1f2d3db82e1f5949fd7006ba61
[ "MIT" ]
null
null
null
source/Motel/motel.types.t.h
autopulous/innkeeper
4b5babf3bd154c1f2d3db82e1f5949fd7006ba61
[ "MIT" ]
null
null
null
source/Motel/motel.types.t.h
autopulous/innkeeper
4b5babf3bd154c1f2d3db82e1f5949fd7006ba61
[ "MIT" ]
null
null
null
/*---------------------------------------------------------------------------- Motel Types application programmer's types (APT) header file ---------------------------------------------------------------------------- Copyright 2010-2012 John L. Hart IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain all copyright notices, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce all copyright notices, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY John L. Hart IV "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL John L. Hart IV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of John L Hart IV. ----------------------------------------------------------------------------*/ #ifndef MOTEL_TYPES_T_H #define MOTEL_TYPES_T_H #include <stddef.h> #include <stdio.h> #include "motel.signal.t.h" #ifdef NULL #undef NULL #endif #define NULL ((void *) 0) /* ** The byte type */ typedef unsigned char byte; /* ** bit bucket types */ #if defined _WIN32 || defined _WIN64 typedef unsigned char bits8; typedef unsigned short bits16; typedef unsigned long bits32; typedef unsigned long long bits64; #else #error need to define bit bucket types for this compiler/architecture #endif /* ** Used to reference an item count */ typedef size_t count; /* ** Used to reference an item index */ typedef size_t index; /* ** The boolean (Boolean) type */ typedef bits8 boolean; #ifdef FALSE #undef FALSE #endif #define FALSE ((boolean)(1 != 1)) #ifdef TRUE #undef TRUE #endif #define TRUE ((boolean)(1 == 1)) /* ** Function return values */ typedef boolean success; /* ** The jumping constructs */ #define same goto reprocess /* should be within a looping construct */ #define next goto iterator /* should be within a looping or try/catch construct */ #define what goto sorry /* should be within a looping construct */ #define fail goto failure /* may be within a looping or try/catch construct */ #define done goto complete /* may be within a looping or try/catch construct */ /* ** The looping constructs */ #define loop for(;;) #define escape(expression) if (expression) break /* ** The try/catch constructs */ #define attempt for(;;) #define exception(expression) if (expression) break /* ** */ /* #define __log_none__ 0 #define __log_errors__ 1 #define __log_warnings__ 2 #define __log_trace__ 4 #define __log_user__ 8 int __log_level__ = __log_none__; FILE * __log_file_stream__ = (FILE *) NULL; #define logging_active (NULL != (void *) __log_file_stream__ && __log_none__ != __log_level__) */ /* ** The lem (Less than, Equal, More than) type */ typedef signed char lem; #ifdef LESS_THAN #undef LESS_THAN #endif #define LESS_THAN ((lem) -1) #ifdef EQUAL_TO #undef EQUAL_TO #endif #define EQUAL_TO ((lem) 0) #ifdef MORE_THAN #undef MORE_THAN #endif #define MORE_THAN ((lem) 1) /* ** The autopulation mode specifiers */ typedef unsigned int autopulation; #ifdef CATENATE #undef CATENATE #endif #define CATENATE ((autopulation) (0<<0)) /* spread existing nodes and insert */ #ifdef EXCISE #undef EXCISE #endif #define EXCISE ((autopulation) (1<<0)) /* remove existing nodes and insert */ #ifdef COPY #undef COPY #endif #define COPY ((autopulation) (0<<1)) /* copy and preserve nodes */ #ifdef MOVE #undef MOVE #endif #define MOVE ((autopulation) (1<<1)) /* copy and destroy nodes */ /* ** Interfaces */ typedef void (* _MotelFunctionPointer)(void); /*------------------------------------------------------------------------------------------------------*/ /* Resource References */ /*------------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------------*/ /* Hierarchical Resource Reference (HRR) */ /* */ /* 154.211.100.76:8080$https/delta\ws\listserver1@johnhart:mysecret?weekly=on;when=friday#public */ /* or */ /* org.speakhuman:8080$https/beta\ws/script.motel@johnhart:mysecret?debug=on;action=parse#strict */ /* \_________________/\____/\___________________/\________________/\____________________/\_____/ */ /* device scheme resource credentials query fragment */ /* \____________/\___/ \_______/\_______/ */ /* host port identity password */ /*------------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------------*/ /* Uniform Resource Locator (URL) structure */ /* */ /* https://johnhart:mysecret@www.speakhuman.org:8080/beta/ws/script.motel?debug=on;action=parse#strict */ /* \___/ \_______________________________________/\___________________/ \___________________/ \____/ */ /* scheme authority resource path query fragment */ /* \_______________/ \________________/ \__/ \____________/ */ /* credentials host port resource name */ /* \______/ \______/ \__/ */ /* username password resource extension */ /*------------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------------*/ /* Local File Reference (LFR) */ /* */ /* script */ /* or */ /* script.motel */ /* or */ /* ../script.motel */ /* or */ /* ..\script.motel */ /* or */ /* /beta\ws/script.motel */ /* or */ /* c:/beta\ws\script.motel */ /* \/\___________________/ */ /* drive resource path */ /* \__________/ */ /* resource name */ /* \___/ */ /* resource extension */ /*------------------------------------------------------------------------------------------------------*/ #define MOTEL_RESOURCE_EXTENSION_SIZE 128 #define MOTEL_EXTENSION_DELIMITER_SIZE 8 #define MOTEL_RESOURCE_NAME_SIZE (512 + MOTEL_RESOURCE_EXTENSION_SIZE) #define MOTEL_RESOURCE_NAME_DELIMITER_SIZE 8 #define MOTEL_RESOURCE_PATH_SIZE (1024 + MOTEL_RESOURCE_NAME_SIZE) #define MOTEL_HOST_DELIMITER_SIZE 8 #define MOTEL_HOST_SIZE 1024 #define MOTEL_PORT_DELIMITER_SIZE 8 #define MOTEL_PORT_SIZE 16 #define MOTEL_DEVICE_SIZE (MOTEL_HOST_SIZE + \ MOTEL_PORT_DELIMITER_SIZE + MOTEL_PORT_SIZE) #define MOTEL_SCHEME_DELIMITER_SIZE 8 #define MOTEL_SCHEME_SIZE 32 #define MOTEL_RESOURCE_REFERENCE_DELIMITER_SIZE 8 #define MOTEL_RESOURCE_REFERENCE_SIZE MOTEL_RESOURCE_PATH_SIZE #define MOTEL_CREDENTIALS_DELIMITER_SIZE 8 #define MOTEL_USERNAME_DELIMITER_SIZE 8 #define MOTEL_IDENTITY_SIZE 1024 #define MOTEL_USERNAME_SIZE MOTEL_IDENTITY_SIZE #define MOTEL_PASSWORD_DELIMITER_SIZE 8 #define MOTEL_PASSWORD_SIZE 1024 #define MOTEL_CREDENTIALS_SIZE (MOTEL_CREDENTIALS_DELIMITER_SIZE + MOTEL_IDENTITY_SIZE + \ MOTEL_PASSWORD_DELIMITER_SIZE + MOTEL_PASSWORD_SIZE) #define MOTEL_AUTHORITY_SIZE (MOTEL_CREDENTIALS_SIZE + \ MOTEL_HOST_DELIMITER_SIZE + MOTEL_HOST_SIZE + \ MOTEL_PORT_DELIMITER_SIZE + MOTEL_PORT_SIZE) #define MOTEL_QUERY_DELIMITER_SIZE 8 #define MOTEL_QUERY_SIZE 4096 #define MOTEL_FRAGMENT_DELIMITER_SIZE 8 #define MOTEL_FRAGMENT_SIZE 4096 #define MOTEL_HRR_SIZE (MOTEL_HOST_SIZE + \ MOTEL_PORT_DELIMITER_SIZE + MOTEL_PORT_SIZE + \ MOTEL_SCHEME_DELIMITER_SIZE + MOTEL_SCHEME_SIZE + \ MOTEL_RESOURCE_REFERENCE_DELIMITER_SIZE + MOTEL_RESOURCE_REFERENCE_SIZE + \ MOTEL_CREDENTIALS_DELIMITER_SIZE + MOTEL_IDENTITY_SIZE + \ MOTEL_PASSWORD_DELIMITER_SIZE + MOTEL_PASSWORD_SIZE + \ MOTEL_QUERY_DELIMITER_SIZE + MOTEL_QUERY_SIZE + \ MOTEL_FRAGMENT_DELIMITER_SIZE + MOTEL_FRAGMENT_SIZE) #define MOTEL_URL_SIZE (MOTEL_SCHEME_SIZE + MOTEL_SCHEME_DELIMITER_SIZE + \ MOTEL_CREDENTIALS_DELIMITER_SIZE + MOTEL_USERNAME_SIZE + \ MOTEL_PASSWORD_DELIMITER_SIZE + MOTEL_PASSWORD_SIZE + \ MOTEL_HOST_DELIMITER_SIZE + MOTEL_HOST_SIZE + \ MOTEL_PORT_DELIMITER_SIZE + MOTEL_PORT_SIZE + \ MOTEL_RESOURCE_REFERENCE_DELIMITER_SIZE + MOTEL_RESOURCE_PATH_SIZE + \ MOTEL_QUERY_DELIMITER_SIZE + MOTEL_QUERY_SIZE + \ MOTEL_FRAGMENT_DELIMITER_SIZE + MOTEL_FRAGMENT_SIZE) #define MOTEL_DRIVE_REFERENCE_SIZE 8 #define MOTEL_DRIVE_REFERENCE_DELIMITER_SIZE 8 #define MOTEL_FILE_REFERENCE_SIZE (MOTEL_DRIVE_REFERENCE_SIZE + MOTEL_DRIVE_REFERENCE_DELIMITER_SIZE + \ MOTEL_RESOURCE_REFERENCE_DELIMITER_SIZE + MOTEL_RESOURCE_REFERENCE_SIZE) #define X__X "----------------------------------------------------------------------------" #endif
40.421875
109
0.487824
522aef54d2066886fb8211bc24ad7a6732fc3fbd
2,211
h
C
homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.h
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.h
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
homeworks/NonLinSchroedingerEquation/templates/nonlinschroedingerequation.h
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
null
null
null
#ifndef NONLINSCHROEDINGEREQUATION_H_ #define NONLINSCHROEDINGEREQUATION_H_ /** * @file nonlinschroedingerequation.h * @brief NPDE homework NonLinSchroedingerEquation code * @author Oliver Rietmann * @date 22.04.2020 * @copyright Developed at ETH Zurich */ #include <Eigen/Core> #include <Eigen/SparseCore> #include <lf/mesh/mesh.h> namespace NonLinSchroedingerEquation { /** @brief Class providing the local element matrix needed for assembly. * It satisfies the LehrFEM++ concept EntityMatrixProvider. */ class MassElementMatrixProvider { public: /** @brief Default implement: all cells are active */ bool isActive(const lf::mesh::Entity &cell) { return true; } /** @brief routine for the computation of element matrices * @param cell reference to the triangular cell for * which the element matrix should be computed. * @return element matrix */ Eigen::Matrix3d Eval(const lf::mesh::Entity &cell); }; /** @brief Computes the $L^2(\mathbb{R^2;\mathbb{C}})$-norm, approximated by 2D * trapezoidal rule. * @param mu vector of length $N$ containing nodal values * @param D real mass matrix of shape $N \times N$ * @return $L^2$-norm of the complex-valued mesh function represented by mu */ double Norm(const Eigen::VectorXcd &mu, const Eigen::SparseMatrix<double> &D); /** @brief Computes the kinetic energy. * @param mu vector of length $N$ containing nodal values * @param A Galerkin matrix of $-\Delta$ (stiffness matrix) of shape $N \times * N$ * @return kinetic energy of the complex-valued mesh function associated with * mu */ double KineticEnergy(const Eigen::VectorXcd &mu, const Eigen::SparseMatrix<double> &A); /** @brief Computes the interaction energy (i.e. energy associated with the * non-linear term). * @param mu vector of length $N$ containing nodal values * @param D real mass matrix of shape $N \times N$ * @return interaction energy of the complex-valued mesh function associated * with mu */ double InteractionEnergy(const Eigen::VectorXcd &mu, const Eigen::SparseMatrix<double> &D); } // namespace NonLinSchroedingerEquation #endif // NONLINSCHROEDINGEREQUATION_H_
34.015385
79
0.71687
52c53d9f019283802d13f4c32763598a94e10609
2,577
c
C
gemmini/software/gemmini-rocc-tests/bareMetalC/tiled_matmul_ws_perf.c
BiEchi/chipyard
c23937d72624f8b57551f106fd225d1004bebb44
[ "Apache-2.0" ]
4
2021-09-30T13:40:44.000Z
2022-03-15T12:40:14.000Z
gemmini/software/gemmini-rocc-tests/bareMetalC/tiled_matmul_ws_perf.c
BiEchi/chipyard
c23937d72624f8b57551f106fd225d1004bebb44
[ "Apache-2.0" ]
null
null
null
gemmini/software/gemmini-rocc-tests/bareMetalC/tiled_matmul_ws_perf.c
BiEchi/chipyard
c23937d72624f8b57551f106fd225d1004bebb44
[ "Apache-2.0" ]
null
null
null
// See LICENSE for license details. #include <stdint.h> #include <stddef.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #ifndef BAREMETAL #include <sys/mman.h> #endif #include "include/gemmini_testutils.h" #define NO_BIAS 0 #define REPEATING_BIAS 1 #define A_TRANSPOSE 0 #define B_TRANSPOSE 0 #ifndef BAREMETAL #define MAT_DIM_I 512 #define MAT_DIM_K 512 #define MAT_DIM_J 512 #else // #define MAT_DIM_I 128 // #define MAT_DIM_K 128 // #define MAT_DIM_J 128 #define MAT_DIM_I 256 #define MAT_DIM_K 256 #define MAT_DIM_J 256 // #define MAT_DIM_I 256 // #define MAT_DIM_K 512 // #define MAT_DIM_J 512 #endif #if A_TRANSPOSE==0 #define A_STRIDE MAT_DIM_K #else #define A_STRIDE MAT_DIM_I #endif #if B_TRANSPOSE==0 #define B_STRIDE MAT_DIM_J #else #define B_STRIDE MAT_DIM_K #endif int main() { #ifndef BAREMETAL if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) { perror("mlockall failed"); exit(1); } #endif gemmini_flush(0); #if A_TRANSPOSE==0 static elem_t full_A[MAT_DIM_I][MAT_DIM_K] row_align(1); #else static elem_t full_A[MAT_DIM_K][MAT_DIM_I] row_align(1); #endif #if B_TRANSPOSE==0 static elem_t full_B[MAT_DIM_K][MAT_DIM_J] row_align(1); #else static elem_t full_B[MAT_DIM_J][MAT_DIM_K] row_align(1); #endif static elem_t full_C[MAT_DIM_I][MAT_DIM_J] row_align(1); static acc_t full_D[MAT_DIM_I][MAT_DIM_J] row_align_acc(1); static full_t gold_full[MAT_DIM_I][MAT_DIM_J]; static elem_t gold[MAT_DIM_I][MAT_DIM_J]; printf("Starting gemmini matmul\n"); printf("I: %d, J: %d, K: %d\n", MAT_DIM_I, MAT_DIM_J, MAT_DIM_K); printf("NO_BIAS: %d, REPEATING_BIAS: %d\n", NO_BIAS, REPEATING_BIAS); printf("A_TRANSPOSE: %d, B_TRANSPOSE: %d\n", A_TRANSPOSE, B_TRANSPOSE); unsigned long start = read_cycles(); tiled_matmul_auto(MAT_DIM_I, MAT_DIM_J, MAT_DIM_K, (elem_t*)full_A, (elem_t*)full_B, NO_BIAS ? NULL : &full_D[0][0], (elem_t*)full_C, A_STRIDE, B_STRIDE, MAT_DIM_J, MAT_DIM_J, MVIN_SCALE_IDENTITY, MVIN_SCALE_IDENTITY, MVIN_SCALE_IDENTITY, NO_ACTIVATION, ACC_SCALE_IDENTITY, 0, REPEATING_BIAS, A_TRANSPOSE, B_TRANSPOSE, false, false, 3, WS); unsigned long end = read_cycles(); printf("Cycles taken: %u\n", end-start); const int total_macs = MAT_DIM_I * MAT_DIM_J * MAT_DIM_K; const int ideal_cycles = total_macs / (DIM * DIM); const int utilization = 100 * ideal_cycles / (end-start); printf("Utilization: %d%%\n", utilization); exit(0); }
24.311321
94
0.694606