blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
492b704e2907266bf09138373fae44c0c934fb48
e023a2bd92905516579c089ae7c09b2b200f7661
/Volume 119/11908 - Skyscraper.cpp
c8bf9c612d6d04fa178296d1b09cfe93ac7d4cea
[]
no_license
jayzhan211/UVa-Online-Judge
0b83bad15e7813b767aec920db1012cc997310f0
881dfc7ac3c4921402589e8764239078fd0bc096
refs/heads/master
2021-10-20T19:09:04.841009
2019-03-01T07:34:05
2019-03-01T07:34:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,978
cpp
11908 - Skyscraper.cpp
#include <bits/stdc++.h> #define LL long long #define Accel ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); #define Re(a,b) memset(a,b,sizeof a) #define F first #define S second #define MP make_pair #define PB push_back #define ALL(X) (X).begin(), (X).end() #define FOR(I, A, B) for (int I = (A); I <= (B); I++) #define REP(I, N) for (int I = 0; I < (N); I++) #define PII pair<int,int> #define PLL pair<LL,LL> #define SZ(a) ((int)a.size()) //#pragma GCC optimize(2) using namespace std; const int N=1e6+1; const int M=998244353; const double eps=1e-6; typedef complex<double>C; const double PI(acos(-1.0)); //for(int mask=i;mask>0;mask=(mask-1)&i) //int a[25]= { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; //__gcd, atan2(y,x)=y/x , __int128 //c(n,k)=c(n-1,k-1)+c(n-1,k) //c(i,r),i for r to n =c(n+1,r+1) //void add(int x){while(x<N)BIT[x]++,x+=x&-x;} //void add(int x){while(x<N)BIT[x]++,x+=x&-x;} //int sum(int x){int t=0;while(x){t+=BIT[x];x-=x&-x;}return t;} //LL pw(LL a,LL b){LL t=1;for(;b;b>>=1,a=a*a%M)b&1?t=t*a%M:0;return t;} //log() = ln() , log(x)/log(y)=log(y)-base-x //INT_MAX 127,INT_MIN 128 //int dw[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; //int dw[8][2]={{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}}; //cout<<fixed<<setprecision(12)<<ans<<endl; //__builtin_popcount(mask) int t,n; struct LW{ int l,r,c; }d[N]; bool cmp(LW a,LW b){ return a.r<b.r||(a.r==b.r&&a.c>b.c); } int f[N]; int main(){ // freopen("01.txt","w",stdout); int tc=0; cin>>t; while(t--){ for(int i=0;i<=200005;i++) f[i]=0; cin>>n; for(int i=0;i<n;i++){ cin>>d[i].l>>d[i].r>>d[i].c; d[i].l++,d[i].r+=d[i].l-1; } sort(d,d+n,cmp); int j=0; for(int i=1;i<=200005;i++){ f[i]=f[i-1]; while(j<n&&d[j].r==i){ f[i]=max(f[i],f[max(d[j].l-1,0)]+d[j].c); j++; } } // cout<<f[100000]<<endl; printf("Case %d: %d\n",++tc,f[200001]); } } /* 12345 234567890 xxxxxx */
0229409bf21e4e3aed98f0e35877f3c6205ce4d1
1e9319334bd9e639e9934e65073adde180bdc1bd
/Volume/BsplineVolume3d.cpp
66b161eb2032ceba9d7b87ca1e0c6d80c2653b04
[]
no_license
SonSang/MinuteFreeform
39d8763195cd1e4654996a9baf339f0b058a2e03
766f04615450ec986e376f9aa60ba8c0af1ad835
refs/heads/master
2023-01-03T15:56:28.811028
2020-11-02T14:30:54
2020-11-02T14:30:54
283,128,226
2
1
null
null
null
null
UTF-8
C++
false
false
10,347
cpp
BsplineVolume3d.cpp
/* ******************************************************************************************* * Author : Sang Hyun Son * Email : shh1295@gmail.com * Github : github.com/SonSang ******************************************************************************************* */ #include "BsplineVolume3d.h" #include <map> namespace MN { // BsplineVolume3d void BsplineVolume3d::insertKnot(int direction, Real knot) { auto& knotVector = (direction == 0 ? uKnot : (direction == 1 ? vKnot : wKnot)); int k = 0, knotSize = (int)knotVector.size(); // 1. Find [k] such that holds [ knot ] in between : knotVector[k] <= knot < knotVector[k+1] k = -1; for (int i = 0; i < knotSize; i++) { if (i == knotSize - 1) break; if (knotVector[i] <= knot && knotVector[i + 1] > knot) k = i; } if (k == -1) throw(std::runtime_error("Invalid knot value for knot insertion")); int degree = (direction == 0 ? uDegree : (direction == 1 ? vDegree : wDegree)), uSize = (int)cpts.size(), vSize = (int)cpts[0].size(), wSize = (int)cpts[0][0].size(), nSize = (direction == 0 ? uSize + 1 : (direction == 1 ? vSize + 1 : wSize + 1)); Real * a = nullptr; std::vector<double> alpha(nSize, 0.0); // 2. Build alpha vector for (int i = 0; i < nSize; i++) { a = &alpha[i]; double kvA = knotVector[i], kvB = knotVector[i + degree]; if (i <= k - degree) *a = 1.0; else if (i >= k + 1) *a = 0.0; else *a = (knot - kvA) / (kvB - kvA); } // 3. Create new knot vector int nKnotSize = knotSize + 1; KnotVector nKnotVector; for (int i = 0; i < nKnotSize; i++) { if (i < k + 1) nKnotVector.push_back(knotVector[i]); else if (i == k + 1) nKnotVector.push_back(knot); else nKnotVector.push_back(knotVector[i - 1]); } knotVector = nKnotVector; // 4. Create new control points int nuSize = uSize, nvSize = vSize, nwSize = wSize; if (direction == 0) nuSize++; else if (direction == 1) nvSize++; else nwSize++; ControlPoints nCpts; nCpts.resize(nuSize); for (int i = 0; i < nuSize; i++) { nCpts[i].resize(nvSize); for (int j = 0; j < nvSize; j++) { nCpts[i][j].resize(nwSize); } } if (direction == 0) { for (int j = 0; j < nvSize; j++) { for (int k = 0; k < nwSize; k++) { for (int i = 0; i < nuSize; i++) { Vec3 tmp0 = { 0.0, 0.0, 0.0 }, tmp1 = { 0.0, 0.0, 0.0 }; if (i < uSize) tmp0 = cpts[i][j][k] * alpha[i]; if (i > 0) tmp1 = cpts[i - 1][j][k] * (1 - alpha[i]); nCpts[i][j][k] = tmp0 + tmp1; } } } } else if (direction == 1) { for (int i = 0; i < nuSize; i++) { for (int k = 0; k < nwSize; k++) { for (int j = 0; j < nvSize; j++) { Vec3 tmp0 = { 0.0, 0.0, 0.0 }, tmp1 = { 0.0, 0.0, 0.0 }; if (j < vSize) tmp0 = cpts[i][j][k] * alpha[j]; if (j > 0) tmp1 = cpts[i][j - 1][k] * (1 - alpha[j]); nCpts[i][j][k] = tmp0 + tmp1; } } } } else { for (int i = 0; i < nuSize; i++) { for (int j = 0; j < nvSize; j++) { for (int k = 0; k < nwSize; k++) { Vec3 tmp0 = { 0.0, 0.0, 0.0 }, tmp1 = { 0.0, 0.0, 0.0 }; if (k < wSize) tmp0 = cpts[i][j][k] * alpha[k]; if (k > 0) tmp1 = cpts[i][j][k - 1] * (1 - alpha[k]); nCpts[i][j][k] = tmp0 + tmp1; } } } } cpts = nCpts; } void BsplineVolume3d::insertKnotFull(int direction) { auto& knotVector = ((direction == 0) ? uKnot : (direction == 1 ? vKnot : wKnot)); auto degree = ((direction == 0) ? uDegree : (direction == 1 ? vDegree : wDegree)); std::map<Real, int> insertionTime; Real beg = knotVector.front(); Real end = knotVector.back(); Real prevKnot = beg; int multiplicity = 0; for (int i = 1; i < knotVector.size(); i++) { if (knotVector[i] == prevKnot) multiplicity++; else { if (prevKnot == beg) insertionTime.insert({ prevKnot, degree - multiplicity }); else insertionTime.insert({ prevKnot, degree - 1 - multiplicity }); multiplicity = 0; } prevKnot = knotVector[i]; } for (auto& insertion : insertionTime) { for (int i = 0; i < insertion.second; i++) insertKnot(direction, insertion.first); } } BsplineVolume3d BsplineVolume3d::create(int uDegree, int vDegree, int wDegree, const KnotVector& uKnot, const KnotVector& vKnot, const KnotVector& wKnot, const ControlPoints& cpts) { BsplineVolume3d volume; volume.uDegree = uDegree; volume.vDegree = vDegree; volume.wDegree = wDegree; volume.uKnot = uKnot; volume.uDomain.set(uKnot.front(), uKnot.back()); volume.vKnot = vKnot; volume.vDomain.set(vKnot.front(), vKnot.back()); volume.wKnot = wKnot; volume.wDomain.set(wKnot.front(), wKnot.back()); volume.cpts = cpts; volume.updatePatches(); return volume; } BsplineVolume3d::Ptr BsplineVolume3d::createPtr(int uDegree, int vDegree, int wDegree, const KnotVector& uKnot, const KnotVector& vKnot, const KnotVector& wKnot, const ControlPoints& cpts) { return std::make_shared<BsplineVolume3d>(create(uDegree, vDegree, wDegree, uKnot, vKnot, wKnot, cpts)); } void BsplineVolume3d::updatePatches() { // Insert knots in all directions insertKnotFull(0); insertKnotFull(1); insertKnotFull(2); patches.clear(); int uPatchNum = 0; int vPatchNum = 0; int wPatchNum = 0; std::vector<double> uniqueKnotsU = { uKnot[0] }; std::vector<double> uniqueKnotsV = { vKnot[0] }; std::vector<double> uniqueKnotsW = { wKnot[0] }; double prevKnot = uKnot[0]; for (auto knot : uKnot) { if (knot != prevKnot) { uPatchNum++; prevKnot = knot; uniqueKnotsU.push_back(knot); } } prevKnot = vKnot[0]; for (auto knot : vKnot) { if (knot != prevKnot) { vPatchNum++; prevKnot = knot; uniqueKnotsV.push_back(knot); } } prevKnot = wKnot[0]; for (auto knot : wKnot) { if (knot != prevKnot) { wPatchNum++; prevKnot = knot; uniqueKnotsW.push_back(knot); } } patches.reserve(uPatchNum * vPatchNum * wPatchNum); int uIndexA = 0, uIndexB = uDegree; int vIndexA = 0, vIndexB = vDegree; int wIndexA = 0, wIndexB = wDegree; for (int i = 0; i < uPatchNum; i++) { Domain uSubdomain = Domain::create(uniqueKnotsU[i], uniqueKnotsU[i + 1]); for (int j = 0; j < vPatchNum; j++) { Domain vSubdomain = Domain::create(uniqueKnotsV[j], uniqueKnotsV[j + 1]); for (int k = 0; k < wPatchNum; k++) { Domain wSubdomain = Domain::create(uniqueKnotsW[k], uniqueKnotsW[k + 1]); ControlPoints bezCpts; bezCpts.resize(uDegree + 1); for (int p = uIndexA; p <= uIndexB; p++) { bezCpts[p - uIndexA].resize(vDegree + 1); for (int q = vIndexA; q <= vIndexB; q++) { bezCpts[p - uIndexA][q - vIndexA].resize(wDegree + 1); for (int r = wIndexA; r <= wIndexB; r++) { bezCpts[p - uIndexA][q - vIndexA][r - wIndexA] = cpts[p][q][r]; } } } Patch patch; patch.uSubdomain = uSubdomain; patch.vSubdomain = vSubdomain; patch.wSubdomain = wSubdomain; patch.patch = BezierVolume3d::createPtr(uDegree, vDegree, wDegree, bezCpts); patches.push_back(patch); wIndexA += wDegree; wIndexB += wDegree; } vIndexA += vDegree; vIndexB += vDegree; wIndexA = 0; wIndexB = wDegree; } uIndexA += uDegree; uIndexB += uDegree; vIndexA = 0; vIndexB = vDegree; wIndexA = 0; wIndexB = wDegree; } } Vec3 BsplineVolume3d::evaluate(Real u, Real v, Real w) const { for (const auto& patch : patches) { if (patch.domainHas(u, v, w)) { Real nu = (u - patch.uSubdomain.beg()) / patch.uSubdomain.width(); Real nv = (v - patch.vSubdomain.beg()) / patch.vSubdomain.width(); Real nw = (w - patch.wSubdomain.beg()) / patch.wSubdomain.width(); return patch.patch->evaluate(nu, nv, nw); } } throw(std::runtime_error("Invalid parameter for Bspline surface evaluation")); } Vec3 BsplineVolume3d::differentiate(Real u, Real v, Real w, int uOrder, int vOrder, int wOrder) const { for (const auto& patch : patches) { if (patch.domainHas(u, v, w)) { Real uWidth, vWidth, wWidth; uWidth = patch.uSubdomain.width(); vWidth = patch.vSubdomain.width(); wWidth = patch.wSubdomain.width(); Real nu = (u - patch.uSubdomain.beg()) / uWidth; Real nv = (v - patch.vSubdomain.beg()) / vWidth; Real nw = (w - patch.wSubdomain.beg()) / wWidth; auto vec = patch.patch->differentiate(nu, nv, nw, uOrder, vOrder, wOrder); if (uOrder == 1 && vOrder == 0 && wOrder == 0) vec /= uWidth; else if (uOrder == 0 && vOrder == 1 && wOrder == 0) vec /= vWidth; else if (uOrder == 0 && vOrder == 0 && wOrder == 1) vec /= wWidth; else if (uOrder == 2 && vOrder == 0 && wOrder == 0) vec /= SQ(uWidth); else if (uOrder == 1 && vOrder == 1 && wOrder == 0) vec /= (uWidth * vWidth); else if (uOrder == 1 && vOrder == 0 && wOrder == 1) vec /= (uWidth * wWidth); else if (uOrder == 0 && vOrder == 2 && wOrder == 0) vec /= SQ(vWidth); else if (uOrder == 0 && vOrder == 1 && wOrder == 1) vec /= (vWidth * wWidth); else if (uOrder == 0 && vOrder == 0 && wOrder == 2) vec /= SQ(wWidth); else if (uOrder == 3 && vOrder == 0 && wOrder == 0) vec /= (uWidth * uWidth * uWidth); else if (uOrder == 2 && vOrder == 1 && wOrder == 0) vec /= (uWidth * uWidth * vWidth); else if (uOrder == 2 && vOrder == 0 && wOrder == 1) vec /= (uWidth * uWidth * wWidth); else if (uOrder == 1 && vOrder == 2 && wOrder == 0) vec /= (uWidth * vWidth * vWidth); else if (uOrder == 1 && vOrder == 1 && wOrder == 1) vec /= (uWidth * vWidth * wWidth); else if (uOrder == 1 && vOrder == 0 && wOrder == 2) vec /= (uWidth * wWidth * wWidth); else if (uOrder == 0 && vOrder == 3 && wOrder == 0) vec /= (vWidth * vWidth * vWidth); else if (uOrder == 0 && vOrder == 2 && wOrder == 1) vec /= (vWidth * vWidth * wWidth); else if (uOrder == 0 && vOrder == 1 && wOrder == 2) vec /= (vWidth * wWidth * wWidth); else if (uOrder == 0 && vOrder == 0 && wOrder == 3) vec /= (wWidth * wWidth * wWidth); return vec; } } throw(std::runtime_error("Invalid parameter for Bspline surface differentiation")); } }
fa89f36830bc68f89dde496fced90506623005fa
3d3585a64e7020ab5dbda98f52e2f61992d6bf65
/atomicclass.cpp
0d7066dccb89e740e36d6b914bee161ee49e6889
[]
no_license
LokeshVarman/CPP-11
9a005f07951cb5940e7128be16c0edd779a57619
20f5c0be9a2a7ed79e1d5fa2ceeb4f66a20f3295
refs/heads/master
2023-03-18T10:39:29.625167
2021-03-15T11:34:32
2021-03-15T11:34:32
336,976,890
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
atomicclass.cpp
#include <iostream> #include <thread> #include <atomic> using namespace std; atomic<int> sharedData; void consumer() { while(sharedData == 0) this_thread::yield(); cout << "Shared data consumed is: "<< sharedData <<endl; } void producer(int d) { while(sharedData != 0) this_thread::yield(); sharedData = d; } int main() { thread consumers[5], producers[5]; for(int i=0;i<5;i++) { consumers[i] = thread(consumer); producers[i]=thread(producer,i+1); } for(int i=0;i<5;i++) { consumers[i].join(); producers[i].join(); } return 0; }
eaad3e90d96cdac17f5e814bce28e1379242147c
46f2e7a10fca9f7e7b80b342240302c311c31914
/opposing_lid_driven_flow/cavity/0.0272/p
8a04067e5a3af062ebc0c369d55d87cb4575446e
[]
no_license
patricksinclair/openfoam_warmups
696cb1950d40b967b8b455164134bde03e9179a1
03c982f7d46b4858e3b6bfdde7b8e8c3c4275df9
refs/heads/master
2020-12-26T12:50:00.615357
2020-02-04T20:22:35
2020-02-04T20:22:35
237,510,814
0
0
null
null
null
null
UTF-8
C++
false
false
23,280
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0272"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 2500 ( 2.22535e-05 -6.51116 -9.29488 -10.4888 -11.1521 -11.5561 -11.8174 -11.9998 -12.1353 -12.2403 -12.3241 -12.3924 -12.4492 -12.4969 -12.5374 -12.572 -12.6019 -12.6279 -12.6505 -12.6704 -12.6879 -12.7034 -12.7173 -12.7298 -12.7413 -12.7519 -12.7619 -12.7716 -12.7812 -12.7911 -12.8014 -12.8126 -12.825 -12.8393 -12.8559 -12.8757 -12.8995 -12.9286 -12.9648 -13.0104 -13.0689 -13.1457 -13.2494 -13.3959 -13.6162 -13.9714 -14.5689 -15.668 -18.3344 -24.7192 -4.95619 -7.67541 -9.18107 -10.1398 -10.806 -11.2642 -11.5839 -11.8153 -11.9887 -12.1226 -12.2286 -12.3142 -12.3846 -12.4433 -12.4928 -12.535 -12.5713 -12.6028 -12.6303 -12.6545 -12.676 -12.6952 -12.7125 -12.7283 -12.743 -12.7569 -12.7702 -12.7832 -12.7964 -12.8101 -12.8246 -12.8404 -12.858 -12.8782 -12.9016 -12.9293 -12.9627 -13.0034 -13.0539 -13.1175 -13.199 -13.3058 -13.4489 -13.6459 -13.9261 -14.3375 -14.9454 -15.8321 -17.2514 -19.8507 -7.92707 -8.75841 -9.55834 -10.2382 -10.7771 -11.1857 -11.4937 -11.7288 -11.9112 -12.0551 -12.1706 -12.2647 -12.3425 -12.4077 -12.4628 -12.5099 -12.5504 -12.5857 -12.6166 -12.6439 -12.6682 -12.69 -12.7099 -12.7282 -12.7452 -12.7615 -12.7772 -12.7928 -12.8087 -12.8251 -12.8427 -12.8618 -12.8831 -12.9073 -12.9354 -12.9684 -13.0077 -13.0554 -13.1139 -13.1867 -13.2787 -13.3965 -13.55 -13.7527 -14.0243 -14.3911 -14.8817 -15.5083 -16.2531 -17.0165 -9.43814 -9.64998 -10.0678 -10.5117 -10.9036 -11.2295 -11.4947 -11.709 -11.8824 -12.0237 -12.1398 -12.2361 -12.3167 -12.3848 -12.4429 -12.4929 -12.5362 -12.574 -12.6072 -12.6367 -12.6631 -12.687 -12.7088 -12.729 -12.7479 -12.7661 -12.7837 -12.8013 -12.8192 -12.8378 -12.8576 -12.8792 -12.9032 -12.9302 -12.9613 -12.9976 -13.0405 -13.0917 -13.1537 -13.2295 -13.3231 -13.4397 -13.5862 -13.7709 -14.0037 -14.2941 -14.6478 -15.0524 -15.4337 -15.6113 -10.3253 -10.3226 -10.525 -10.8007 -11.0744 -11.3234 -11.541 -11.7267 -11.8836 -12.0157 -12.1272 -12.2216 -12.302 -12.3708 -12.4301 -12.4815 -12.5264 -12.5658 -12.6007 -12.6318 -12.6598 -12.6853 -12.7086 -12.7303 -12.7508 -12.7705 -12.7898 -12.809 -12.8285 -12.8488 -12.8705 -12.8939 -12.9197 -12.9488 -12.9818 -13.02 -13.0645 -13.1171 -13.1796 -13.2545 -13.3447 -13.4539 -13.5859 -13.7451 -13.9344 -14.154 -14.3979 -14.6454 -14.8242 -14.8051 -10.8932 -10.8164 -10.9034 -11.0696 -11.2564 -11.4417 -11.6148 -11.7703 -11.9074 -12.0267 -12.1302 -12.2198 -12.2975 -12.365 -12.4238 -12.4754 -12.5208 -12.5611 -12.5969 -12.629 -12.6581 -12.6846 -12.7091 -12.732 -12.7537 -12.7745 -12.795 -12.8154 -12.8362 -12.8577 -12.8806 -12.9052 -12.9323 -12.9624 -12.9963 -13.0351 -13.0798 -13.1317 -13.1923 -13.2634 -13.3469 -13.445 -13.5594 -13.6915 -13.8403 -14.0016 -14.1655 -14.3117 -14.384 -14.3013 -11.2763 -11.1823 -11.2105 -11.308 -11.4333 -11.5687 -11.7033 -11.8305 -11.9471 -12.0521 -12.1457 -12.2286 -12.3018 -12.3664 -12.4236 -12.4742 -12.5192 -12.5594 -12.5955 -12.628 -12.6577 -12.6849 -12.7101 -12.7337 -12.7561 -12.7778 -12.7991 -12.8203 -12.8418 -12.8642 -12.8877 -12.913 -12.9405 -12.9709 -13.0048 -13.0431 -13.0866 -13.1363 -13.1933 -13.2587 -13.3337 -13.4192 -13.5156 -13.6221 -13.7363 -13.8522 -13.96 -14.0435 -14.0631 -13.969 -11.55 -11.4595 -11.4583 -11.5134 -11.5961 -11.6936 -11.7968 -11.8991 -11.9966 -12.0872 -12.1702 -12.2453 -12.313 -12.3737 -12.4281 -12.477 -12.5208 -12.5603 -12.596 -12.6285 -12.6582 -12.6856 -12.7111 -12.7351 -12.758 -12.7801 -12.8018 -12.8234 -12.8454 -12.8681 -12.8919 -12.9172 -12.9446 -12.9746 -13.0077 -13.0446 -13.0859 -13.1324 -13.1848 -13.2437 -13.3095 -13.3825 -13.462 -13.5464 -13.6325 -13.7145 -13.7841 -13.8293 -13.8237 -13.7363 -11.7559 -11.6746 -11.6591 -11.6879 -11.7416 -11.8112 -11.8895 -11.9708 -12.0512 -12.1283 -12.2007 -12.2678 -12.3294 -12.3856 -12.4366 -12.4829 -12.525 -12.5632 -12.5981 -12.63 -12.6594 -12.6866 -12.7121 -12.7361 -12.7591 -12.7813 -12.8031 -12.8248 -12.8468 -12.8694 -12.893 -12.918 -12.9447 -12.9738 -13.0055 -13.0404 -13.079 -13.1218 -13.1691 -13.2211 -13.278 -13.3392 -13.4038 -13.4699 -13.5341 -13.5914 -13.6354 -13.6577 -13.6405 -13.564 -11.917 -11.8454 -11.8233 -11.8359 -11.8699 -11.919 -11.978 -12.0421 -12.1077 -12.1726 -12.2351 -12.2943 -12.3496 -12.4008 -12.4481 -12.4915 -12.5313 -12.5678 -12.6014 -12.6324 -12.661 -12.6877 -12.7128 -12.7365 -12.7592 -12.7812 -12.8028 -12.8243 -12.846 -12.8682 -12.8913 -12.9155 -12.9413 -12.969 -12.999 -13.0315 -13.0671 -13.1058 -13.1478 -13.1933 -13.2418 -13.2926 -13.3447 -13.396 -13.4435 -13.4831 -13.51 -13.5186 -13.4967 -13.431 -12.0467 -11.9839 -11.9592 -11.9619 -11.9824 -12.0166 -12.0607 -12.1108 -12.1641 -12.2182 -12.2716 -12.3232 -12.3723 -12.4185 -12.4617 -12.5019 -12.5391 -12.5736 -12.6056 -12.6353 -12.6629 -12.6888 -12.7131 -12.7363 -12.7585 -12.78 -12.8011 -12.8221 -12.8432 -12.8647 -12.8869 -12.9102 -12.9347 -12.9608 -12.9887 -13.0187 -13.051 -13.0857 -13.1228 -13.162 -13.2031 -13.245 -13.2867 -13.3263 -13.3612 -13.3882 -13.4039 -13.4044 -13.3813 -13.325 -12.1534 -12.0981 -12.0729 -12.0695 -12.0809 -12.1043 -12.137 -12.1759 -12.2188 -12.2636 -12.3089 -12.3534 -12.3966 -12.4379 -12.477 -12.5138 -12.5482 -12.5804 -12.6105 -12.6386 -12.6649 -12.6897 -12.7131 -12.7354 -12.7569 -12.7777 -12.798 -12.8183 -12.8386 -12.8592 -12.8804 -12.9024 -12.9254 -12.9497 -12.9755 -13.0029 -13.032 -13.0628 -13.0952 -13.1289 -13.1634 -13.1979 -13.2311 -13.2616 -13.2871 -13.3053 -13.3135 -13.3094 -13.2867 -13.2384 -12.2426 -12.1938 -12.1692 -12.1622 -12.1673 -12.1829 -12.2068 -12.2369 -12.2712 -12.308 -12.3461 -12.3843 -12.4219 -12.4584 -12.4934 -12.5267 -12.5582 -12.5879 -12.6159 -12.6422 -12.667 -12.6905 -12.7127 -12.734 -12.7545 -12.7743 -12.7938 -12.8131 -12.8324 -12.8519 -12.8719 -12.8925 -12.9139 -12.9364 -12.9599 -12.9847 -13.0107 -13.0379 -13.0661 -13.0949 -13.1239 -13.1521 -13.1786 -13.202 -13.2206 -13.2325 -13.2359 -13.2292 -13.2079 -13.1662 -12.318 -12.2749 -12.2515 -12.2424 -12.2434 -12.2532 -12.2705 -12.2936 -12.3208 -12.3509 -12.3826 -12.4151 -12.4475 -12.4795 -12.5105 -12.5404 -12.5689 -12.596 -12.6218 -12.6462 -12.6693 -12.6912 -12.7121 -12.7321 -12.7514 -12.7702 -12.7885 -12.8067 -12.8248 -12.8431 -12.8618 -12.8809 -12.9007 -12.9212 -12.9426 -12.9649 -12.988 -13.0119 -13.0363 -13.0609 -13.0851 -13.1082 -13.1293 -13.1473 -13.1608 -13.1684 -13.1687 -13.1609 -13.1412 -13.1052 -12.3826 -12.3443 -12.3225 -12.3125 -12.3107 -12.3164 -12.3286 -12.3461 -12.3676 -12.3919 -12.4181 -12.4455 -12.4732 -12.5009 -12.5282 -12.5546 -12.5802 -12.6047 -12.6281 -12.6504 -12.6716 -12.6919 -12.7113 -12.7299 -12.7479 -12.7654 -12.7825 -12.7994 -12.8163 -12.8333 -12.8505 -12.8681 -12.8861 -12.9048 -12.924 -12.9439 -12.9644 -12.9853 -13.0064 -13.0273 -13.0475 -13.0665 -13.0834 -13.0972 -13.107 -13.1115 -13.11 -13.1018 -13.084 -13.0529 -12.4383 -12.4045 -12.3844 -12.374 -12.3704 -12.3732 -12.3816 -12.3947 -12.4114 -12.431 -12.4525 -12.4753 -12.4988 -12.5225 -12.5461 -12.5693 -12.5919 -12.6137 -12.6347 -12.6549 -12.6742 -12.6927 -12.7105 -12.7276 -12.7441 -12.7602 -12.776 -12.7915 -12.807 -12.8226 -12.8383 -12.8543 -12.8706 -12.8874 -12.9046 -12.9223 -12.9403 -12.9585 -12.9767 -12.9945 -13.0114 -13.027 -13.0405 -13.0512 -13.0583 -13.0608 -13.0583 -13.0502 -13.0343 -13.0076 -12.4868 -12.457 -12.4387 -12.4285 -12.4239 -12.4246 -12.4302 -12.4397 -12.4526 -12.4681 -12.4855 -12.5043 -12.524 -12.5441 -12.5643 -12.5843 -12.604 -12.6232 -12.6418 -12.6598 -12.677 -12.6937 -12.7097 -12.7252 -12.7402 -12.7548 -12.7691 -12.7833 -12.7973 -12.8114 -12.8256 -12.8399 -12.8546 -12.8695 -12.8848 -12.9004 -12.9161 -12.9319 -12.9475 -12.9626 -12.9768 -12.9896 -13.0005 -13.0088 -13.014 -13.0152 -13.0122 -13.0046 -12.9907 -12.9678 -12.5293 -12.5032 -12.4868 -12.4771 -12.472 -12.4713 -12.4747 -12.4816 -12.4913 -12.5034 -12.5173 -12.5326 -12.5488 -12.5655 -12.5825 -12.5996 -12.6165 -12.6331 -12.6493 -12.665 -12.6803 -12.695 -12.7092 -12.723 -12.7364 -12.7494 -12.7622 -12.7748 -12.7874 -12.7999 -12.8125 -12.8253 -12.8382 -12.8514 -12.8648 -12.8784 -12.892 -12.9057 -12.919 -12.9318 -12.9437 -12.9543 -12.9631 -12.9696 -12.9734 -12.9738 -12.9708 -12.964 -12.952 -12.9327 -12.5669 -12.5443 -12.5298 -12.5209 -12.5156 -12.5141 -12.5158 -12.5205 -12.5277 -12.537 -12.5479 -12.56 -12.5731 -12.5868 -12.6009 -12.6151 -12.6294 -12.6435 -12.6573 -12.6708 -12.6839 -12.6967 -12.7091 -12.7211 -12.7328 -12.7442 -12.7554 -12.7664 -12.7774 -12.7884 -12.7994 -12.8105 -12.8218 -12.8332 -12.8448 -12.8565 -12.8683 -12.8799 -12.8912 -12.902 -12.9119 -12.9207 -12.9279 -12.933 -12.9359 -12.9359 -12.9331 -12.9272 -12.9171 -12.9011 -12.6005 -12.5812 -12.5686 -12.5606 -12.5555 -12.5534 -12.554 -12.5571 -12.5622 -12.5691 -12.5773 -12.5868 -12.5971 -12.608 -12.6193 -12.6309 -12.6426 -12.6542 -12.6657 -12.677 -12.6881 -12.6989 -12.7094 -12.7196 -12.7295 -12.7393 -12.7488 -12.7583 -12.7676 -12.777 -12.7864 -12.7958 -12.8054 -12.8152 -12.825 -12.8349 -12.8449 -12.8547 -12.8642 -12.8732 -12.8815 -12.8887 -12.8945 -12.8987 -12.9009 -12.9008 -12.8984 -12.8936 -12.8854 -12.8725 -12.6308 -12.6147 -12.604 -12.597 -12.5923 -12.5899 -12.5898 -12.5915 -12.5949 -12.5998 -12.6058 -12.6128 -12.6206 -12.629 -12.6378 -12.6469 -12.6562 -12.6655 -12.6747 -12.6839 -12.6929 -12.7017 -12.7103 -12.7186 -12.7268 -12.7348 -12.7427 -12.7505 -12.7582 -12.7659 -12.7736 -12.7814 -12.7893 -12.7974 -12.8055 -12.8137 -12.8219 -12.83 -12.8378 -12.8453 -12.852 -12.8579 -12.8627 -12.8661 -12.868 -12.868 -12.8661 -12.8624 -12.8561 -12.8462 -12.6584 -12.6454 -12.6366 -12.6307 -12.6265 -12.6242 -12.6235 -12.6242 -12.6262 -12.6294 -12.6335 -12.6384 -12.6439 -12.65 -12.6564 -12.6632 -12.6701 -12.6772 -12.6843 -12.6913 -12.6983 -12.7051 -12.7118 -12.7183 -12.7247 -12.731 -12.7371 -12.7432 -12.7492 -12.7552 -12.7613 -12.7674 -12.7736 -12.7799 -12.7864 -12.7929 -12.7994 -12.8058 -12.8121 -12.818 -12.8235 -12.8283 -12.8321 -12.835 -12.8366 -12.8368 -12.8356 -12.833 -12.8286 -12.8217 -12.684 -12.6739 -12.6671 -12.6623 -12.6588 -12.6566 -12.6555 -12.6555 -12.6564 -12.6581 -12.6605 -12.6634 -12.667 -12.6709 -12.6752 -12.6797 -12.6845 -12.6894 -12.6944 -12.6994 -12.7043 -12.7092 -12.714 -12.7187 -12.7233 -12.7278 -12.7322 -12.7365 -12.7408 -12.7451 -12.7494 -12.7538 -12.7583 -12.7629 -12.7676 -12.7724 -12.7772 -12.7821 -12.7868 -12.7914 -12.7956 -12.7993 -12.8024 -12.8048 -12.8062 -12.8068 -12.8063 -12.805 -12.8024 -12.7983 -12.7081 -12.7009 -12.6959 -12.6923 -12.6896 -12.6876 -12.6864 -12.6857 -12.6856 -12.6861 -12.6869 -12.6882 -12.6899 -12.6918 -12.6941 -12.6966 -12.6993 -12.7021 -12.7051 -12.7081 -12.7111 -12.7141 -12.717 -12.7198 -12.7226 -12.7253 -12.7279 -12.7305 -12.733 -12.7356 -12.7381 -12.7408 -12.7435 -12.7463 -12.7493 -12.7523 -12.7555 -12.7587 -12.762 -12.7651 -12.7681 -12.7709 -12.7732 -12.7752 -12.7766 -12.7775 -12.7778 -12.7777 -12.777 -12.7758 -12.7311 -12.7267 -12.7236 -12.7213 -12.7193 -12.7177 -12.7163 -12.7152 -12.7143 -12.7136 -12.7131 -12.7128 -12.7127 -12.7129 -12.7132 -12.7138 -12.7145 -12.7154 -12.7164 -12.7174 -12.7185 -12.7196 -12.7207 -12.7218 -12.7227 -12.7236 -12.7245 -12.7252 -12.726 -12.7267 -12.7275 -12.7283 -12.7292 -12.7302 -12.7313 -12.7326 -12.7341 -12.7356 -12.7373 -12.7391 -12.7409 -12.7426 -12.7443 -12.7458 -12.7472 -12.7485 -12.7496 -12.7507 -12.752 -12.7535 -12.7535 -12.752 -12.7508 -12.7497 -12.7485 -12.7472 -12.7458 -12.7443 -12.7426 -12.7409 -12.7391 -12.7373 -12.7356 -12.7341 -12.7326 -12.7313 -12.7302 -12.7292 -12.7283 -12.7275 -12.7267 -12.726 -12.7252 -12.7245 -12.7236 -12.7227 -12.7218 -12.7207 -12.7196 -12.7185 -12.7174 -12.7164 -12.7154 -12.7145 -12.7138 -12.7132 -12.7129 -12.7127 -12.7128 -12.7131 -12.7136 -12.7143 -12.7152 -12.7163 -12.7177 -12.7193 -12.7213 -12.7236 -12.7267 -12.7311 -12.7758 -12.777 -12.7777 -12.7778 -12.7775 -12.7766 -12.7752 -12.7732 -12.7709 -12.7681 -12.7651 -12.762 -12.7587 -12.7555 -12.7523 -12.7493 -12.7463 -12.7435 -12.7408 -12.7381 -12.7356 -12.733 -12.7305 -12.7279 -12.7253 -12.7226 -12.7198 -12.717 -12.7141 -12.7111 -12.7081 -12.7051 -12.7021 -12.6993 -12.6966 -12.6941 -12.6918 -12.6898 -12.6882 -12.6869 -12.6861 -12.6856 -12.6857 -12.6863 -12.6876 -12.6896 -12.6923 -12.6959 -12.7009 -12.7081 -12.7983 -12.8024 -12.805 -12.8063 -12.8068 -12.8062 -12.8048 -12.8024 -12.7993 -12.7956 -12.7914 -12.7868 -12.7821 -12.7773 -12.7724 -12.7676 -12.7629 -12.7583 -12.7538 -12.7494 -12.7451 -12.7408 -12.7365 -12.7322 -12.7278 -12.7233 -12.7187 -12.714 -12.7092 -12.7043 -12.6994 -12.6944 -12.6894 -12.6845 -12.6797 -12.6752 -12.6709 -12.6669 -12.6634 -12.6605 -12.6581 -12.6564 -12.6555 -12.6555 -12.6566 -12.6588 -12.6623 -12.6671 -12.6739 -12.684 -12.8217 -12.8286 -12.833 -12.8356 -12.8368 -12.8366 -12.835 -12.8321 -12.8283 -12.8235 -12.818 -12.8121 -12.8058 -12.7994 -12.7929 -12.7864 -12.7799 -12.7736 -12.7674 -12.7613 -12.7552 -12.7492 -12.7432 -12.7371 -12.731 -12.7247 -12.7183 -12.7118 -12.7051 -12.6983 -12.6913 -12.6843 -12.6772 -12.6701 -12.6632 -12.6564 -12.65 -12.6439 -12.6384 -12.6335 -12.6294 -12.6262 -12.6242 -12.6234 -12.6242 -12.6265 -12.6307 -12.6366 -12.6454 -12.6584 -12.8462 -12.8561 -12.8624 -12.8661 -12.868 -12.868 -12.8661 -12.8627 -12.858 -12.852 -12.8453 -12.8378 -12.83 -12.8219 -12.8137 -12.8055 -12.7974 -12.7893 -12.7814 -12.7736 -12.7659 -12.7582 -12.7505 -12.7427 -12.7348 -12.7268 -12.7186 -12.7103 -12.7017 -12.6929 -12.6839 -12.6747 -12.6655 -12.6562 -12.6469 -12.6378 -12.629 -12.6206 -12.6128 -12.6058 -12.5998 -12.5949 -12.5915 -12.5897 -12.5899 -12.5923 -12.5969 -12.604 -12.6147 -12.6308 -12.8725 -12.8854 -12.8936 -12.8984 -12.9009 -12.9009 -12.8987 -12.8945 -12.8887 -12.8815 -12.8732 -12.8642 -12.8547 -12.8449 -12.8349 -12.825 -12.8152 -12.8054 -12.7958 -12.7864 -12.777 -12.7676 -12.7583 -12.7488 -12.7393 -12.7295 -12.7196 -12.7094 -12.6989 -12.6881 -12.677 -12.6657 -12.6542 -12.6426 -12.6309 -12.6193 -12.608 -12.5971 -12.5868 -12.5773 -12.569 -12.5622 -12.5571 -12.554 -12.5534 -12.5555 -12.5606 -12.5686 -12.5812 -12.6005 -12.9011 -12.9171 -12.9272 -12.9331 -12.9359 -12.9359 -12.9331 -12.9279 -12.9207 -12.9119 -12.902 -12.8912 -12.8799 -12.8683 -12.8565 -12.8448 -12.8332 -12.8218 -12.8105 -12.7994 -12.7884 -12.7774 -12.7664 -12.7554 -12.7442 -12.7328 -12.7211 -12.7091 -12.6967 -12.6839 -12.6708 -12.6573 -12.6434 -12.6294 -12.6151 -12.6009 -12.5868 -12.5731 -12.56 -12.5479 -12.537 -12.5277 -12.5205 -12.5158 -12.514 -12.5156 -12.5208 -12.5298 -12.5443 -12.5669 -12.9327 -12.952 -12.964 -12.9708 -12.9738 -12.9734 -12.9696 -12.9631 -12.9543 -12.9437 -12.9318 -12.919 -12.9057 -12.892 -12.8784 -12.8648 -12.8514 -12.8382 -12.8253 -12.8125 -12.7999 -12.7874 -12.7748 -12.7622 -12.7494 -12.7364 -12.723 -12.7092 -12.695 -12.6803 -12.665 -12.6493 -12.6331 -12.6165 -12.5996 -12.5825 -12.5655 -12.5487 -12.5326 -12.5173 -12.5034 -12.4913 -12.4815 -12.4747 -12.4713 -12.472 -12.4771 -12.4868 -12.5032 -12.5293 -12.9679 -12.9907 -13.0046 -13.0122 -13.0152 -13.014 -13.0088 -13.0005 -12.9896 -12.9768 -12.9626 -12.9475 -12.9319 -12.9161 -12.9004 -12.8848 -12.8695 -12.8546 -12.8399 -12.8256 -12.8114 -12.7973 -12.7833 -12.7691 -12.7548 -12.7402 -12.7252 -12.7097 -12.6937 -12.677 -12.6598 -12.6418 -12.6232 -12.604 -12.5843 -12.5643 -12.5441 -12.524 -12.5043 -12.4855 -12.4681 -12.4526 -12.4397 -12.4301 -12.4246 -12.4239 -12.4285 -12.4387 -12.457 -12.4867 -13.0076 -13.0343 -13.0502 -13.0583 -13.0608 -13.0583 -13.0512 -13.0405 -13.027 -13.0114 -12.9945 -12.9767 -12.9585 -12.9403 -12.9223 -12.9046 -12.8874 -12.8706 -12.8543 -12.8383 -12.8226 -12.807 -12.7915 -12.776 -12.7602 -12.7441 -12.7276 -12.7104 -12.6927 -12.6742 -12.6549 -12.6347 -12.6137 -12.5919 -12.5693 -12.5461 -12.5225 -12.4988 -12.4753 -12.4525 -12.4309 -12.4114 -12.3947 -12.3816 -12.3732 -12.3704 -12.374 -12.3844 -12.4045 -12.4383 -13.0529 -13.084 -13.1018 -13.11 -13.1115 -13.107 -13.0972 -13.0834 -13.0665 -13.0475 -13.0273 -13.0064 -12.9853 -12.9644 -12.9439 -12.924 -12.9048 -12.8861 -12.8681 -12.8505 -12.8333 -12.8163 -12.7994 -12.7825 -12.7654 -12.7479 -12.7299 -12.7113 -12.6919 -12.6716 -12.6504 -12.6281 -12.6047 -12.5802 -12.5546 -12.5282 -12.5009 -12.4732 -12.4455 -12.4181 -12.3919 -12.3675 -12.3461 -12.3286 -12.3164 -12.3106 -12.3124 -12.3225 -12.3443 -12.3826 -13.1052 -13.1412 -13.1609 -13.1687 -13.1684 -13.1608 -13.1473 -13.1293 -13.1082 -13.0851 -13.0609 -13.0363 -13.0119 -12.988 -12.9649 -12.9426 -12.9212 -12.9007 -12.8809 -12.8618 -12.8431 -12.8248 -12.8067 -12.7885 -12.7702 -12.7514 -12.7321 -12.7121 -12.6912 -12.6693 -12.6462 -12.6218 -12.596 -12.5689 -12.5404 -12.5105 -12.4795 -12.4475 -12.415 -12.3826 -12.3509 -12.3208 -12.2936 -12.2705 -12.2532 -12.2434 -12.2424 -12.2515 -12.2748 -12.318 -13.1662 -13.2079 -13.2292 -13.2359 -13.2325 -13.2206 -13.202 -13.1786 -13.1521 -13.1239 -13.0949 -13.0661 -13.0379 -13.0107 -12.9847 -12.9599 -12.9364 -12.9139 -12.8925 -12.8719 -12.8519 -12.8323 -12.813 -12.7938 -12.7743 -12.7545 -12.734 -12.7127 -12.6905 -12.667 -12.6422 -12.6159 -12.5879 -12.5582 -12.5267 -12.4934 -12.4584 -12.4219 -12.3842 -12.346 -12.308 -12.2712 -12.2369 -12.2068 -12.1828 -12.1673 -12.1621 -12.1692 -12.1937 -12.2426 -13.2384 -13.2867 -13.3094 -13.3135 -13.3053 -13.2871 -13.2616 -13.2311 -13.1979 -13.1634 -13.1289 -13.0952 -13.0628 -13.032 -13.0029 -12.9755 -12.9497 -12.9254 -12.9024 -12.8804 -12.8592 -12.8386 -12.8183 -12.798 -12.7776 -12.7569 -12.7354 -12.7131 -12.6897 -12.6649 -12.6386 -12.6105 -12.5804 -12.5482 -12.5138 -12.477 -12.4379 -12.3966 -12.3534 -12.3088 -12.2636 -12.2188 -12.1759 -12.1369 -12.1043 -12.0809 -12.0695 -12.0729 -12.0981 -12.1534 -13.325 -13.3813 -13.4044 -13.4039 -13.3882 -13.3612 -13.3263 -13.2867 -13.245 -13.2031 -13.162 -13.1228 -13.0857 -13.051 -13.0187 -12.9887 -12.9608 -12.9347 -12.9102 -12.8869 -12.8647 -12.8432 -12.8221 -12.8011 -12.78 -12.7585 -12.7363 -12.7131 -12.6888 -12.6629 -12.6352 -12.6056 -12.5736 -12.5391 -12.5019 -12.4617 -12.4185 -12.3723 -12.3232 -12.2716 -12.2182 -12.1641 -12.1108 -12.0607 -12.0166 -11.9823 -11.9618 -11.9592 -11.9839 -12.0467 -13.431 -13.4967 -13.5186 -13.51 -13.4831 -13.4435 -13.396 -13.3447 -13.2926 -13.2418 -13.1933 -13.1478 -13.1058 -13.067 -13.0315 -12.999 -12.969 -12.9413 -12.9155 -12.8912 -12.8682 -12.846 -12.8243 -12.8028 -12.7812 -12.7592 -12.7365 -12.7128 -12.6877 -12.661 -12.6323 -12.6014 -12.5678 -12.5313 -12.4914 -12.448 -12.4008 -12.3495 -12.2943 -12.2351 -12.1726 -12.1077 -12.042 -11.978 -11.919 -11.8698 -11.8359 -11.8233 -11.8454 -11.917 -13.564 -13.6405 -13.6577 -13.6354 -13.5914 -13.5341 -13.4699 -13.4038 -13.3392 -13.278 -13.2211 -13.1691 -13.1218 -13.079 -13.0404 -13.0055 -12.9738 -12.9447 -12.918 -12.893 -12.8694 -12.8468 -12.8248 -12.803 -12.7813 -12.759 -12.7361 -12.7121 -12.6866 -12.6594 -12.63 -12.5981 -12.5632 -12.525 -12.4829 -12.4366 -12.3855 -12.3294 -12.2678 -12.2007 -12.1283 -12.0512 -11.9708 -11.8895 -11.8112 -11.7416 -11.6879 -11.6591 -11.6745 -11.7559 -13.7363 -13.8237 -13.8293 -13.7841 -13.7145 -13.6325 -13.5464 -13.462 -13.3825 -13.3095 -13.2437 -13.1848 -13.1324 -13.0859 -13.0446 -13.0077 -12.9746 -12.9446 -12.9172 -12.8918 -12.8681 -12.8454 -12.8234 -12.8018 -12.7801 -12.758 -12.7351 -12.7111 -12.6856 -12.6582 -12.6285 -12.596 -12.5603 -12.5208 -12.4769 -12.4281 -12.3737 -12.313 -12.2453 -12.1701 -12.0872 -11.9966 -11.8991 -11.7968 -11.6936 -11.5961 -11.5133 -11.4583 -11.4594 -11.55 -13.969 -14.0631 -14.0435 -13.96 -13.8522 -13.7363 -13.6221 -13.5156 -13.4192 -13.3337 -13.2587 -13.1933 -13.1363 -13.0866 -13.0431 -13.0048 -12.9709 -12.9405 -12.913 -12.8877 -12.8642 -12.8418 -12.8203 -12.799 -12.7778 -12.7561 -12.7337 -12.71 -12.6848 -12.6577 -12.628 -12.5955 -12.5594 -12.5192 -12.4742 -12.4235 -12.3664 -12.3017 -12.2285 -12.1457 -12.0521 -11.9471 -11.8304 -11.7032 -11.5686 -11.4333 -11.308 -11.2105 -11.1823 -11.2763 -14.3013 -14.384 -14.3117 -14.1655 -14.0016 -13.8403 -13.6915 -13.5594 -13.445 -13.3469 -13.2634 -13.1923 -13.1317 -13.0798 -13.0351 -12.9963 -12.9624 -12.9323 -12.9052 -12.8806 -12.8577 -12.8362 -12.8154 -12.795 -12.7745 -12.7537 -12.732 -12.7091 -12.6846 -12.6581 -12.629 -12.5969 -12.561 -12.5208 -12.4754 -12.4238 -12.365 -12.2975 -12.2198 -12.1302 -12.0267 -11.9073 -11.7703 -11.6147 -11.4417 -11.2563 -11.0696 -10.9033 -10.8164 -10.8932 -14.8051 -14.8242 -14.6454 -14.3979 -14.154 -13.9344 -13.7451 -13.5859 -13.4539 -13.3447 -13.2545 -13.1796 -13.1171 -13.0645 -13.02 -12.9818 -12.9488 -12.9197 -12.8939 -12.8705 -12.8488 -12.8285 -12.809 -12.7898 -12.7705 -12.7508 -12.7303 -12.7086 -12.6852 -12.6598 -12.6318 -12.6007 -12.5658 -12.5264 -12.4815 -12.4301 -12.3708 -12.302 -12.2216 -12.1272 -12.0157 -11.8835 -11.7266 -11.5409 -11.3234 -11.0743 -10.8007 -10.525 -10.3226 -10.3252 -15.6113 -15.4337 -15.0524 -14.6478 -14.2941 -14.0037 -13.7709 -13.5862 -13.4397 -13.3231 -13.2295 -13.1537 -13.0917 -13.0405 -12.9976 -12.9613 -12.9302 -12.9032 -12.8792 -12.8576 -12.8378 -12.8192 -12.8013 -12.7837 -12.7661 -12.7479 -12.729 -12.7088 -12.687 -12.6631 -12.6367 -12.6072 -12.5739 -12.5362 -12.4929 -12.4429 -12.3848 -12.3167 -12.236 -12.1398 -12.0237 -11.8824 -11.7089 -11.4946 -11.2294 -10.9035 -10.5117 -10.0678 -9.64994 -9.4381 -17.0165 -16.2531 -15.5083 -14.8817 -14.3911 -14.0243 -13.7527 -13.55 -13.3965 -13.2787 -13.1867 -13.1139 -13.0554 -13.0077 -12.9684 -12.9354 -12.9073 -12.8831 -12.8618 -12.8427 -12.8251 -12.8087 -12.7928 -12.7772 -12.7615 -12.7452 -12.7282 -12.7099 -12.69 -12.6682 -12.6439 -12.6166 -12.5857 -12.5504 -12.5098 -12.4628 -12.4076 -12.3425 -12.2647 -12.1706 -12.0551 -11.9112 -11.7288 -11.4937 -11.1857 -10.7771 -10.2382 -9.5583 -8.75837 -7.92703 -19.8507 -17.2514 -15.8321 -14.9454 -14.3375 -13.9261 -13.6459 -13.4489 -13.3058 -13.199 -13.1175 -13.0539 -13.0034 -12.9627 -12.9293 -12.9016 -12.8782 -12.858 -12.8404 -12.8246 -12.8101 -12.7964 -12.7832 -12.7701 -12.7568 -12.743 -12.7283 -12.7125 -12.6952 -12.676 -12.6545 -12.6303 -12.6028 -12.5713 -12.535 -12.4928 -12.4432 -12.3846 -12.3142 -12.2286 -12.1226 -11.9887 -11.8152 -11.5838 -11.2642 -10.8059 -10.1397 -9.18103 -7.67536 -4.95614 -24.7192 -18.3344 -15.668 -14.5689 -13.9714 -13.6162 -13.3959 -13.2494 -13.1457 -13.0689 -13.0104 -12.9648 -12.9286 -12.8995 -12.8757 -12.8559 -12.8393 -12.825 -12.8126 -12.8014 -12.791 -12.7812 -12.7716 -12.7619 -12.7519 -12.7413 -12.7298 -12.7173 -12.7034 -12.6879 -12.6703 -12.6505 -12.6279 -12.6019 -12.572 -12.5373 -12.4968 -12.4492 -12.3924 -12.324 -12.2402 -12.1352 -11.9998 -11.8173 -11.556 -11.152 -10.4888 -9.29484 -6.51111 9.72521e-05 ) ; boundaryField { movingWallTop { type zeroGradient; } movingWallBottom { type zeroGradient; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
82bdee9b42c354587b8662403134880a9f693713
127b4bb0893d5ca8fb066e9e2d770538240432ea
/yellowfellow-ac/UVA/10959/12778566_AC_0ms_0kB.cpp
494ca158557ad538792bc3c61b06a5ca3eec6ba5
[]
no_license
kuningfellow/Kuburan-CP
5481f3f7fce9471acd108dc601adc183c9105672
2dc8bbc8c18a8746d32a4a20910b717c066d0d41
refs/heads/master
2020-04-24T15:13:40.853652
2019-12-24T07:21:38
2019-12-24T07:21:38
172,057,574
0
0
null
null
null
null
UTF-8
C++
false
false
779
cpp
12778566_AC_0ms_0kB.cpp
#include <stdio.h> #include <vector> #include <iostream> #include <queue> using namespace std; int main() { int tc; cin>>tc; while (tc--) { int n,m; cin>>n>>m; vector<int>lis[n]; int vis[n]; for (int i=0;i<n;i++)vis[i]=0; int a,b; for (int i=0;i<m;i++) { cin>>a>>b; lis[a].push_back(b); lis[b].push_back(a); } queue<int>q; q.push(0); int step=1; int siz; vis[0]=1; while (!q.empty()) { siz=q.size(); for (int i=0;i<siz;i++) { for (int j=0;j<lis[q.front()].size();j++) { if (vis[lis[q.front()][j]]==0) { vis[lis[q.front()][j]]=step; q.push(lis[q.front()][j]); } } q.pop(); } step++; } for (int i=1;i<n;i++) { printf ("%d\n",vis[i]); } if (tc!=0)printf ("\n"); } }
40723e1ea7712b6759367b69e208a3098a53c0c4
671dab1e784a9845aa9a0ceee1862d7bf269702c
/Week4-1-CPlayerFix/ClassTest/ClassTest.cpp
7ac8722567a34c014a7bb0c36c0c8313eeb50198
[]
no_license
zrma/PLinCPP
fd9eadc40802acd6f449793a3c65740bfc8ed719
759c198851d9c92ed08f5d71ca76aca60f56e3e4
refs/heads/master
2021-01-17T05:25:29.215925
2014-02-25T07:09:21
2014-02-25T07:09:21
null
0
0
null
null
null
null
UHC
C++
false
false
1,390
cpp
ClassTest.cpp
// ClassTest.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include "Ship.h" #include "Aircraft.h" #include "Battleship.h" #include "Player.h" #include <iostream> #include <Windows.h> int _tmain(int argc, _TCHAR* argv[]) { CPlayer user_1; int turn = 1; user_1.SetPosition(); printf_s("초기화 완료\n"); Position hitPos; HitResult hitResult; while (user_1.GetLeftShips() > 0) { printf_s("----------------------------------\n"); printf_s("[%d턴째] 좌표를 입력 해 주세요 : ", turn); std::cin >> hitPos.x >> hitPos.y; ++turn; // printf_s("\n%c%c\n", input_string.c_str()[0], input_string.c_str()[1]); hitResult = user_1.HitCheck(hitPos); switch (hitResult) { case MISS: printf_s("Miss!\n"); break; case HIT: printf_s("Hit!\n"); break; case DESTROY_AIRCRAFT: printf_s("Destroy Aircraft!\n"); break; case DESTROY_BATTLESHIP: printf_s("Destroy Battleship!\n"); break; case DESTROY_CRUISER: printf_s("Destroy Cruiser!\n"); break; case DESTROY_DESTROYER: printf_s("Destroy Destroyer!\n"); break; case DESTROY_SUBMARINE: printf_s("Destroy Submarine!\n"); break; default: printf_s("Don\'t Print Here!\n"); break; } } printf_s("모든 배가 파괴 되었습니다.\n"); getchar(); getchar(); return 0; }
b2515f8e5c00effeca443469fbf7e29a014b0144
9b1c4136869b349b62be64b807a46f0bb59763e0
/00078 - The Final Exam.cpp
2191113e6264c72facdb397d9bc1f415563c47d8
[]
no_license
m00p1ng/codecube.in.th-problem
89a23e8e55266622d3d1aefd3b16ab1f419b2727
b82067ec2c9f87d48e8d3322ac1c601886ded8e0
refs/heads/master
2020-03-23T19:07:40.416094
2018-08-15T21:43:51
2018-08-15T21:43:51
141,954,662
0
0
null
null
null
null
UTF-8
C++
false
false
534
cpp
00078 - The Final Exam.cpp
#include <cstdio> int main() { int n; int scores[5]; int sum = 0; scanf("%d", &n); for(int i = 0; i < 5; i++) { scanf("%d", &scores[i]); sum += scores[i]; } bool is_valid = sum == n; for(int i = 0; i < 5 && !is_valid; i++) { if(sum - scores[i] == n) { is_valid = true; scores[i] = 0; } } if(is_valid) { for(int i = 0; i < 5; i++) { printf("%d ", scores[i]); } } else { puts("-1"); } }
23b47a327dd1f4b56da69eb36984cf452d8df61b
d3c9c1718ebc96e41941001a0922d9305e7c4741
/ch6/0618/0618.cpp
e88a4ce14c6c28e260da0b6a5db3a6cc959ca831
[]
no_license
cyc12332/CPP_Practice
025970e1babc6405a2ce043f496bd2b26d2f9bb5
020746290ecb55249f7ae9a90af67aa4b83e7cf7
refs/heads/master
2022-02-21T05:13:39.134137
2019-08-21T14:01:21
2019-08-21T14:01:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
0618.cpp
// 0618.cpp : 此檔案包含 'main' 函式。程式會於該處開始執行及結束執行。 // #include <iostream> using namespace std; void function1(); void function2(void); int main() { function1(); function2(); } void function1() { cout << "func.1 takes no args." << endl; } void function2(void) { cout << "func.2 alse takes no args." << endl; } // 執行程式: Ctrl + F5 或 [偵錯] > [啟動但不偵錯] 功能表 // 偵錯程式: F5 或 [偵錯] > [啟動偵錯] 功能表 // 開始使用的提示: // 1. 使用 [方案總管] 視窗,新增/管理檔案 // 2. 使用 [Team Explorer] 視窗,連線到原始檔控制 // 3. 使用 [輸出] 視窗,參閱組建輸出與其他訊息 // 4. 使用 [錯誤清單] 視窗,檢視錯誤 // 5. 前往 [專案] > [新增項目],建立新的程式碼檔案,或是前往 [專案] > [新增現有項目],將現有程式碼檔案新增至專案 // 6. 之後要再次開啟此專案時,請前往 [檔案] > [開啟] > [專案],然後選取 .sln 檔案
5b07be970c7c10148980d1601eb951c4f2da1c82
c0e0138bff95c2eac038349772e36754887a10ae
/mdk_release_18.08.10_general_purpose/mdk/common/components/kernelLib/MvCV/kernels/fast9ScoreCv/shave/src/cpp/fast9ScoreCv.cpp
ec07708a704eb6341d7458f663eb450c42e5215e
[]
no_license
elfmedy/vvdn_tofa
f24d2e1adc617db5f2b1aef85f478998aa1840c9
ce514e0506738a50c0e3f098d8363f206503a311
refs/heads/master
2020-04-13T17:52:19.490921
2018-09-25T12:01:21
2018-09-25T12:01:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,829
cpp
fast9ScoreCv.cpp
#include <mv_types.h> #include "fast9ScoreCv.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #define adiff(a,b) ((a)>(b)?((a)-(b)):((b)-(a))) // local function definition void fastExclude(u8** row, unsigned int* posValid, unsigned int *nrOfPoints, unsigned int thresh, unsigned int width); void fastBitFlag(u8** row, unsigned int* posValid, u8* scores, u16 *cornerPositions, unsigned int thresh, unsigned int nrOfPoints); void fastScore(u8 *score, u8* scoresInput, unsigned int thresh, unsigned int nrOfPoints); void mvcvfast9ScoreCv(u8** row, u8* score, u16 *base, unsigned int thresh, unsigned int width, void* bulkBuff) { unsigned int* posValid = (unsigned int*)bulkBuff; unsigned char* scoresInput =(unsigned char*) (((unsigned char*)bulkBuff) + 4 * width + 8); unsigned int nrOfPoints; fastExclude(row, posValid, &nrOfPoints, thresh, width); fastBitFlag(row, posValid, scoresInput, base, thresh, nrOfPoints); *((u32*)score) = *((u32*)(&base[0])); fastScore((score+4), scoresInput, thresh, *((u32*)(&base[0]))); } void fastExclude(u8** row, unsigned int* posValid, unsigned int *nrOfPoints, unsigned int thresh, unsigned int width) { int posx; int threshL = thresh & 0xFF; *nrOfPoints = 0; for (posx = 0; posx < (int)width; posx++) { if (((adiff(row[3][posx], row[0][posx]) <= threshL) && (adiff(row[3][posx], row[6][posx]) <= threshL)) || ((adiff(row[3][posx], row[3][posx + 3]) <= threshL) && (adiff(row[3][posx], row[3][posx - 3]) <= threshL))) { continue; } else { posValid[*nrOfPoints] = posx; (*nrOfPoints)++; } } //printf("After fastExclude =%d\n",*nrOfPoints); } u8 satu8add(u8 a, u8 b) { int sum = (int)a + (int)b; if (sum > 255) return ((u8)255); else if (sum < 0) return ((u8)0); else return ((u8)sum); } u8 satu8sub(u8 a, u8 b) { int sub = (int)a - (int)b; if (sub > 255) return ((u8)255); else if (sub < 0) return ((u8)0); else return ((u8)sub); } void fastBitFlag(u8** row, unsigned int* posValid, u8* scores, u16 *cornerPositions, unsigned int thresh, unsigned int nrOfPoints) { unsigned int itr; unsigned int counter = 0; u16 *position = cornerPositions + 2; u16 bitFlag = 0x01FF; unsigned int *adrForCounter2 = (unsigned int*)cornerPositions; u8 *scoresOut = scores; for (itr = 0; itr < nrOfPoints; itr++) { int posx = posValid[itr]; u8 origin = row[3][posx]; u8 sample[17] = {0}; u8 loLimit = satu8sub(origin,thresh); u8 hiLimit = satu8add(origin, thresh); unsigned int i = 0; u16 bitMaskLow = 0; u16 bitMaskHi = 0; u8 hiCount = 0; u8 loCount = 0; u8 localHiScore[16] = {0}; u8 localLoScore[16] = {0}; unsigned int finalCounter = 0; u16 bitMask = 0; sample[0] = row[0][posx - 1]; sample[1] = row[0][posx]; sample[2] = row[0][posx + 1]; sample[3] = row[1][posx + 2]; sample[4] = row[2][posx + 3]; sample[5] = row[3][posx + 3]; sample[6] = row[4][posx + 3]; sample[7] = row[5][posx + 2]; sample[8] = row[6][posx + 1]; sample[9] = row[6][posx]; sample[10] = row[6][posx - 1]; sample[11] = row[5][posx - 2]; sample[12] = row[4][posx - 3]; sample[13] = row[3][posx - 3]; sample[14] = row[2][posx - 3]; sample[15] = row[1][posx - 2]; for (i = 0; i<16; i++) { localHiScore[i] = satu8sub(sample[i], hiLimit); localLoScore[i] = satu8sub(loLimit,sample[i]); if (localHiScore[i]) { bitMaskHi |= 1 << i; hiCount++; } if (localLoScore[i]) { bitMaskLow |= (1 << i); loCount++; } } if (hiCount >loCount) { bitMask = bitMaskHi; memcpy(scoresOut, localHiScore, 16); } else { memcpy(scoresOut, localLoScore, 16); bitMask = bitMaskLow; } finalCounter = 0; bitFlag = 0x01FF; for (i = 0; i<16; i++) { if ((bitMask & bitFlag) == bitFlag) { finalCounter++; if(finalCounter>7) { //printf("finalCounter=%d\n",finalCounter); } } if (bitFlag & 0x8000) { bitFlag = ((bitFlag & 0x7FFF) << 1) + 1; } else { bitFlag = bitFlag << 1; } } if (finalCounter != 0) { //printf("finalCounter=%d\n",finalCounter); *position = posx; position++; scoresOut += 16; counter++; } } *adrForCounter2 = counter; } unsigned short rightrot(unsigned short x, unsigned int n) { unsigned short low1 = 1; /* 0x00..01 */ unsigned short high1 = 0x8000; /* 0x80..00 */ unsigned short lowbit; while (n-- > 0) { /* repeat n times */ lowbit = x & low1; /* save low bit */ x = x >> 1; /* right-shift by 1; 0 shifted into high bit */ if (lowbit == low1) x = x | high1; /* set high bit to 1 if low bit was 1 */ } return x; } void vectorRotate(u8* vect, u32 rotVal) { unsigned char vectIntern[16]; u32 i; for (i = 0; i<16; i++) { vectIntern[i] = vect[(i+rotVal)%16]; } memcpy(vect, vectIntern, 16); } u8 minimumCalc(u8 a, u8 b) { if (a < b) return a; return b; } void vectorShift(u8* vect, u32 shiftVal) { unsigned char vectIntern[16]; memset(vectIntern, 0, 16); u32 i; for (i = 0; i<(16-shiftVal); i++) { vectIntern[i] = vect[(i+shiftVal)]; } memcpy(vect, vectIntern, 16); } u16 ones(u16 f) { u16 i; u16 ret = 0; for (i = 0; i<16; i++) { if ((f & (1<< i)) == (1<<i)) { ret++;} } return(ret); } void fastScore(u8 *score, u8* scoresInput, unsigned int thresh, unsigned int nrOfPoints) { unsigned int itr; unsigned short bitMask; u32 i; //printf("nrOfPoints 0x%x \n", nrOfPoints); for (itr = 0; itr < nrOfPoints; itr++) { //printf("\n\n\n itr 0x%x \n", itr); //cmu.vnz bitMask = 0; for (i = 0; i<16; i++) { if(scoresInput[i]) bitMask |= 1 << i; //printf("scoresInput 0x%x \n", scoresInput[i]); } //printf("bitMask 0x%x \n", bitMask); // found first valid position // 2 vau and after compare TRF registers will keep the mask, // mask have to be continue, impossible to have gap //VAU.AND v5, v8, v2 //VAU.AND v6, v8, v3 //CMU.CMVV.u16 v2, v5 //CMU.CMVV.u16 v3, v6 || cmu.cpti i0 C_CMU0 // cmu.cpti i1 C_CMU0 // iau.and i0 EQ (0b01000100010001000100010001000100) // iau.and i1 EQ (0b01000100010001000100010001000100) // unsigned short finalCounter = 0; unsigned short bitFlag = 0x01FF; for (i = 0; i<16; i++) { if ((bitMask & bitFlag) == bitFlag) { finalCounter |= 1 << i; } if (bitFlag & 0x8000) { bitFlag = ((bitFlag & 0x7FFF) << 1) + 1; } else { bitFlag = bitFlag << 1; } } //printf("finalCounter 0x%x \n", finalCounter); u8 maxScore = 0; u8 min = 0; int nrRep = ones(finalCounter); for(; nrRep; nrRep--) { // IAU.BSF Id, Is i = 0; while ((finalCounter & (1<< i)) != (1<<i)) { i++;} unsigned int bfs = i; // rotate scores to // vau.rol vectorRotate(scoresInput, bfs); //for (i = 0; i<16; i++) { // printf("scoresInput 0x%x \n", scoresInput[i]); //} // minimum calculation 9 values { // min 1 1 instruction u8 min1_1 = minimumCalc(scoresInput[0], scoresInput[1]); u8 min1_2 = minimumCalc(scoresInput[2], scoresInput[3]); u8 min1_3 = minimumCalc(scoresInput[4], scoresInput[5]); u8 min1_4 = minimumCalc(scoresInput[6], scoresInput[7]); // min 2 u8 min2_1 = minimumCalc(min1_1, min1_2); u8 min2_2 = minimumCalc(min1_3, min1_4); //min 3 u8 min3_1 = minimumCalc(min2_1, min2_2); //min 4 final min = minimumCalc(min3_1, scoresInput[8]); } vectorRotate(scoresInput, 1); finalCounter = finalCounter >> (bfs+1); if(maxScore < min) maxScore = min; } scoresInput += 16; *score = maxScore + thresh - 1; score++; } }
560a8fccde7c5c8a07bda9143dd64fe2e67df2c5
b9cbbabb7cec3984df5ac03759f35bb54f748247
/student.cpp
531ddbe1a5bada6a9b57304ffe9c7d5b0539f0fd
[]
no_license
OOP2019lab/lab11-l181107abdullahkhan
e8dd9d34aa13de9d867f455dfbf1fee15cf78689
c6c9227236cff6d7947dd683b54ec0125f45d780
refs/heads/master
2020-05-09T20:41:50.481810
2019-04-15T05:23:56
2019-04-15T05:23:56
181,417,281
0
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
student.cpp
#include"student.h" student::student(string a,string b,int c, float g):person(a,b,c){ cout<<"overloaded constructor called"<<endl; gpa=g; } student::~student(){ cout<<"destructor called for student"<<endl; } void student::setgpa(float a){ gpa=a; } float student::getgpa(){ return gpa; } void student::printstudent(){ printperson(); cout<<" whose gpa is "<<gpa<<endl; }
a7573d0fe44ce4ecbfe92a591307e519e5587f64
464c2c54747a01deafaee52f7f8499810488459b
/TestShell/Simulations/TextureDemo.h
7d8436da8edeaa7daa33647c873a3a9d757df09d
[]
no_license
Harmyder/TestShell
5f85b3d8bdee4f1729e13c67b6b78505c2a778ab
83943c983950e0f74b498348598d03c79a6c6348
refs/heads/master
2021-01-12T08:25:01.066940
2018-05-06T11:46:34
2018-05-06T11:46:34
76,568,480
1
0
null
null
null
null
UTF-8
C++
false
false
422
h
TextureDemo.h
#pragma once #include "Internal\BaseSimulation.h" class TextureDemo : public BaseSimulation { public: CONS_DEC(TextureDemo); ~TextureDemo(); public: void Init() override; void Step(float deltaTime) override; private: std::unique_ptr<Viewer::RenderItemOpaqueRaii> sheet_; std::unique_ptr<Viewer::MaterialRaii> mat_; std::unique_ptr<Pipeline::InputScene> inputScene_; };
61e5fb9fe7de0724d36f619800bdb688737084d3
8a47789c51525551f4ca509bb8ce6d330652f3ab
/Firmware/FFBoard/Inc/I2CHandler.h
92b976d437cfb1ecf9897debd3e2df0ec3623cd2
[ "MIT" ]
permissive
Ultrawipf/OpenFFBoard
1494a9e6c8b6ce146bdc8f512d07717ee5259af8
dc2d3793e4d1d515c6ef6987722c126f736c2f8d
refs/heads/master
2023-08-10T13:47:21.213620
2023-07-20T14:03:21
2023-07-20T14:05:36
239,824,219
394
109
MIT
2023-08-02T07:41:04
2020-02-11T17:36:00
C
UTF-8
C++
false
false
542
h
I2CHandler.h
/* * I2CHandler.h * * Created on: Mar 10, 2022 * Author: Yannick */ #ifndef SRC_I2CHANDLER_H_ #define SRC_I2CHANDLER_H_ #include "global_callbacks.h" class I2CHandler { public: I2CHandler(); virtual ~I2CHandler(); virtual void I2cTxCplt(I2C_HandleTypeDef *hi2c); virtual void I2cRxCplt(I2C_HandleTypeDef *hi2c); virtual void I2cError(I2C_HandleTypeDef *hi2c); static std::vector<I2CHandler*>& getI2CHandlers() { static std::vector<I2CHandler*> i2cHandlers{}; return i2cHandlers; } }; #endif /* SRC_I2CHANDLER_H_ */
841f87ef2da7953d2791fd35c205c20d7b7973f1
46cd3608c7307c3fc140026b901ac2fac87fb418
/Application/Source/Mesh.cpp
7b813bfa8e7e984d0972b9b00b5e9dbc9560a38a
[ "Apache-2.0" ]
permissive
zshaqeel/SP2
d795a2e9a4b7d4b072b0dd84e23a4605c23c1b31
ff4e0373ef7e5864ae89f46d75037381b16b447e
refs/heads/main
2023-03-04T21:30:30.307243
2021-02-15T01:48:47
2021-02-15T01:48:47
338,936,808
0
0
Apache-2.0
2021-02-15T01:02:52
2021-02-15T01:02:52
null
UTF-8
C++
false
false
5,709
cpp
Mesh.cpp
#include "Mesh.h" #include "Vertex.h" #include "GL\glew.h" Mesh::Mesh(const std::string &meshName): name(meshName), mode(DRAW_TRIANGLES), textureID(0) { glGenBuffers(1, &vertexBuffer); glGenBuffers(1, &indexBuffer); } Mesh::~Mesh() { glDeleteBuffers(1, &vertexBuffer); glDeleteBuffers(1, &indexBuffer); if (textureID > 0) { glDeleteTextures(1, &textureID); } } unsigned Mesh::locationKa; unsigned Mesh::locationKd; unsigned Mesh::locationKs; unsigned Mesh::locationNs; void Mesh::SetMaterialLoc(unsigned kA, unsigned kD, unsigned kS, unsigned nS) { locationKa = kA; locationKd = kD; locationKs = kS; locationNs = nS; } void Mesh::Render() { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); if (textureID > 0) glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Position)); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color))); if (textureID > 0) glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color) + sizeof(Vector3))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); if (materials.size() == 0) { switch (mode) { case (DRAW_TRIANGLES): glDrawElements(GL_TRIANGLES, indexSize, GL_UNSIGNED_INT, 0); break; case (DRAW_TRIANGLE_STRIP): glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0); break; case (DRAW_LINES): glDrawElements(GL_LINES, indexSize, GL_UNSIGNED_INT, 0); break; case (DRAW_TRIANGLE_FAN): glDrawElements(GL_TRIANGLE_FAN, indexSize, GL_UNSIGNED_INT, 0); break; default: glDrawElements(GL_TRIANGLES, indexSize, GL_UNSIGNED_INT, 0); break; } } else { for (unsigned i = 0, offset = 0; i < materials.size(); ++i) { Material& material = materials[i]; glUniform3fv(locationKa, 1, &material.kAmbient.r); glUniform3fv(locationKd, 1, &material.kDiffuse.r); glUniform3fv(locationKs, 1, &material.kSpecular.r); glUniform1f(locationNs, material.kShininess); switch (mode) { case (DRAW_TRIANGLES): glDrawElements(GL_TRIANGLES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(unsigned))); break; case (DRAW_TRIANGLE_STRIP): glDrawElements(GL_TRIANGLE_STRIP, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(unsigned))); break; case (DRAW_LINES): glDrawElements(GL_LINES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(unsigned))); break; case (DRAW_TRIANGLE_FAN): glDrawElements(GL_TRIANGLE_FAN, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(unsigned))); break; default: glDrawElements(GL_TRIANGLES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(unsigned))); break; } offset += material.size; } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); if (textureID > 0) glDisableVertexAttribArray(3); } void Mesh::Render(unsigned offset, unsigned count) { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); if (textureID > 0) glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Position)); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color))); if (textureID > 0) glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color) + sizeof(Vector3))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); if (materials.size() == 0) { switch (mode) { case (DRAW_TRIANGLES): glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_TRIANGLE_STRIP): glDrawElements(GL_TRIANGLE_STRIP, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_LINES): glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_TRIANGLE_FAN): glDrawElements(GL_TRIANGLE_FAN, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; default: glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; } } else { for (unsigned i = 0, offset = 0; i < materials.size(); ++i) { Material& material = materials[i]; glUniform3fv(locationKa, 1, &material.kAmbient.r); glUniform3fv(locationKd, 1, &material.kDiffuse.r); glUniform3fv(locationKs, 1, &material.kSpecular.r); glUniform1f(locationNs, material.kShininess); switch (mode) { case (DRAW_TRIANGLES): glDrawElements(GL_TRIANGLES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_TRIANGLE_STRIP): glDrawElements(GL_TRIANGLE_STRIP, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_LINES): glDrawElements(GL_LINES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; case (DRAW_TRIANGLE_FAN): glDrawElements(GL_TRIANGLE_FAN, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; default: glDrawElements(GL_TRIANGLES, material.size, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint))); break; } offset += material.size; } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); if (textureID > 0) glDisableVertexAttribArray(3); }
e158468a46e53ddf7963238d7209f25d9798b0bf
3a5e8004bdec734b78a5bf825a31a64c462506f6
/web.cpp
c53ac47f07ab112662c631723a03dff11ec23a36
[]
no_license
ch0wdan/sprinklers_pi
5bfe33fc516a94072c48e8f1ffc84f62007ba815
46f76d45b0a77c15f68a5dcce877797f20a3da5a
refs/heads/master
2021-01-21T09:46:47.984736
2014-11-03T00:00:15
2014-11-03T00:00:15
26,090,962
1
0
null
null
null
null
UTF-8
C++
false
false
25,487
cpp
web.cpp
// web.cpp // This file manages the web server for the Sprinkler System // Author: Richard Zimmerman // Copyright (c) 2013 Richard Zimmerman // #include "web.h" #include "settings.h" #ifdef ARDUINO #include "nntp.h" #endif #include "Weather.h" #include "sysreset.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include "Event.h" web::web(void) : m_server(0) { } web::~web(void) { if (m_server) delete m_server; m_server = 0; } bool web::Init() { uint16_t port = GetWebPort(); if ((port > 65000) || (port < 80)) port = 80; trace(F("Listening on Port %u\n"), port), m_server = new EthernetServer(port); #ifdef ARDUINO m_server->begin(); return true; #else return m_server->begin(); #endif } static char sendbuf[512]; #ifdef ARDUINO static char * sendbufptr; static inline void setup_sendbuf() { sendbufptr = sendbuf; } static int flush_sendbuf(EthernetClient & client) { int ret = 0; if (sendbufptr > sendbuf) { ret = client.write((uint8_t*)sendbuf, sendbufptr-sendbuf); setup_sendbuf(); } return ret; } static int stream_putchar(char c, FILE *stream) { if (sendbufptr >= sendbuf + sizeof(sendbuf)) { int send_len = ((EthernetClient*)(stream->udata))->write((uint8_t*)sendbuf, sizeof(sendbuf)); if (!send_len) return 0; setup_sendbuf(); } *(sendbufptr++) = c; return 1; } #endif static void ServeHeader(FILE * stream_file, int code, const char * pReason, bool cache, const char * type = "text/html") { fprintf_P(stream_file, PSTR("HTTP/1.1 %d %s\nContent-Type: %s\n"), code, pReason, type); if (cache) fprintf_P(stream_file, PSTR("Last-Modified: Fri, 02 Jun 2006 09:46:32 GMT\nExpires: Sun, 17 Jan 2038 19:14:07 GMT\n")); else fprintf_P(stream_file, PSTR("Cache-Control: no-cache\n")); fputc('\n', stream_file); } static void Serve404(FILE * stream_file) { ServeHeader(stream_file, 404, "NOT FOUND", false); fprintf(stream_file, "NOT FOUND"); } static void ServeError(FILE * stream_file) { ServeHeader(stream_file, 405, "NOT ALLOWED", false); fprintf(stream_file, "NOT ALLOWED"); } static void JSONSchedules(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); int iNumSchedules = GetNumSchedules(); fprintf(stream_file, "{\n\"Table\" : [\n"); Schedule sched; for (int i = 0; i < iNumSchedules; i++) { LoadSchedule(i, &sched); fprintf_P(stream_file, PSTR("%s\t{\"id\" : %d, \"name\" : \"%s\", \"e\" : \"%s\" }"), (i == 0) ? "" : ",\n", i, sched.name, (sched.IsEnabled()) ? "on" : "off"); } fprintf(stream_file, "\n]}"); } static void JSONZones(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); fprintf_P(stream_file, PSTR("{\n\"zones\" : [\n")); FullZone zone = {0}; for (int i = 0; i < NUM_ZONES; i++) { LoadZone(i, &zone); fprintf_P(stream_file, PSTR("%s\t{\"name\" : \"%s\", \"enabled\" : \"%s\", \"pump\" : \"%s\", \"state\" : \"%s\" }"), (i == 0) ? "" : ",\n", zone.name, zone.bEnabled ? "on" : "off", zone.bPump ? "on" : "off", isZoneOn(i + 1) ? "on" : "off"); } fprintf(stream_file, "\n]}"); } #ifdef LOGGING static void JSONLogs(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); fprintf(stream_file, "{\n"); time_t sdate = 0; time_t edate = 0; Logging::GROUPING grouping = Logging::NONE; // Iterate through the kv pairs and search for the start and end dates. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if (strcmp(key, "sdate") == 0) { sdate = strtol(value, 0, 10); } else if (strcmp(key, "edate") == 0) { edate = strtol(value, 0, 10); } else if (strcmp(key, "g") == 0) { if (value[0] == 'h') grouping = Logging::HOURLY; else if (value[0] == 'd') grouping = Logging::DAILY; else if (value[0] == 'm') grouping = Logging::MONTHLY; } } log.GraphZone(stream_file, sdate, edate, grouping); fprintf(stream_file, "}"); } static void JSONtLogs(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); fprintf(stream_file, "{\n\t\"logs\": [\n"); time_t sdate = 0; time_t edate = 0; // Iterate through the kv pairs and search for the start and end dates. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if (strcmp(key, "sdate") == 0) { sdate = strtol(value, 0, 10); } else if (strcmp(key, "edate") == 0) { edate = strtol(value, 0, 10); } } log.TableZone(stream_file, sdate, edate); fprintf(stream_file, "\t]\n}"); } #endif static void JSONSettings(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); IPAddress ip; fprintf(stream_file, "{\n"); #ifdef ARDUINO ip = GetIP(); fprintf_P(stream_file, PSTR("\t\"ip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]); ip = GetNetmask(); fprintf_P(stream_file, PSTR("\t\"netmask\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]); ip = GetGateway(); fprintf_P(stream_file, PSTR("\t\"gateway\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]); ip = GetNTPIP(); fprintf_P(stream_file, PSTR("\t\"NTPip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]); fprintf_P(stream_file, PSTR("\t\"NTPoffset\" : \"%d\",\n"), GetNTPOffset()); #endif fprintf_P(stream_file, PSTR("\t\"webport\" : \"%u\",\n"), GetWebPort()); fprintf_P(stream_file, PSTR("\t\"ot\" : \"%d\",\n"), GetOT()); ip = GetWUIP(); fprintf_P(stream_file, PSTR("\t\"wuip\" : \"%d.%d.%d.%d\",\n"), ip[0], ip[1], ip[2], ip[3]); fprintf_P(stream_file, PSTR("\t\"wutype\" : \"%s\",\n"), GetUsePWS() ? "pws" : "zip"); fprintf_P(stream_file, PSTR("\t\"zip\" : \"%ld\",\n"), (long) GetZip()); fprintf_P(stream_file, PSTR("\t\"sadj\" : \"%ld\",\n"), (long) GetSeasonalAdjust()); char ak[17]; GetApiKey(ak); fprintf_P(stream_file, PSTR("\t\"apikey\" : \"%s\",\n"), ak); GetPWS(ak); ak[11] = 0; fprintf_P(stream_file, PSTR("\t\"pws\" : \"%s\"\n"), ak); fprintf(stream_file, "}"); } static void JSONwCheck(const KVPairs & key_value_pairs, FILE * stream_file) { Weather w; ServeHeader(stream_file, 200, "OK", false, "text/plain"); char key[17]; GetApiKey(key); char pws[12] = {0}; GetPWS(pws); const Weather::ReturnVals vals = w.GetVals(GetWUIP(), key, GetZip(), pws, GetUsePWS()); const int scale = w.GetScale(vals); fprintf(stream_file, "{\n"); fprintf_P(stream_file, PSTR("\t\"valid\" : \"%s\",\n"), vals.valid ? "true" : "false"); fprintf_P(stream_file, PSTR("\t\"keynotfound\" : \"%s\",\n"), vals.keynotfound ? "true" : "false"); fprintf_P(stream_file, PSTR("\t\"minhumidity\" : \"%d\",\n"), vals.minhumidity); fprintf_P(stream_file, PSTR("\t\"maxhumidity\" : \"%d\",\n"), vals.maxhumidity); fprintf_P(stream_file, PSTR("\t\"meantempi\" : \"%d\",\n"), vals.meantempi); fprintf_P(stream_file, PSTR("\t\"precip_today\" : \"%d\",\n"), vals.precip_today); fprintf_P(stream_file, PSTR("\t\"precip\" : \"%d\",\n"), vals.precipi); fprintf_P(stream_file, PSTR("\t\"wind_mph\" : \"%d\",\n"), vals.windmph); fprintf_P(stream_file, PSTR("\t\"UV\" : \"%d\",\n"), vals.UV); fprintf_P(stream_file, PSTR("\t\"scale\" : \"%d\"\n"), scale); fprintf(stream_file, "}"); } static void JSONState(const KVPairs & key_value_pairs, FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false, "text/plain"); fprintf_P(stream_file, PSTR("{\n\t\"version\" : \"%s\",\n\t\"run\" : \"%s\",\n\t\"zones\" : \"%d\",\n\t\"schedules\" : \"%d\",\n\t\"timenow\" : \"%lu\",\n\t\"events\" : \"%d\""), VERSION, GetRunSchedules() ? "on" : "off", GetNumEnabledZones(), GetNumSchedules(), nntpTimeServer.LocalNow(), iNumEvents); if (runState.isSchedule() || runState.isManual()) { FullZone zone; LoadZone(runState.getZone() - 1, &zone); long time_check = runState.getEndTime() * 60L - (nntpTimeServer.LocalNow() - previousMidnight(nntpTimeServer.LocalNow())); if (runState.isManual()) time_check = 99999; fprintf_P(stream_file, PSTR(",\n\t\"onzone\" : \"%s\",\n\t\"offtime\" : \"%ld\""), zone.name, time_check); } fprintf_P(stream_file, (PSTR("\n}"))); } static void JSONSchedule(const KVPairs & key_value_pairs, FILE * stream_file) { int sched_num = -1; freeMemory(); // Iterate through the kv pairs and search for the id. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if (strcmp(key, "id") == 0) { sched_num = atoi(value); } } // Now check to see if the id is in range. const uint8_t numSched = GetNumSchedules(); if ((sched_num < 0) || (sched_num >= numSched)) { ServeError(stream_file); return; } // Now construct the response and send it ServeHeader(stream_file, 200, "OK", false, "text/plain"); Schedule sched; LoadSchedule(sched_num, &sched); fprintf_P(stream_file, PSTR("{\n\t\"name\" : \"%s\",\n\t\"enabled\" : \"%s\",\n\t\"wadj\" : \"%s\",\n\t\"type\" : \"%s\",\n\t\"d1\" : \"%s\",\n\t\"d2\" : \"%s\""), sched.name, sched.IsEnabled() ? "on" : "off", sched.IsWAdj() ? "on" : "off", sched.IsInterval() ? "off" : "on", sched.day & 0x01 ? "on" : "off", sched.day & 0x02 ? "on" : "off"); fprintf_P(stream_file, PSTR(",\n\t\"d3\" : \"%s\",\n\t\"d4\" : \"%s\",\n\t\"d5\" : \"%s\",\n\t\"d6\" : \"%s\",\n\t\"d7\" : \"%s\",\n\t\"interval\" : \"%d\",\n\t\"times\" : [\n"), sched.day & 0x04 ? "on" : "off", sched.day & 0x08 ? "on" : "off", sched.day & 0x10 ? "on" : "off", sched.day & 0x20 ? "on" : "off", sched.day & 0x40 ? "on" : "off", sched.interval); for (int i = 0; i < 4; i++) { if (sched.time[i] == -1) { fprintf_P(stream_file, PSTR("%s\t\t{\"t\" : \"00:00\", \"e\" : \"off\" }"), (i == 0) ? "" : ",\n"); } else { fprintf_P(stream_file, PSTR("%s\t\t{\"t\" : \"%02d:%02d\", \"e\" : \"on\" }"), (i == 0) ? "" : ",\n", sched.time[i] / 60, sched.time[i] % 60); } } fprintf_P(stream_file, PSTR("\n\t],\n\t\"zones\" : [\n")); for (int i = 0; i < NUM_ZONES; i++) { FullZone zone; LoadZone(i, &zone); fprintf(stream_file, "%s\t\t{\"name\" : \"%s\", \"e\":\"%s\", \"duration\" : %d}", (i == 0) ? "" : ",\n", zone.name, zone.bEnabled ? "on" : "off", sched.zone_duration[i]); } fprintf(stream_file, " ]\n}"); } static bool SetQSched(const KVPairs & key_value_pairs) { // So, we first end any schedule that's currently running by turning things off then on again. ReloadEvents(); int sched = -1; // Iterate through the kv pairs and update the appropriate structure values. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if ((key[0] == 'z') && (key[1] > 'a') && (key[1] <= ('a' + NUM_ZONES)) && (key[2] == 0)) { quickSchedule.zone_duration[key[1] - 'b'] = atoi(value); } if (strcmp(key, "sched") == 0) { sched = atoi(value); } } if (sched == -1) LoadSchedTimeEvents(0, true); else LoadSchedTimeEvents(sched); return true; } static void ServeEventPage(FILE * stream_file) { ServeHeader(stream_file, 200, "OK", false); freeMemory(); const time_t timeNow = nntpTimeServer.LocalNow(); fprintf_P(stream_file, PSTR("<h1>%d Events</h1><h3>%02d:%02d:%02d %d/%d/%d (%d)</h3>"), iNumEvents, hour(timeNow), minute(timeNow), second(timeNow), year(timeNow), month(timeNow), day(timeNow), weekday(timeNow)); for (uint8_t i = 0; i < iNumEvents; i++) fprintf_P(stream_file, PSTR("Event [%02d] Time:%02d:%02d(%d) Command %d data %d,%d<br/>"), i, events[i].time / 60, events[i].time % 60, events[i].time, events[i].command, events[i].data[0], events[i].data[1]); } static void ServeSchedPage(FILE * stream_file) { Schedule sched; freeMemory(); ServeHeader(stream_file, 200, "OK", false); const uint8_t numSched = GetNumSchedules(); for (uint8_t iSchedNum = 0; iSchedNum < numSched; iSchedNum++) { LoadSchedule(iSchedNum, &sched); fprintf_P(stream_file, PSTR("<hr/>Schedule #%d<br/>"), iSchedNum); if (sched.IsEnabled()) fprintf_P(stream_file, PSTR("Enabled")); else fprintf_P(stream_file, PSTR("Not Enabled")); fprintf_P(stream_file, PSTR("<br/>Name:%s<br/>"), sched.name); if (sched.IsInterval()) fprintf_P(stream_file, PSTR("Interval : %d"), sched.interval); else { fprintf_P(stream_file, PSTR("Day :")); if (sched.day & 0x01) fprintf(stream_file, "Su"); if (sched.day & 0x02) fprintf(stream_file, "M"); if (sched.day & 0x04) fprintf(stream_file, "T"); if (sched.day & 0x08) fprintf(stream_file, "W"); if (sched.day & 0x10) fprintf(stream_file, "R"); if (sched.day & 0x20) fprintf(stream_file, "F"); if (sched.day & 0x40) fprintf(stream_file, "Sa"); fprintf_P(stream_file, PSTR("(%d)"), sched.day); } for (uint8_t i = 0; i < 4; i++) fprintf_P(stream_file, PSTR("<br/>Time %d:%02d:%02d(%d)"), i + 1, sched.time[i] / 60, sched.time[i] % 60, sched.time[i]); for (uint8_t i = 0; i < NUM_ZONES; i++) fprintf_P(stream_file, PSTR("<br/>Zone %d Duration:%d"), i + 1, sched.zone_duration[i]); } } static void ServeZonesPage(FILE * stream_file) { FullZone zone; ServeHeader(stream_file, 200, "OK", false); for (uint8_t iZoneNum = 0; iZoneNum < NUM_ZONES; iZoneNum++) { LoadZone(iZoneNum, &zone); fprintf_P(stream_file, PSTR("<hr/>Zone #%d<br/>"), iZoneNum); if (zone.bEnabled) fprintf_P(stream_file, PSTR("Enabled")); else fprintf_P(stream_file, PSTR("Not Enabled")); fprintf_P(stream_file, PSTR("<br/>Name:%s<br/>"), zone.name); if (zone.bPump) fprintf_P(stream_file, PSTR("Pump ON")); else fprintf_P(stream_file, PSTR("Pump OFF")); } } static bool RunSchedules(const KVPairs & key_value_pairs) { // Iterate through the kv pairs and update the appropriate structure values. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if (strcmp(key, "system") == 0) { SetRunSchedules(strcmp(value, "on") == 0); } } return true; } static bool ManualZone(const KVPairs & key_value_pairs) { freeMemory(); // Turn off the current schedules. SetRunSchedules(false); bool bOn = false; int iZoneNum = -1; // Iterate through the kv pairs and update the appropriate structure values. for (int i = 0; i < key_value_pairs.num_pairs; i++) { const char * key = key_value_pairs.keys[i]; const char * value = key_value_pairs.values[i]; if ((strcmp(key, "zone") == 0) && (value[0] == 'z') && (value[1] > 'a') && (value[1] <= ('a' + NUM_ZONES))) { iZoneNum = value[1] - 'a'; } else if (strcmp(key, "state") == 0) { if (strcmp(value, "on") == 0) bOn = true; else bOn = false; } } if ((iZoneNum >= 0) && bOn) { TurnOnZone(iZoneNum); runState.SetManual(true, iZoneNum); } else { TurnOffZones(); runState.SetManual(false); } return true; } static void ServeFile(FILE * stream_file, const char * fname, SdFile & theFile, EthernetClient & client) { freeMemory(); const char * ext; for (ext=fname + strlen(fname); ext>fname; ext--) if (*ext == '.') { ext++; break; } if (ext > fname) { if (strcmp(ext, "jpg") == 0) ServeHeader(stream_file, 200, "OK", true, "image/jpeg"); else if (strcmp(ext, "gif") == 0) ServeHeader(stream_file, 200, "OK", true, "image/gif"); else if (strcmp(ext, "css") == 0) ServeHeader(stream_file, 200, "OK", true, "text/css"); else if (strcmp(ext, "js") == 0) ServeHeader(stream_file, 200, "OK", true, "application/javascript"); else if (strcmp(ext, "ico") == 0) ServeHeader(stream_file, 200, "OK", true, "image/x-icon"); else ServeHeader(stream_file, 200, "OK", true); } else ServeHeader(stream_file, 200, "OK", true); #ifdef ARDUINO flush_sendbuf(client); #else fflush(stream_file); #endif while (theFile.available()) { int bytes = theFile.read(sendbuf, 512); if (bytes <= 0) break; client.write((uint8_t*) sendbuf, bytes); } } // change a character represented hex digit (0-9, a-f, A-F) to the numeric value static inline char hex2int(const char ch) { if (ch < 48) return 0; else if (ch <=57) // 0-9 return (ch - 48); else if (ch < 65) return 0; else if (ch <=70) // A-F return (ch - 55); else if (ch < 97) return 0; else if (ch <=102) // a-f return ch - 87; else return 0; } // Pass in a connected client, and this function will parse the HTTP header and return the requested page // and a KV pairs structure for the variable assignments. static bool ParseHTTPHeader(EthernetClient & client, KVPairs * key_value_pairs, char * sPage, int iPageSize) { enum { INITIALIZED = 0, PARSING_PAGE, PARSING_KEY, PARSING_VALUE, PARSING_VALUE_PERCENT, PARSING_VALUE_PERCENT1, LOOKING_FOR_BLANKLINE, FOUND_BLANKLINE, DONE, ERROR } current_state = INITIALIZED; // an http request ends with a blank line static const char get_text[] = "GET /"; const char * gettext_ptr = get_text; char * page_ptr = sPage; key_value_pairs->num_pairs = 0; char * key_ptr = key_value_pairs->keys[0]; char * value_ptr = key_value_pairs->values[0]; char recvbuf[100]; // note: trial and error has shown that it doesn't help to increase this number.. few ms at the most. char * recvbufptr = recvbuf; char * recvbufend = recvbuf; while (true) { if (recvbufptr >= recvbufend) { int len = client.read((uint8_t*) recvbuf, sizeof(recvbuf)); if (len <= 0) { if (!client.connected()) break; else continue; } else { recvbufptr = recvbuf; recvbufend = recvbuf + len; } } char c = *(recvbufptr++); //Serial.print(c); switch (current_state) { case INITIALIZED: if (c == *gettext_ptr) { gettext_ptr++; if (gettext_ptr - get_text >= (long)sizeof(get_text) - 1) { current_state = PARSING_PAGE; } } break; case PARSING_PAGE: if (c == '?') { *page_ptr = 0; current_state = PARSING_KEY; } else if (c == ' ') { *page_ptr = 0; current_state = LOOKING_FOR_BLANKLINE; } else if (c == '\n') { *page_ptr = 0; current_state = FOUND_BLANKLINE; } else if ((c > 32) && (c < 127)) { if (page_ptr - sPage >= iPageSize - 1) { current_state = ERROR; } else *page_ptr++ = c; } break; case PARSING_KEY: if (c == ' ') current_state = LOOKING_FOR_BLANKLINE; else if (c == '\n') { current_state = FOUND_BLANKLINE; } else if (c == '&') { current_state = ERROR; } else if (c == '=') { *key_ptr = 0; current_state = PARSING_VALUE; } else if ((c > 32) && (c < 127)) { if (key_ptr - key_value_pairs->keys[key_value_pairs->num_pairs] >= KEY_SIZE - 1) { current_state = ERROR; } else *key_ptr++ = c; } break; case PARSING_VALUE: case PARSING_VALUE_PERCENT: case PARSING_VALUE_PERCENT1: if ((c == ' ') || c == '&') { *value_ptr = 0; trace(F("Found a KV pair : %s -> %s\n"), key_value_pairs->keys[key_value_pairs->num_pairs], key_value_pairs->values[key_value_pairs->num_pairs]); if ((c == '&') && (key_value_pairs->num_pairs >= NUM_KEY_VALUES - 1)) { current_state = ERROR; break; } if (c == '&') { key_value_pairs->num_pairs++; key_ptr = key_value_pairs->keys[key_value_pairs->num_pairs]; value_ptr = key_value_pairs->values[key_value_pairs->num_pairs]; current_state = PARSING_KEY; } else { key_value_pairs->num_pairs++; current_state = LOOKING_FOR_BLANKLINE; } break; } else if ((c > 32) && (c < 127)) { if (value_ptr - key_value_pairs->values[key_value_pairs->num_pairs] >= VALUE_SIZE - 1) { current_state = ERROR; break; } switch (current_state) { case PARSING_VALUE_PERCENT: if (isxdigit(c)) { *value_ptr = hex2int(c) << 4; current_state = PARSING_VALUE_PERCENT1; } else current_state = PARSING_VALUE; break; case PARSING_VALUE_PERCENT1: if (isxdigit(c)) { *value_ptr += hex2int(c); // let's check this value to see if it's legal if (((*value_ptr >= 0 ) && (*value_ptr < 32)) || (*value_ptr == 127) || (*value_ptr == '"') || (*value_ptr == '\\')) *value_ptr = ' '; value_ptr++; } current_state = PARSING_VALUE; break; default: if (c == '+') *value_ptr++ = ' '; else if (c == '%') current_state = PARSING_VALUE_PERCENT; else *value_ptr++ = c; break; } } else current_state = ERROR; break; case LOOKING_FOR_BLANKLINE: if (c == '\n') current_state = FOUND_BLANKLINE; break; case FOUND_BLANKLINE: if (c == '\n') current_state = DONE; else if (c != '\r') current_state = LOOKING_FOR_BLANKLINE; break; default: break; } // switch if (current_state == DONE) return true; else if (current_state == ERROR) return false; } // true return false; } void web::ProcessWebClients() { // listen for incoming clients EthernetClient client = m_server->available(); if (client) { bool bReset = false; #ifdef ARDUINO FILE stream_file; FILE * pFile = &stream_file; setup_sendbuf(); fdev_setup_stream(pFile, stream_putchar, NULL, _FDEV_SETUP_WRITE); stream_file.udata = &client; #else FILE * pFile = fdopen(client.GetSocket(), "w"); #endif freeMemory(); trace(F("Got a client\n")); //ShowSockStatus(); KVPairs key_value_pairs; char sPage[35]; if (!ParseHTTPHeader(client, &key_value_pairs, sPage, sizeof(sPage))) { trace(F("ERROR!\n")); ServeError(pFile); } else { trace(F("Page:%s\n"), sPage); //ShowSockStatus(); if (strcmp(sPage, "bin/setSched") == 0) { if (SetSchedule(key_value_pairs)) { if (GetRunSchedules()) ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/setZones") == 0) { if (SetZones(key_value_pairs)) { ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/delSched") == 0) { if (DeleteSchedule(key_value_pairs)) { if (GetRunSchedules()) ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/setQSched") == 0) { if (SetQSched(key_value_pairs)) { ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/settings") == 0) { if (SetSettings(key_value_pairs)) { ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/manual") == 0) { if (ManualZone(key_value_pairs)) { ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/run") == 0) { if (RunSchedules(key_value_pairs)) { ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else ServeError(pFile); } else if (strcmp(sPage, "bin/factory") == 0) { ResetEEPROM(); ReloadEvents(); ServeHeader(pFile, 200, "OK", false); } else if (strcmp(sPage, "bin/reset") == 0) { ServeHeader(pFile, 200, "OK", false); bReset = true; } else if (strcmp(sPage, "json/schedules") == 0) { JSONSchedules(key_value_pairs, pFile); } else if (strcmp(sPage, "json/zones") == 0) { JSONZones(key_value_pairs, pFile); } else if (strcmp(sPage, "json/settings") == 0) { JSONSettings(key_value_pairs, pFile); } else if (strcmp(sPage, "json/state") == 0) { JSONState(key_value_pairs, pFile); } else if (strcmp(sPage, "json/schedule") == 0) { JSONSchedule(key_value_pairs, pFile); } else if (strcmp(sPage, "json/wcheck") == 0) { JSONwCheck(key_value_pairs, pFile); } #ifdef LOGGING else if (strcmp(sPage, "json/logs") == 0) { JSONLogs(key_value_pairs, pFile); } else if (strcmp(sPage, "json/tlogs") == 0) { JSONtLogs(key_value_pairs, pFile); } #endif else if (strcmp(sPage, "ShowSched") == 0) { freeMemory(); ServeSchedPage(pFile); } else if (strcmp(sPage, "ShowZones") == 0) { freeMemory(); ServeZonesPage(pFile); } else if (strcmp(sPage, "ShowEvent") == 0) { ServeEventPage(pFile); } else if (strcmp(sPage, "ReloadEvent") == 0) { ReloadEvents(true); ServeEventPage(pFile); } else { if (strlen(sPage) == 0) strcpy(sPage, "index.htm"); // prepend path memmove(sPage + 5, sPage, sizeof(sPage) - 5); memcpy(sPage, "/web/", 5); sPage[sizeof(sPage)-1] = 0; trace(F("Serving Page: %s\n"), sPage); SdFile theFile; if (!theFile.open(sPage, O_READ)) Serve404(pFile); else { if (theFile.isFile()) ServeFile(pFile, sPage, theFile, client); else Serve404(pFile); theFile.close(); } } } #ifdef ARDUINO flush_sendbuf(client); // give the web browser time to receive the data delay(1); #else fflush(pFile); fclose(pFile); #endif // close the connection: client.stop(); if (bReset) sysreset(); } }
b7b6d38fac13c976a25aeddc9265a869de6182ba
ca58c853fcf7f82c74cbf3e16335e2caab2ad618
/src/selectfilesdialog/selectfilesdialog.cpp
d567e89af2a76105da20f3dc68b08e4fa1eb21fc
[]
no_license
kerasking/9News
dc6ef899de7554e0d3f3511560b94454c171407e
b7affd69c26b90cc08e12b08ab67ae4ce555190f
refs/heads/master
2021-05-29T15:24:28.043609
2014-11-29T17:14:52
2014-11-29T17:14:52
27,329,106
1
0
null
null
null
null
UTF-8
C++
false
false
7,518
cpp
selectfilesdialog.cpp
#include "selectfilesdialog.h" #include <QDebug> #include <QApplication> #include <QDeclarativeEngine> #include <QDeclarativeContext> #include <QDeclarativeView> #include <QFile> SelectFilesDialog::SelectFilesDialog() : QObject(0) { lastOpenMode = false; m_chooseType = AllType; m_chooseMode = MultipleChoice; m_inverseTheme = false; isShow = false; connect(this, SIGNAL(close()), SLOT(onClose())); QFile file(":/selectfilesdialog/icon/configure.bat"); if(file.open(QIODevice::ReadOnly)){ QString temp_str = file.readLine(); int temp_pos = temp_str.lastIndexOf(QRegExp("\\S")); if(temp_pos>=0) temp_str = temp_str.left(temp_pos+1); while(temp_str!=""){ IconInfo info; QStringList temp_list = temp_str.split(":"); info.filePath = temp_list[0]; info.suffixList = temp_list.at(1).split(" "); iconInfoList<<info; temp_str = file.readLine(); temp_pos = temp_str.lastIndexOf(QRegExp("\\S")); if(temp_pos>=0) temp_str = temp_str.left(temp_pos+1); //qDebug()<<temp_str; } }else{ qDebug()<<QString::fromUtf8("SelectFilesDialog:configure.bat打开失败")<<file.errorString(); } } int SelectFilesDialog::selectionCount() const { return files.length(); } SelectFilesDialog::ChooseType SelectFilesDialog::chooseType() const { return m_chooseType; } SelectFilesDialog::ChooseMode SelectFilesDialog::chooseMode() const { return m_chooseMode; } bool SelectFilesDialog::inverseTheme() const { return m_inverseTheme; } void SelectFilesDialog::open(const QUrl initPath, const QString &nameFilters, Filters filters, SortFlags sortflags) { if(isShow){ qmlView->showFullScreen(); return; } isShow = true; //qDebug()<<((QDir::Filters)((int)filters))<<((QDir::SortFlags)((int)sortflags)); files.clear(); if(!lastOpenMode) dir = new QDir(initPath.toLocalFile()); lastOpenMode = true; dir->setFilter((QDir::Filters)((int)filters)); dir->setSorting((QDir::SortFlags)((int)sortflags)); if(nameFilters!=""){ QStringList temp_list = nameFilters.split(";"); dir->setNameFilters(temp_list); } qmlView = new QDeclarativeView(); qmlView->engine()->rootContext()->setContextProperty("fileDialog", this); #ifdef HARMATTAN_BOOSTER qmlView->setSource(QUrl("qrc:/selectfilesdialog/meego.qml")); #else qmlView->setSource(QUrl("qrc:/selectfilesdialog/symbian.qml")); #endif qmlView->showFullScreen(); } int SelectFilesDialog::exec(const QUrl initPath, const QString &nameFilters, Filters filters, SortFlags sortflags) { if(isShow){ qmlView->showFullScreen(); return -1; } isShow = true; //qDebug()<<((QDir::Filters)((int)filters))<<((QDir::SortFlags)((int)sortflags)); files.clear(); if(lastOpenMode) delete this->dir; lastOpenMode = false; QDir dir(initPath.toLocalFile()); this->dir = &dir; dir.setFilter((QDir::Filters)((int)filters)); dir.setSorting((QDir::SortFlags)((int)sortflags)); if(nameFilters!=""){ QStringList temp_list = nameFilters.split(";"); dir.setNameFilters(temp_list); } QDeclarativeView view; qmlView = &view; view.engine()->rootContext()->setContextProperty("fileDialog", this); #ifdef HARMATTAN_BOOSTER view.setSource(QUrl("qrc:/selectfilesdialog/meego.qml")); #else view.setSource(QUrl("qrc:/selectfilesdialog/symbian.qml")); #endif QEventLoop loop; connect(this, SIGNAL(close()), &loop, SLOT(quit())); view.showFullScreen(); int result = loop.exec(QEventLoop::DialogExec); view.close(); return result; } QVariantMap SelectFilesDialog::firstSelection() const { Data data = files.first(); QVariantMap map; map["name"] = data.name; map["type"] = data.type; return map; } QVariantMap SelectFilesDialog::lastSelection() const { Data data = files.last(); QVariantMap map; map["name"] = data.name; map["type"] = data.type; return map; } QVariantMap SelectFilesDialog::at(int index) const { Data data = files[index]; QVariantMap map; map["name"] = data.name; map["type"] = data.type; return map; } QVariantList SelectFilesDialog::allSelection() const { QVariantList result_list; foreach(Data data, files){ QVariantMap map; map["name"] = data.name; map["type"] = data.type; result_list<<map; } return result_list; } QVariantList SelectFilesDialog::getCurrentFilesInfo() const { QVariantList result_list; foreach(QFileInfo file_info, dir->entryInfoList()){ if(file_info.fileName()=="."||file_info.fileName()=="..") continue; QVariantMap temp_map; temp_map["name"] = file_info.fileName(); temp_map["path"] = file_info.absolutePath(); temp_map["size"] = ((int)((file_info.size()/1024.0)*100))/100.0; temp_map["suffix"] = file_info.suffix(); temp_map["lastModified"] = file_info.lastModified().toString(); if(file_info.isFile()){ temp_map["type"] = FileType; }else{ temp_map["type"] = FolderType; temp_map["isEmpty"] = dirIsEmpty(file_info); } result_list<<temp_map; } return result_list; } bool SelectFilesDialog::cdPath(const QString &newPath) { return dir->cd(newPath); } void SelectFilesDialog::addSelection(ChooseType type, const QString &absolutePath) { Data data; data.name = absolutePath; data.type = type; files.append(data); } void SelectFilesDialog::removeSelection(const QString &absolutePath) { for(int i=0; i<files.count(); ++i){ Data data = files[i]; if(data.name == absolutePath){ files.removeAt(i); } } } void SelectFilesDialog::clearSelection() { files.clear(); } void SelectFilesDialog::setChooseType(ChooseType arg) { if (m_chooseType != arg) { m_chooseType = arg; emit chooseTypeChanged(arg); } } void SelectFilesDialog::setChooseMode(ChooseMode arg) { if (m_chooseMode != arg) { m_chooseMode = arg; emit chooseModeChanged(arg); } } QString SelectFilesDialog::getIconNameBySuffix(const QString &suffix) const { foreach(IconInfo info, iconInfoList){ foreach(QString str, info.suffixList){ if(str == suffix){ return "qrc:/selectfilesdialog/icon/"+info.filePath; } } } return "qrc:/selectfilesdialog/icon/unknow"; } void SelectFilesDialog::setInverseTheme(bool arg) { if (m_inverseTheme != arg) { m_inverseTheme = arg; emit inverseThemeChanged(arg); } } bool SelectFilesDialog::dirIsEmpty(const QFileInfo &fileInfo) const { QDir dir = fileInfo.dir(); dir.cd(fileInfo.fileName()); return dir.entryList().length()<=2; } void SelectFilesDialog::onClose() { if(lastOpenMode){//如果是调用open打开的对话框 qmlView->deleteLater(); } isShow = false; }
6bedf032dd609f8d76e6b401167a73a3088858d8
24cc159a4b2c416ff7c7457003cd5202c2de322f
/noor/header/options.h
819cb0e9bdca0da495cbeaecd31984ac53829a14
[]
no_license
Ardook/noor
2853c60e550d1332d6eaaee131d1b85438616a25
4097399149298d36824927db92d10f6e9bbe086f
refs/heads/master
2021-01-08T11:17:49.302397
2018-10-18T14:48:22
2018-10-18T14:48:22
135,198,783
3
0
null
null
null
null
UTF-8
C++
false
false
13,347
h
options.h
/* MIT License Copyright (c) 2015-2018 Ardavan Kanani Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef OPTIONS_H #define OPTIONS_H const std::string texture_dir( "../../docs/scenes/textures/" ); const std::vector<std::string> hdr_files = { /*0*/std::string( texture_dir + "hdri/env.hdr" ), /*1*/std::string( texture_dir + "hdri/skylight-morn.exr" ), /*2*/std::string( texture_dir + "hdri/pisa_latlong.exr" ), /*3*/std::string( texture_dir + "hdri/sky.exr" ), /*4*/std::string( texture_dir + "hdri/hdri_sky_01_full.hdr" ), /*5*/std::string( texture_dir + "hdri/hdri_sky_02_full.hdr" ), /*6*/std::string( texture_dir + "hdri/hdri_sky_03_full.hdr" ), /*7*/std::string( texture_dir + "hdri/georgentor_4k.hdr" ), /*8*/std::string( texture_dir + "hdri/vignaioli_night_4k.hdr" ), /*9*/std::string( texture_dir + "hdri/hotel_room_4k.hdr" ), /*10*/std::string( texture_dir + "hdri/hall_con.hdr" ), /*11*/std::string( texture_dir + "hdri/envmap.exr" ), /*12*/std::string( texture_dir + "hdri/harties_4k.hdr" ), /*13*/std::string( texture_dir + "hdri/flower_road_4k.hdr" ), /*14*/std::string( texture_dir + "hdri/noon_grass_4k.hdr" ), /*15*/std::string( texture_dir + "hdri/umhlanga_sunrise_4k.hdr" ), /*16*/std::string( texture_dir + "hdri/moonlit_golf_4k.hdr" ), /*17*/std::string( texture_dir + "hdri/kiara_6_afternoon_4k.hdr" ), /*18*/std::string( texture_dir + "hdri/flower_road_4k.hdr" ), /*19*/std::string( texture_dir + "hdri/symmetrical_garden_4k.hdr" ), /*20*/std::string( texture_dir + "hdri/aft_lounge_4k.hdr" ), /*21*/std::string( texture_dir + "hdri/royal_esplanade_4k.hdr" ), /*22*/std::string( texture_dir + "hdri/satara_night_8k.hdr" ), /*23*/std::string( texture_dir + "hdri/umhlanga_sunrise_8k.hdr" ), /*24*/std::string( texture_dir + "hdri/cayley_interior_8k.hdr" ), /*25*/std::string( texture_dir + "hdri/canada_montreal_loft_max_sunny.exr" ), /*26*/std::string( texture_dir + "hdri/canada_montreal_nad_cafeteria_bright.exr" ), /*27*/std::string( texture_dir + "hdri/canada_montreal_nad_photorealism.exr" ), /*28*/std::string( texture_dir + "hdri/canada_montreal_pierre_bathroom.exr" ), /*29*/std::string( texture_dir + "hdri/canada_montreal_pierre_kitchen.exr" ), /*30*/std::string( texture_dir + "hdri/canada_montreal_thea.exr" ), }; const std::string models_dir( "../../docs/scenes/models/" ); const std::vector<std::string> model_files = { /*0*/ std::string( models_dir + "obj/cornell-box/CornellBox-Original.obj" ) /*1*/ ,std::string( models_dir + "obj/cornell-box/CornellBox-Sphere.obj" ) /*2*/ ,std::string( models_dir + "obj/cornell-box/CornellBox-Glossy.obj" ) /*3*/ ,std::string( models_dir + "obj/cornell-box/CornellBox-Mirror.obj" ) /*4*/ ,std::string( models_dir + "obj/mitsuba/mitsuba.obj" ) /*5*/ ,std::string( models_dir + "obj/head/head.obj" ) /*6*/ ,std::string( models_dir + "obj/f16/f16.obj" ) /*7*/ ,std::string( models_dir + "obj/dabrovic-sponza/sponza.obj" ) /*8*/ ,std::string( models_dir + "obj/lost-empire/lost_empire.obj" ) /*9*/ ,std::string( models_dir + "obj/rungholt/rungholt3.obj" ) /*10*/ ,std::string( models_dir + "obj/sgi/sgi.obj" ) /*11*/ ,std::string( models_dir + "obj/bunny/bunny.obj" ) /*12*/ ,std::string( models_dir + "obj/chess/chessbox.obj" ) /*13*/ ,std::string( models_dir + "obj/treespaceship/treespaceship.obj" ) /*14*/ ,std::string( models_dir + "obj/trees/tree.obj" ) /*15*/ ,std::string( models_dir + "obj/rose/rose.obj" ) /*16*/ ,std::string( models_dir + "obj/corvette/corvette.obj" ) /*17*/ ,std::string( models_dir + "obj/lonelytree/lonelytree.obj" ) /*18*/ ,std::string( models_dir + "obj/A380/A380.obj" ) /*19*/ ,std::string( models_dir + "obj/transparency/treecube.obj" ) /*20*/ ,std::string( models_dir + "obj/transparency/leaf.obj" ) /*21*/ ,std::string( models_dir + "obj/sibenik/sibenik.obj" ) /*22*/ ,std::string( models_dir + "obj/powerplant/powerplant.obj" ) /*23*/ ,std::string( models_dir + "obj/dragon.obj" ) /*24*/ ,std::string( models_dir + "obj/buddha.obj" ) /*25*/ ,std::string( models_dir + "obj/hairball.obj" ) /*26*/ ,std::string( models_dir + "obj/dragon_girl/dragon_girl.obj" ) /*27*/ ,std::string( models_dir + "obj/teapot/teapot.obj" ) /*28*/ ,std::string( models_dir + "obj/dragon/dragon.obj" ) /*29*/ ,std::string( models_dir + "obj/testing/testing.obj" ) /*30*/ ,std::string( models_dir + "obj/testing/baloondog.obj" ) /*31*/ ,std::string( models_dir + "obj/testing/dragon.obj" ) /*32*/ ,std::string( models_dir + "fbx/cornellbox_original.fbx" ) /*33*/ ,std::string( models_dir + "fbx/cornellbox_spheres.fbx" ) /*34*/ ,std::string( models_dir + "fbx/dragon.fbx" ) /*35*/ ,std::string( models_dir + "fbx/museum.fbx" ) /*36*/ ,std::string( models_dir + "fbx/train.fbx" ) /*37*/ ,std::string( models_dir + "fbx/treasure.fbx" ) /*38*/ ,std::string( models_dir + "fbx/cabin.fbx" ) /*39*/ ,std::string( models_dir + "fbx/carnival.fbx" ) /*40*/ ,std::string( models_dir + "fbx/lighthouse.fbx" ) /*41*/ ,std::string( models_dir + "fbx/frozentest.fbx" ) /*42*/ ,std::string( models_dir + "fbx/instancedtest.fbx" ) /*43*/ ,std::string( models_dir + "fbx/lighttest.fbx" ) /*44*/ ,std::string( models_dir + "fbx/indoor.fbx" ) /*45*/ ,std::string( models_dir + "fbx/outdoor.fbx" ) /*46*/ ,std::string( models_dir + "fbx/combo_lores.fbx" ) /*47*/ ,std::string( models_dir + "fbx/combo_hires.fbx" ) /*48*/ ,std::string( models_dir + "fbx/combo.fbx" ) /*49*/ ,std::string( models_dir + "fbx/test.fbx" ) /*50*/ ,std::string( models_dir + "fbx/temp.fbx" ) }; std::unordered_map<std::string, float> options = { { "-model",(float) 0}, { "-hdr",(float) 0 }, { "-skydome",(float) 0 }, { "-width",(float) 1024 }, { "-height",(float) 1024 }, { "-lens_radius", 0.0f }, { "-focal_length", 5.0f }, { "-samples",(float) 1 }, { "-bounces",(float) 2 }, { "-rr",(float) 1 }, { "-num_gpus",(float) 2 }, { "-bvh_num_bins",(float) 16 }, { "-bvh_max_height",(float) 32 }, { "-bvh_min_leaf_tris",(float) 2 }, { "-bvh_max_leaf_tris",(float) 2 }, { "-bvh_ci", 1.0f }, { "-bvh_ct", 0.125f } }; const std::string help = "\ Example Options:\n \ -model 0 (index of the model file)\n \ -hdr 0 (index of the hdr file)\n \ -skydome 0 (0-hdr, 1-physical )\n \ -width 1024 (width in pixels)\n \ -height 1024 (height in pixels)\n \ -lens_radius 0 (lens radius)\n \ -focal_length 5 (focal distance)\n \ -bounces 3 (max path tracing bounces)\n \ -rr 2 (Russian roulette depth)\n \ -bvh_max_height 32 (max height of tree (make leaf)\n \ -bvh_num_bins 16 (bvh build number of bins)\n \ -bvh_min_leaf_tris 2 (min num tris to create leaf node)\n \ -bvh_max_leaf_tris 2 (max num tris early leaf node creation)\n \ -bvh_ci 1.0 (traversal cost object splitter)\n \ -bvh_ct 0.125 (traversal cost object splitter)\n "; const std::string keyboard_shortcuts = "\ Keyboard shortcuts:\n \ esc\t(exit)\n \ 1 (draw fps)\n \ 2 (enable/disable env light)\n \ 3 (enable/disable env debug view)\n \ 4 (enable/disable env debug view importance sample)\n \ 5 (switch to persp cam)\n \ 6 (switch to ortho cam)\n \ 7 (switch to env cam)\n \ F9 (tonemap: Gamma correct)\n \ F10 (tonemap: Reinhard)\n \ F11 (tonemap: Filmic)\n \ F12 (tonemap: Uncharted)\n \ \nMouse Control:\n \ -Left mouse button orbit/rotate. \n \ -Right mouse button zoom in/out. \n \ -Middle mouse button strafe. \n"; BVHSpec bvh_spec{ static_cast<glm::uint32>( options["-bvh_num_bins"] ) /* num_bins */ ,static_cast<glm::uint32>( options["-bvh_max_height"] ) /* max_height */ , options["-bvh_ci"] /* Ci */ , options["-bvh_ct"] /* Ct object*/ ,static_cast<glm::uint32>( options["-bvh_min_leaf_tris"] ) /* min_leaf_tris */ ,static_cast<glm::uint32>( options["-bvh_max_leaf_tris"] ) /* max_leaf_tris */ }; CameraSpec camera_spec{ glm::vec3( 0.0f, 0.0f, 3.0f ), // eye glm::vec3( 0.0f, 1.0f, 0.0f ), // up glm::vec3( 0.0f, 0.0f, 0.0f ), // lookAt glm::pi<float>() / 4.f, static_cast<glm::uint32>( options["-width"] ), // width in pixels static_cast<glm::uint32>( options["-height"] ), // height in pixels options["-lens_radius"], // lens_radius options["-focal_lenth"], // focal_length static_cast<glm::uint8>( options["-bounces"] ), static_cast<glm::uint8>( options["-rr"] ), // Russian Roulette }; ModelSpec model_spec; Spec noor_spec( bvh_spec, camera_spec, model_spec ); inline void printHelp() { std::cout << keyboard_shortcuts << std::endl; std::cout << help << std::endl; std::cout << "model files: \n"; int count = 0; for ( const std::string& model_file : model_files ) { std::cout << "\t" << count++ << "- " << model_file << std::endl; } count = 0; std::cout << "\nhdr files: \n"; for ( const std::string& hdr_file : hdr_files ) { std::cout << "\t" << count++ << "- " << hdr_file << std::endl; } } inline bool is_numeric( const char *s ) { bool single_dot = false; return std::all_of( s, s + std::strlen( s ), [&single_dot]( char c ) { if ( c == '.' ) { if ( single_dot ) return false; else single_dot = true; } return isdigit( c ) || c == '.'; } ); } inline bool parseOptions( int argc, char * argv[] ) { int num_models = static_cast<int>( model_files.size() ); int num_hdrs = static_cast<int>( hdr_files.size() ); for ( int i = 1; i < argc; i += 2 ) { if ( strcmp( argv[i], "help" ) == 0 || strcmp( argv[i], "-help" ) == 0 ) { printHelp(); return false; } if ( options.find( argv[i] ) != options.end() ) { if ( argv[i + 1] == nullptr || !is_numeric( argv[i + 1] ) ) { std::cerr << "Invalid argument for " << argv[i] << std::endl; return false; } float argument = std::stof( argv[i + 1] ); if ( strcmp( argv[i], "-model" ) == 0 && argument >= num_models ) { std::cerr << argv[i + 1] << " exceeds number of available models. "; std::cerr << "there are only " << num_models << " models." << std::endl; return false; } if ( strcmp( argv[i], "-hdr" ) == 0 && argument >= num_hdrs ) { std::cerr << argv[i + 1] << " exceeds number of available hdrs. "; std::cerr << "there are only " << num_hdrs << " hdrs." << std::endl; return false; } options[argv[i]] = argument; } else { std::cerr << "Flag " << argv[i] << " not recognized!" << std::endl; std::cerr << "Use -help or help for list of valid options." << std::endl; return false; } } noor_spec._model_spec._model_filename = model_files[static_cast<glm::uint32>( options["-model"] )]; noor_spec._model_spec._hdr_filename = hdr_files[static_cast<glm::uint32>( options["-hdr"] )]; noor_spec._model_spec._skydome_type = static_cast<int>( options["-skydome"] ); noor_spec._camera_spec._w = static_cast<glm::uint32>( options["-width"] ); noor_spec._camera_spec._h = static_cast<glm::uint32>( options["-height"] ); noor_spec._camera_spec._bounces = static_cast<glm::uint32>( options["-bounces"] ); noor_spec._camera_spec._rr = static_cast<glm::uint32>( options["-rr"] ); noor_spec._camera_spec._lens_radius = options["-lens_radius"]; noor_spec._camera_spec._focal_length = options["-focal_length"]; noor_spec._bvh_spec._num_bins = static_cast<glm::uint32>( options["-bvh_num_bins"] ); noor_spec._bvh_spec._max_height = static_cast<glm::uint32>( options["-bvh_max_height"] ); noor_spec._bvh_spec._min_leaf_tris = static_cast<glm::uint32>( options["-bvh_min_leaf_tris"] ); noor_spec._bvh_spec._max_leaf_tris = static_cast<glm::uint32>( options["-bvh_max_leaf_tris"] ); noor_spec._bvh_spec._Ci = options["-bvh_ci"]; noor_spec._bvh_spec._Ct = options["-bvh_ct"]; noor_spec._num_gpus = options["-num_gpus"]; return true; } #endif /* OPTIONS_H */
3297f5c7752fcbb21d61cd6e9c1923a3af7350dc
09f0c5a33f3c518e5360fd02586a6bd254c43e72
/C++/Exercise/Operator/src/Operator.cpp
ce6e563d6c0c9f88d8763aad1da6a915d673fa5e
[]
no_license
josephding23/Codes
c74f157f98e6eb5af2cc9a35f44c6c371e161df9
c440c7c45f78a28842e7b8af838707533666e4b4
refs/heads/master
2021-09-22T01:09:02.338998
2018-09-04T08:59:45
2018-09-04T08:59:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,864
cpp
Operator.cpp
#include "Operator.h" Date::Date(int year, int month, int day) { this -> year = year; this -> month = month; this -> day = day; } Date::Date(const Date &date) { year = date.year; month = date.month; day = date.day; } bool ifLeepYear(int year) { if((year % 400 == 0)||(year % 4 == 0 && year % 25 != 0)) return true; else return false; } void Date::printFullYear() { cout << year << '-'; cout << setfill('0') << setw(2) << month << '-'; cout << setfill('0') << setw(2) << day << endl; } void Date::printStandardYear() { int standardYear = year % 100; cout << standardYear << '-'; cout << setfill('0') << setw(2) << month << '-'; cout << setfill('0') << setw(2) << day << endl; } int Date::operator- (const Date &date2) const { int daysofMonths[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int daysofYear = 365; int sumDays = 0; const int toYear = date2.year; const int toMonth = date2.month; const int toDay = date2.day; bool ifYearLater = toYear > year; //Calculate the whole years first if (ifYearLater) { //Original year later for (int i = year + 1; i < toYear; i++){ if(ifLeepYear(i)) daysofYear++; sumDays += daysofYear; daysofYear = 365; } for(int i = month + 1; i <= 12; i++) sumDays += daysofMonths[i]; sumDays += (daysofMonths[month] - day - 1); //1969.8.11 2010.4.15 for(int i = 1; i < toMonth - 1; i++) sumDays += daysofMonths[i]; sumDays += toDay - 1; if(month <= 2 && ifLeepYear(year)) sumDays++; if(toMonth > 2 && ifLeepYear(toYear)) sumDays++; } else { //Original year former for (int i = toYear + 1; i < year; i++){ if(ifLeepYear(i)) daysofYear++; sumDays -= daysofYear; daysofYear = 365; } for(int i = 1; i < month; i++) sumDays -= daysofMonths[i]; sumDays -= day; //1969.8.11 1949.10.1 for(int i = toMonth; i <= 12; i++) sumDays -= daysofMonths[i]; sumDays += toDay - 1; if(month > 2 && ifLeepYear(year)) sumDays++; if(toMonth < 2 && ifLeepYear(toYear)) sumDays++; } //Calculate the margin if (month >= toMonth) { //Original month bigger for (int i = month + 1; i < toMonth; i++) sumDays += daysofMonths[i]; sumDays += daysofMonths[month] - day - 1; sumDays += toDay - 1; if(ifLeepYear(year) && month <= 2) sumDays++; if(ifLeepYear(toYear) && toMonth > 2) sumDays++; } else { //Original month smaller for (int i = toMonth - 1; i > month; i--) sumDays -= daysofMonths[i]; sumDays += daysofMonths[toMonth]; // 1900.4.7 1923.1.7 if(ifLeepYear(year) && month > 2) sumDays--; if(ifLeepYear(toYear) && toMonth <= 2) sumDays--; } return sumDays; } bool Date::operator> (const Date &date2) { if(year != date2.year) return year > date2.year; if(month != date2.month) return month > date2.month; if(day != date2.day) return day > date2.day; } bool Date::operator< (const Date &date2) { if(year != date2.year) return year < date2.year; if(month != date2.month) return month < date2.month; if(day != date2.day) return day < date2.day; } Employee::Employee(const string firstName, const string lastName, Date birthDate, Date hireDate) { this -> firstName = firstName; this -> lastName = lastName; this -> birthDate = birthDate; this -> hireDate = hireDate; } void Employee::print() { cout << "Employee Information:" << endl; cout << "First Name: " << firstName << endl; cout << "Last Name: " << lastName << endl; cout << "Birth Date: "; birthDate.printFullYear(); cout << endl << "Hire Date: "; hireDate.printStandardYear(); cout << endl; } void Employee::setInformation(const string firstName, const string lastName, Date birthDate, Date hireDate) { this -> firstName = firstName; this -> lastName = lastName; this -> birthDate = birthDate; this -> hireDate = hireDate; } Employee::Employee(const Employee &employee) { firstName = employee.firstName; lastName = employee.lastName; birthDate = employee.birthDate; hireDate = employee.hireDate; } Employee& Employee::getMostFaith(Employee employees[], int n) { int place = 0; for(int i = 0; i < n; i++) if(employees[i].getHireDate() < employees[place].getHireDate()) place = i; return employees[place]; }
3b4e96b24f79de5712bd2d289070eee30c9d48a4
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/compiler/xla/mlir/backends/gpu2/conversion/de_bufferization.h
0d69a117a77ebc4b9028ba84c44cf400cfd7ec48
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
4,898
h
de_bufferization.h
/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. 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 TENSORFLOW_COMPILER_XLA_MLIR_BACKENDS_GPU2_CONVERSION_DE_BUFFERIZATION_H_ #define TENSORFLOW_COMPILER_XLA_MLIR_BACKENDS_GPU2_CONVERSION_DE_BUFFERIZATION_H_ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/Value.h" // from @llvm-project namespace xla { namespace gpu { // As a part of the compilation pipeline to prepare XLA executable to run on top // of IREE VM we convert it from LMHLO dialects to IREEInput dialect. The key // difference is that at LMHLO level program operates on buffers (memrefs), // and at IREEInput level it uses value semantics and tensors. // // We rely on in-place semantics of IREEInput operations (tied operands) to // re-write operations writing to buffers to operations updating tensors. // // Example: // // func @main(%arg0: memref<f32>, %arg1: memref<f32>) { // lmhlo.fusion { // %0 = bufferization.to_tensor %arg0 : memref<f32> // %0 = bufferization.to_tensor %arg1 : memref<f32> // %2 = mhlo.add %0, %1: tensor<f32> // memref.tensor_store %2, %arg1 : memref<f32> // } // "some.consumer"(%arg1) : (memref<f32>) -> () // } // // In this example `%arg0` is a read only buffer, and `%arg1` is a read-write // buffer. // // func @main(%arg0: tensor<f32>, %arg1: tensor<f32>) { // %0 = iree_input.dispatch @add(%arg0, %arg1) // : (tensor<f32>, tensor<f32>) -> %arg1 // "some.consumer"(%0) : (tensor<f32>) -> () // } // // We use `DeBufferization` to track the mapping from a memref to the last // tensor produced by an operation that wrote into a memref. In the example // above instead of passing `%arg1` to the consumer, we pass the last tensor // that shares the storage with `%arg1`. After lowering this representation to // IREEs HAL dialect, it's guaranteed that XLA program will read/write from/to // exactly the same buffer slices as its original version. // // In XLA all input arguments do not alias, so we don't need any buffer aliasing // analysis, and we can safely rely on memref.view operation offsets and sizes. // // Conversion implementation is a bit more complicated because we have to handle // memref.view and memref.reinterpret_cast operations, but all conversions // conceptually are doing the same transformation as in example above. struct DeBufferization { // Mapping block block arguments to memref views constructed from them. We'll // need it at the very end to tie all inplace updates to the optimization // barrier to prevent dead code elimination. llvm::DenseMap<mlir::BlockArgument, llvm::SmallVector<mlir::TypedValue<mlir::MemRefType>>> imported; // Mapping from the memref view to the last tensor that is tied to the same // underlying storage. We use this mapping to thread inplace tensor updates // through all operations in the compiled function. llvm::DenseMap<mlir::Block *, llvm::DenseMap<mlir::TypedValue<mlir::MemRefType>, mlir::TypedValue<mlir::TensorType>>> remapped; }; // We only pass around tensors constructed from a row major memrefs because // currently IREE buffer view can't represent a strided layout. As a short term // solution the plan is to pass tensor layout as a side data structure, but // longer term we'll need to add tensor/buffer layouts to IREE HAL buffers. mlir::TypedValue<mlir::MemRefType> stripReinterpretCast( mlir::TypedValue<mlir::MemRefType> value); mlir::TypedValue<mlir::MemRefType> stripReinterpretCast( mlir::TypedValue<mlir::BaseMemRefType> value); //===----------------------------------------------------------------------===// // Helper functions for de-bufferizing operations with nested regions //===----------------------------------------------------------------------===// struct UsedBuffers { llvm::SetVector<mlir::TypedValue<mlir::MemRefType>> read; llvm::SetVector<mlir::TypedValue<mlir::MemRefType>> write; }; UsedBuffers getUsedBuffers(llvm::ArrayRef<mlir::Block *> blocks); } // namespace gpu } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_MLIR_BACKENDS_GPU2_CONVERSION_DE_BUFFERIZATION_H_
15233be640b6a53dfdd2081e9d1cf97c9d7d92de
343870aeb0229ce42f8bafcd3e2dc696e22c7635
/app/src/main/cpp/native-lib.cpp
02d9b4116d8a29ffe6f4bc581888b1d1fbadb697
[ "MIT" ]
permissive
tinyvpn/tvpn_android
4f131ce8a696c5c62c9726a363a1d7a05bb686e9
8c33e7bd165d369983e18dcc9166501b9835fb40
refs/heads/main
2023-06-25T09:40:24.305152
2021-07-29T09:39:25
2021-07-29T09:39:25
390,667,471
0
0
null
null
null
null
UTF-8
C++
false
false
18,888
cpp
native-lib.cpp
#include <jni.h> #include <string> #include <android/log.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <thread> #include "sysutl.h" #include "sockutl.h" #include "fileutl.h" #include "timeutl.h" #include "stringutl.h" #include "obfuscation_utl.h" #include "vpn_packet.h" #include "sockhttp.h" #include "ssl_client2.h" #include "http_client.h" static int g_protocol; static int client_sock; static int g_fd_tun_dev; static int g_in_recv_tun; static int g_in_recv_socket; static int g_isRun; static uint32_t g_private_ip; static int in_traffic, out_traffic; extern "C" JNIEXPORT jstring JNICALL Java_com_tinyvpn_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MainActivity_initFromJNI( JNIEnv *env, jobject /* this */, jstring log_path) { string_utl::set_random_http_domains(); sock_http::init_http_head(); const char *inPath = (env)->GetStringUTFChars(log_path, NULL); if (NULL == inPath) return 1; (env)->ReleaseStringUTFChars(log_path, inPath); std::string strPath(inPath); strPath += "/alog.txt"; OpenFile(strPath.c_str()); SetLogLevel(0); return 0; } /* extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MyVPNService_pushHttpHeaderFromJni( JNIEnv *env, jobject , jobject buf, jint body_length, jint obfu) { jbyte *buff = (jbyte *) env->GetDirectBufferAddress(buf); VpnPacket packet((char*)buff, 1020, 4096); packet.set_back_offset(1020 + body_length); if (obfu == 1) obfuscation_utl::encode((unsigned char*)packet.data(), 4, g_iv); if (obfu == 1) obfuscation_utl::encode((unsigned char*)packet.data()+4, body_length-4, g_iv); sock_http::push_front_xdpi_head_1(packet); return 1020-packet.front_offset(); } extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MyVPNService_popFrontXdpiHeadFromJni( JNIEnv *env, jobject , jobject buf, jint position, jint length, jint obfu) { std::string http_header; jbyte *buff = (jbyte *) env->GetDirectBufferAddress(buf); http_header.assign((char*)buff + position, length); int http_head_length=0; int http_body_length=0; if (sock_http::pop_front_xdpi_head(http_header, http_head_length,http_body_length) != 0){ // parse error return 0; } if (http_body_length==0||http_head_length==0) { __android_log_write(ANDROID_LOG_DEBUG, "JNI", "parse http header error."); return 0; } if (obfu == 1) obfuscation_utl::decode((unsigned char*)buff + position + http_head_length, 4, g_iv); if (obfu == 1) { obfuscation_utl::decode((unsigned char*)buff+position+http_head_length+4, http_body_length-4, g_iv); } return http_body_length<<16 | http_head_length; }*/ extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MyVPNService_connectServerFromJni( JNIEnv *env, jobject thisObj /* this */, jint protocol, jstring ip, jint port, jint premium, jstring androidId, jstring userName, jstring userPassword) { INFO("start connect server"); g_protocol = protocol; std::string global_private_ip; char* ip_packet_data; const char *inIp = (env)->GetStringUTFChars(ip, NULL); if (NULL == inIp) return 1; std::string strIp(inIp); (env)->ReleaseStringUTFChars(ip, inIp); const char *inId = (env)->GetStringUTFChars(androidId, NULL); if (NULL == inId) return 1; std::string strId(inId); (env)->ReleaseStringUTFChars(androidId, inId); std::string strName; if(premium >= 2) { const char *inName = (env)->GetStringUTFChars(userName, NULL); if (NULL == inName) return 1; strName = inName; (env)->ReleaseStringUTFChars(userName, inName); } std::string strPassword; if(premium>=2) { const char *inPassword = (env)->GetStringUTFChars(userPassword, NULL); if (NULL == inPassword) return 1; strPassword = inPassword; (env)->ReleaseStringUTFChars(userPassword, inPassword); } __android_log_print(ANDROID_LOG_DEBUG, "JNI", "ip:%s,id:%s,name:%s,password:%s", strIp.c_str(), strId.c_str(), strName.c_str(), strPassword.c_str()); int sock = 0; if (g_protocol == kSslType) { if (init_ssl_client() != 0) { __android_log_write(ANDROID_LOG_ERROR, "JNI", "init ssl fail."); return 1; } INFO("connect ssl"); connect_ssl(strIp, port, sock); if (sock == 0) { __android_log_write(ANDROID_LOG_ERROR, "JNI", "sock is zero."); return 1; } } else if (g_protocol == kHttpType) { if (connect_tcp(strIp, port, sock) != 0) return 1; } else { __android_log_write(ANDROID_LOG_ERROR, "JNI", "protocol errror."); return 1; } std::string strPrivateIp; INFO("get private_ip"); if (g_protocol == kSslType) get_private_ip(premium,strId,strName,strPassword, strPrivateIp); else if (g_protocol == kHttpType) { if (get_private_ip_http(premium, strId, strName, strPassword, strPrivateIp) != 0) { __android_log_write(ANDROID_LOG_ERROR, "JNI", "get private_ip error."); return 1; } } ip_packet_data = (char*)strPrivateIp.c_str(); g_private_ip = *(uint32_t*)ip_packet_data; global_private_ip = socket_utl::socketaddr_to_string(g_private_ip); __android_log_print(ANDROID_LOG_INFO, "JNI", "global_private_ip:%s,%s", string_utl::HexEncode(strPrivateIp).c_str(), global_private_ip.c_str()); //INFO("global_private_ip:%s,%s", string_utl::HexEncode(strPrivateIp).c_str(), global_private_ip.c_str()); // set client_fd jclass thisClass = (env)->GetObjectClass( thisObj); //INFO("get class ok."); jfieldID fidNumber = (env)->GetFieldID( thisClass, "client_fd", "I"); //INFO("get field ok."); if (NULL == fidNumber) return 1; //INFO("field not null"); // Change the variable (env)->SetIntField(thisObj, fidNumber, (jint)sock); __android_log_print(ANDROID_LOG_INFO, "JNI", "set client_fd:%d", sock); //INFO("set client_fd:%d", sock); client_sock = sock; fidNumber = (env)->GetFieldID( thisClass, "privateIp", "I"); if (NULL == fidNumber) return 1; // Change the variable (env)->SetIntField(thisObj, fidNumber, ntohl(g_private_ip)); __android_log_print(ANDROID_LOG_INFO, "JNI", "set private_ip:%x", ntohl(g_private_ip)); //INFO("get private ip ok."); return 0; } const int BUF_SIZE = 4096*4; static char g_tcp_buf[BUF_SIZE*2]; static int g_tcp_len; int write_tun(char* ip_packet_data, int ip_packet_len){ int len; if (g_tcp_len != 0) { if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) { __android_log_print(ANDROID_LOG_ERROR, "JNI", "relay size over %lu", sizeof(g_tcp_buf)); g_tcp_len = 0; return 1; } memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); ip_packet_data = g_tcp_buf; ip_packet_len += g_tcp_len; g_tcp_len = 0; __android_log_print(ANDROID_LOG_DEBUG, "JNI", "relayed packet:%d", ip_packet_len); } while(1) { if (ip_packet_len == 0) break; // todo: recv from socket, send to utun1 if (ip_packet_len < sizeof(struct ip) ) { __android_log_print(ANDROID_LOG_ERROR, "JNI","less than ip header:%d.", ip_packet_len); memcpy(g_tcp_buf, ip_packet_data, ip_packet_len); g_tcp_len = ip_packet_len; break; } struct ip *iph = (struct ip *)ip_packet_data; len = ntohs(iph->ip_len); if (ip_packet_len < len) { if (len > BUF_SIZE) { __android_log_print(ANDROID_LOG_ERROR, "JNI","something error1.%x,%x,data:%s",len, ip_packet_len, string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str()); g_tcp_len = 0; } else { __android_log_print(ANDROID_LOG_DEBUG, "JNI","relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len); if (g_tcp_len == 0) { memcpy(g_tcp_buf +g_tcp_len, ip_packet_data, ip_packet_len); g_tcp_len += ip_packet_len; } } break; } if (len > BUF_SIZE) { __android_log_print(ANDROID_LOG_ERROR, "JNI","something error.%x,%x",len, ip_packet_len); g_tcp_len = 0; break; } else if (len == 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI","len is zero.%x,%x",len, ip_packet_len); //string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str()); g_tcp_len = 0; break; } char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN); __android_log_print(ANDROID_LOG_DEBUG, "JNI","send to utun, from(%s) to (%s) with size:%d",ip_src,ip_dst,len); // if (sys_utl::tun_dev_write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) { if (::write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI","write tun error:%d", g_fd_tun_dev); return 1; } ip_packet_len -= len; ip_packet_data += len; } return 0; } int write_tun_http(char* ip_packet_data, int ip_packet_len) { static uint32_t g_iv = 0x87654321; int len; if (g_tcp_len != 0) { if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) { INFO("relay size over %d", sizeof(g_tcp_buf)); g_tcp_len = 0; return 1; } memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); ip_packet_data = g_tcp_buf; ip_packet_len += g_tcp_len; g_tcp_len = 0; INFO("relayed packet:%d", ip_packet_len); } std::string http_packet; int http_head_length, http_body_length; while (1) { if (ip_packet_len == 0) break; http_packet.assign(ip_packet_data, ip_packet_len); if (sock_http::pop_front_xdpi_head(http_packet, http_head_length, http_body_length) != 0) { // decode http header fail __android_log_print(ANDROID_LOG_DEBUG, "JNI","relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len); if (g_tcp_len == 0) { memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); g_tcp_len += ip_packet_len; } break; } ip_packet_len -= http_head_length; ip_packet_data += http_head_length; obfuscation_utl::decode((unsigned char *) ip_packet_data, 4, g_iv); obfuscation_utl::decode((unsigned char *) ip_packet_data + 4, http_body_length - 4, g_iv); struct ip *iph = (struct ip *) ip_packet_data; len = ntohs(iph->ip_len); char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET, &iph->ip_src.s_addr, ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET, &iph->ip_dst.s_addr, ip_dst, INET_ADDRSTRLEN); __android_log_print(ANDROID_LOG_DEBUG, "JNI","send to tun,http, from(%s) to (%s) with size:%d, header:%d,body:%d", ip_src, ip_dst, len, http_head_length, http_body_length); sys_utl::tun_dev_write(g_fd_tun_dev, (void *) ip_packet_data, len); ip_packet_len -= http_body_length; ip_packet_data += http_body_length; } return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MyVPNService_startSslThreadFromJni( JNIEnv *env, jobject thisObj /* this */, jint tun_fd) { g_fd_tun_dev = tun_fd; INFO("start ssl thread"); __android_log_print(ANDROID_LOG_DEBUG, "JNI", "start ssl thread:%d,g_fd_tun_dev:%d,client_sock:%d", tun_fd, g_fd_tun_dev, client_sock); g_isRun= 1; g_in_recv_tun = 1; g_tcp_len = 0; in_traffic = 0; out_traffic = 0; //std::thread tun_thread(client_recv_tun, client_sock); g_in_recv_socket = 1; int ip_packet_len; char ip_packet_data[BUF_SIZE]; int ret; time_t lastTime = time_utl::localtime(); time_t currentTime; time_t recvTime = time_utl::localtime(); time_t sendTime = time_utl::localtime(); fd_set fdsr; int maxfd; while(g_isRun == 1){ FD_ZERO(&fdsr); FD_SET(client_sock, &fdsr); FD_SET(g_fd_tun_dev, &fdsr); maxfd = std::max(client_sock, g_fd_tun_dev); struct timeval tv_select; tv_select.tv_sec = 2; tv_select.tv_usec = 0; int nReady = select(maxfd + 1, &fdsr, NULL, NULL, &tv_select); if (nReady < 0) { ERROR("select error:%d", nReady); __android_log_print(ANDROID_LOG_ERROR, "JNI", "select error:%d", nReady); break; } else if (nReady == 0) { //ERROR("select timeout"); __android_log_print(ANDROID_LOG_DEBUG, "JNI", "select timeout"); continue; } if (FD_ISSET(g_fd_tun_dev, &fdsr)) { // recv from tun static VpnPacket vpn_packet(4096); int readed_from_tun; vpn_packet.reset(); readed_from_tun = sys_utl::tun_dev_read(g_fd_tun_dev, vpn_packet.data(), vpn_packet.remain_size()); vpn_packet.set_back_offset(vpn_packet.front_offset()+readed_from_tun); if(readed_from_tun < sizeof(struct ip)) { __android_log_print(ANDROID_LOG_ERROR, "JNI","tun_dev_read error, size:%d", readed_from_tun); ERROR("tun_dev_read error"); break; } if(readed_from_tun > 0) { struct ip *iph = (struct ip *)vpn_packet.data(); char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN); if(g_private_ip != iph->ip_src.s_addr) { __android_log_print(ANDROID_LOG_ERROR, "JNI","src_ip mismatch:%x,%x",g_private_ip, iph->ip_src.s_addr); continue; } __android_log_print(ANDROID_LOG_DEBUG, "JNI","recv from tun, from(%s) to (%s) with size:%d",ip_src,ip_dst,readed_from_tun); //file_utl::write(sockid, vpn_packet.data(), readed_from_tun); out_traffic += readed_from_tun; if (g_protocol == kSslType) { if (ssl_write(vpn_packet.data(), readed_from_tun) != 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI", "ssl_write error!"); ERROR("ssl_write error"); break; } } else if (g_protocol == kHttpType){ http_write(vpn_packet); } sendTime = time_utl::localtime(); } // if (--nReady == 0) // read over // continue; } if (FD_ISSET(client_sock, &fdsr)) { // recv from socket ip_packet_len = 0; if (g_protocol == kSslType) { ret = ssl_read(ip_packet_data, ip_packet_len); if (ret != 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI", "ssl_read error!"); ERROR("ssl_read error"); break; } } else if (g_protocol == kHttpType) { ip_packet_len = file_utl::read(client_sock, ip_packet_data, BUF_SIZE); } else { ERROR("protocol error."); break; } if (ip_packet_len == 0) continue; in_traffic += ip_packet_len; __android_log_print(ANDROID_LOG_DEBUG, "JNI", "recv from socket, size:%d", ip_packet_len); if (g_protocol == kSslType) { if (write_tun((char *) ip_packet_data, ip_packet_len) != 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI", "write_tun error"); ERROR("write_tun error"); break; } } else if (g_protocol == kHttpType){ if (write_tun_http((char *) ip_packet_data, ip_packet_len) != 0) { __android_log_print(ANDROID_LOG_ERROR, "JNI", "write_tun error"); ERROR("write_tun error"); break; } } recvTime = time_utl::localtime(); } currentTime = time_utl::localtime(); if (currentTime - recvTime > 60 || currentTime - sendTime > 60) { __android_log_print(ANDROID_LOG_ERROR, "JNI","send or recv timeout"); break; } if (currentTime - lastTime >= 1) { jclass thisClass = (env)->GetObjectClass(thisObj); jfieldID fidNumber = (env)->GetFieldID(thisClass, "current_traffic", "I"); if (NULL == fidNumber) { ERROR("current_traffic error"); return 1; } // Change the variable (env)->SetIntField(thisObj, fidNumber, in_traffic + out_traffic); __android_log_print(ANDROID_LOG_INFO, "JNI", "current traffic:%d", in_traffic+out_traffic); jmethodID mtdCallBack = (env)->GetMethodID(thisClass, "trafficCallback", "()I"); if (NULL == mtdCallBack) { ERROR("trafficCallback error"); return 1; } ret = (env)->CallIntMethod(thisObj, mtdCallBack); lastTime = time_utl::localtime(); } } __android_log_print(ANDROID_LOG_INFO, "JNI","main thread stop"); if(g_protocol == kSslType) ssl_close(); else if (g_protocol == kHttpType) close(client_sock); g_isRun = 0; // callback to app jclass thisClass = (env)->GetObjectClass( thisObj); jmethodID midCallBackAverage = (env)->GetMethodID(thisClass, "stopCallback", "()I"); if (NULL == midCallBackAverage) return 1; ret = (env)->CallIntMethod(thisObj, midCallBackAverage); __android_log_print(ANDROID_LOG_DEBUG, "JNI", "stop callback:%d", ret); return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_tinyvpn_MyVPNService_stopRunFromJni( JNIEnv *env, jobject /* this */) { g_isRun = 0; __android_log_print(ANDROID_LOG_INFO, "JNI", "set stop ok"); return 0; }
10dc2e43fd03f30b720d7f665b37b56c0a0d8967
2430873260c0d2e99e23c65ec556e86bd0289980
/src/projectile.cpp
577e89dca249f8505999d95b2c8d963aa3144441
[]
no_license
resisposse/ddos
378b3ddf824bad77629a4c304ce6a3880bda6494
9259fdb668bf3b7b4d6527dc583cb43109ddf6c4
refs/heads/master
2023-04-18T08:40:24.369441
2017-11-16T18:24:16
2019-04-26T12:14:03
110,987,791
1
0
null
null
null
null
UTF-8
C++
false
false
4,314
cpp
projectile.cpp
/* * Dark Domains Of Space * 2015 © Project Team (see: LICENSE) */ #include <SFML/Graphics.hpp> #include <iostream> #include <cmath> #include "weapon.hpp" #include "projectile.hpp" #include "globals.hpp" ProjectileSprite::ProjectileSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) { float b; int magnitude, magnitudeTmp; float angle, spreadDist; sf::Vector2f difference, differenceTmp; sf::Vector2u spriteSize = projectileTexture.getSize(); position = startPosition; hit = false; speed = 300; damage = 10; aoe = 0; /* Area of effect in pixels */ piercing = false; sprite.setTexture(projectileTexture); sprite.setScale(0.5, 0.5); sprite.setOrigin(sf::Vector2f(spriteSize.x / 2, spriteSize.y / 2)); sprite.setPosition(position); /* Calculate spread and the direction the bullet will travel */ differenceTmp.x = position.x - mousePosition.x; differenceTmp.y = position.y - mousePosition.y; magnitudeTmp = sqrt(pow(differenceTmp.x, 2) + pow(differenceTmp.y, 2)); spreadDist = tan(((rand() % inaccuracy - (inaccuracy / 2))) * PI / 180.0) * magnitudeTmp; b = 90 - (90.0 - (atan(differenceTmp.y / differenceTmp.x) * 180.0/PI)); if (b <= 0) { difference.x = position.x - (mousePosition.x + (sin(b * PI / 180) * spreadDist)); difference.y = position.y - (mousePosition.y - (cos(b * PI / 180) * spreadDist)); } else if (b > 0) { difference.x = position.x - (mousePosition.x - (sin(b * PI / 180) * spreadDist)); difference.y = position.y - (mousePosition.y + (cos(b * PI / 180) * spreadDist)); } magnitude = sqrt(pow(difference.x, 2) + pow(difference.y, 2)); normalized.x = (difference.x / magnitude); normalized.y = (difference.y / magnitude); /* Face sprite in the direction it's travelling */ angle = atan2(difference.y, difference.x) * 180 / PI; sprite.setRotation(angle); } void ProjectileSprite::update(float second) { /* Calculate sprites velocity and move it */ xVelocity = -normalized.x * speed * second; yVelocity = -normalized.y * speed * second; sprite.move(sf::Vector2f(xVelocity, yVelocity)); position = sprite.getPosition(); } int ProjectileSprite::getDamage() { return damage; } int ProjectileSprite::getAoE() { return aoe; } /* Undecided if we need this function bool ProjectileSprite::outsideWindow() { // check if sprite is outside of the window return position.x < 0 || position.x > WINDOW_WIDTH || position.y < 0 || position.y > WINDOW_HEIGHT; } */ BulletSprite::BulletSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 500; damage = 18; aoe = 0; piercing = false; } LaserSprite::LaserSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 1000; damage = 25; aoe = 0; piercing = true; } PelletSprite::PelletSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 300; damage = 12; aoe = 0; piercing = false; } HeavyBulletSprite::HeavyBulletSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 1500; damage = 50; aoe = 0; piercing = false; } PlasmaBallSprite::PlasmaBallSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 500; damage = 50; aoe = 64; piercing = false; } BeamSprite::BeamSprite(sf::Texture& projectileTexture, sf::Vector2f startPosition, sf::Vector2i mousePosition, int inaccuracy) : ProjectileSprite(projectileTexture, startPosition, mousePosition, inaccuracy) { hit = false; speed = 800; damage = 10; aoe = 0; piercing = true; }
1e9b3048f02f1aa132a41cd3915c53b3d5dd5ab3
44b16bd380b2507a0830013752479d28b9b1e83f
/WorldAPI/Point.cpp
ecd4100dca65884f2d24d02dacd50ab944988cda
[]
no_license
lenainav/World
5285a0e6cfa1963c814f3b82e80e66ea4b90859a
6afb1fade4c6524739b2e1fc0c4fc3397d82f905
refs/heads/master
2021-01-13T02:26:42.270576
2015-02-12T14:54:06
2015-02-12T14:54:06
29,678,836
0
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
Point.cpp
#include "Point.h" Point::Point() { //ctor x = y = 0; } Point::Point(int vx, int vy) //Point point point... { x = vx; y = vy; } Point::~Point() { //dtor } bool Point::equal(Point &b) { return b.x == x && b.y == y; } bool Point::operator==( Point &pb) { return equal(pb); } Point Point::operator+(Point &pb) { return Point(x +pb.x, y + pb.y); } Point Point::operator-(Point &pb) { return Point(x - pb.x, y - pb.y); }
422331f6397265b419b7224083d893d462d18d6c
cf777505c5e6713c7e0dd23146c24aa557a93e6e
/src/Filesystem/FilesystemUtils.cpp
2a9e5c42ac225f91cb9b58aa23ed7201025a4e09
[]
no_license
profi248/backwither
b5c8a10de28bb15845fd48e76c53175cb3f0116b
2a74448de05d545cdf0ff55a4e1d3f00cf98fadc
refs/heads/master
2023-02-26T21:10:53.273631
2021-01-21T18:58:51
2021-01-31T23:30:33
266,898,543
0
0
null
null
null
null
UTF-8
C++
false
false
3,316
cpp
FilesystemUtils.cpp
#include <algorithm> #include <fstream> #include <filesystem> #include <memory> #include <iostream> #include "FilesystemUtils.h" #include "File.h" using namespace std; namespace fs = filesystem; Directory FilesystemUtils::BrowseFolderRecursive (string path_str) { auto path = fs::path(path_str); auto de = fs::directory_entry(path); Directory root; fs::directory_options directoryOptions = {}; if (ENABLE_FOLDER_SYMLINKS) directoryOptions |= fs::directory_options::follow_directory_symlink; for (auto & item : fs::recursive_directory_iterator(path, directoryOptions)) { if (item.is_regular_file()) { fs::path filePath = item.path(); root.AddFilesystemEntity( make_shared<File>(File(filePath.lexically_proximate(path_str), static_cast<long long>(TimeUtils::toTimeT(item.last_write_time())), item.file_size())) ); } } return root; } void FilesystemUtils::VerifySourceDirectory (string source) { if (!fs::exists(source)) throw runtime_error("Directory \"" + source + "\" doesn't exist."); if (!fs::is_directory(source)) throw runtime_error("Path \"" + source + "\" is not a directory."); if (IsDirectoryEmpty(source)) throw runtime_error("Directory \"" + source + "\" is empty."); } void FilesystemUtils::VerifyOrCreateDestinationDirectory (string destination) { if (fs::exists(destination)) { if (!fs::is_directory(destination)) throw runtime_error("Path \"" + destination + "\" is not a directory."); } else { if (!fs::create_directories(destination)) throw runtime_error("Directory can't be created in \"" + destination + "\"."); } auto tmpFileStream = ofstream(NormalizeDirectoryPath(destination) + ".tmp"); if (!tmpFileStream.is_open() || !(tmpFileStream << "a")) throw runtime_error("Directory \"" + destination + "\" not writable."); if (!fs::remove(NormalizeDirectoryPath(destination) + ".tmp")) throw runtime_error("Directory \"" + destination + "\" not writable."); } string FilesystemUtils::NormalizeDirectoryPath (string path) { if (path[path.length()] != '/') return path += '/'; return path; } string FilesystemUtils::GetDirectoryOfFilePath (string path) { int lastSeparator = -1; for (size_t i = 0; i < path.length(); i++) { if (path[i] == '/') lastSeparator = i; } if (lastSeparator < 0) return path; return path.substr(0, lastSeparator + 1); } bool FilesystemUtils::IsDirectoryEmpty (string path) { if (!fs::exists(path)) throw runtime_error("Directory \"" + path + "\" does not exist."); return fs::begin(fs::directory_iterator(path)) == fs::end(fs::directory_iterator(path)); } string FilesystemUtils::AbsolutePath (std::string path, bool create) { if (fs::exists(path)) return fs::canonical(path); else { if (create) { fs::create_directories(path); return fs::canonical(path); } else throw runtime_error("Backup path \"" + path + "\" does not exist."); } } bool FilesystemUtils::ArePathsEqual (std::string a, std::string b) { return fs::equivalent(a, b); }
7a28c953683c3185c4d07b8113d0467ff7c3455c
44289ecb892b6f3df043bab40142cf8530ac2ba4
/Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/content/UndoOwner.h
ff91ff7d90cc0c5afe269944281d2a8f535f0a13
[ "Apache-2.0" ]
permissive
warrenween/Elastos
a6ef68d8fb699fd67234f376b171c1b57235ed02
5618eede26d464bdf739f9244344e3e87118d7fe
refs/heads/master
2021-01-01T04:07:12.833674
2017-06-17T15:34:33
2017-06-17T15:34:33
97,120,576
2
1
null
2017-07-13T12:33:20
2017-07-13T12:33:20
null
UTF-8
C++
false
false
1,668
h
UndoOwner.h
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 __ELASTOS_DROID_CONTENT_UNDOOWNER_H__ #define __ELASTOS_DROID_CONTENT_UNDOOWNER_H__ #include "Elastos.Droid.Content.h" #include <elastos/core/Object.h> namespace Elastos { namespace Droid { namespace Content { /** * Representation of an owner of {@link UndoOperation} objects in an {@link UndoManager}. * * @hide */ class UndoOwner : public Object , public IUndoOwner { public: CAR_INTERFACE_DECL() UndoOwner(); virtual ~UndoOwner(); CARAPI constructor( /* [in] */ const String& tag); CARAPI GetTag( /* [out] */ String* tag); CARAPI GetData( /* [out] */ IInterface** data); private: String mTag; AutoPtr<IUndoManager> mManager; AutoPtr<IInterface> mData; Int32 mOpCount; // For saving/restoring state. Int32 mStateSeq; Int32 mSavedIdx; }; } } } #endif // __ELASTOS_DROID_CONTENT_UNDOOWNER_H__
41c4dc0497de7a677fab45797fe318865b219653
e3bf32784b0c8b847db671cd5658522a54da4d71
/FEA/hw_bonus/src/driver.hpp
dd7ef2e563976e8e6ffb06f70468895e9977869b
[]
no_license
JustinClough/Learning_Codes
9bb778ddf4fbb8e887d670948d5c0950306b2a9f
a661ed7a5e3cd6a5330800866f332654a371242f
refs/heads/master
2021-01-10T22:34:41.146967
2019-01-31T21:34:50
2019-01-31T21:34:50
69,578,560
0
0
null
2016-09-30T13:17:33
2016-09-29T15:00:35
C++
UTF-8
C++
false
false
312
hpp
driver.hpp
#ifndef DRIVER_HPP #define DRIVER_HPP #include "printer.hpp" // Checks the argument inputs void check_inputs( int argc, char** argv, int* pmeth); // Drives the problem void drive_problem( int method); void drive( int Np1, int method, Printer* printer); #endif
d76cd49cee3cdb466c26e674ae4618833f2cc006
6d6a3210144fa0b92ad5d4b6ad2ec0c49dcdc7c7
/src/KalmanFilter.h
fb62a4a37bae1af405c967bec13f01a8e6f72cba
[]
no_license
takyonxxx/Variometer-Primary-Flight-Display
85518904fdb08f97d093c20618d37ba1cebb562d
70ccf6eb1c4bc72b8dc0c66e9830fc5a03ff008d
refs/heads/master
2022-09-21T04:20:23.442022
2022-09-06T10:03:56
2022-09-06T10:03:56
142,159,243
11
6
null
null
null
null
UTF-8
C++
false
false
2,311
h
KalmanFilter.h
#ifndef KALMANFILTER_H #define KALMANFILTER_H template<typename T> static inline constexpr T Square(T a) { return a * a; } class KalmanFilter { // The state we are tracking, namely: double x_abs_; // The absolute quantity x. double x_vel_; // The rate of change of x, in x units per second squared. // Covariance matrix for the state. double p_abs_abs_; double p_abs_vel_; double p_vel_vel_; // The variance of the acceleration noise input to the system model, in units // per second squared. double var_x_accel_; public: // Constructors: the first allows you to supply the variance of the // acceleration noise input to the system model in x units per second squared; // the second constructor assumes a variance of 1.0. KalmanFilter(double var_x_accel); KalmanFilter(); // The following three methods reset the filter. All of them assign a huge // variance to the tracked absolute quantity and a var_x_accel_ variance to // its derivative, so the very next measurement will essentially be copied // directly into the filter. Still, we provide methods that allow you to // specify initial settings for the filter's tracked state. // // NOTE: "x_abs_value" is meant to connote the value of the absolute quantity // x, not the absolute value of x. void Reset(); void Reset(double x_abs_value); void Reset(double x_abs_value, double x_vel_value); /** * Sets the variance of the acceleration noise input to the system model in * x units per second squared. */ void SetAccelerationVariance(double var_x_accel) { var_x_accel_ = var_x_accel; } /** * Updates state given a direct sensor measurement of the absolute * quantity x, the variance of that measurement, and the interval * since the last measurement in seconds. This interval must be * greater than 0; for the first measurement after a Reset(), it's * safe to use 1.0. */ void Update(double z_abs, double var_z_abs, double dt); // Getters for the state and its covariance. double GetXAbs() const { return x_abs_; } double GetXVel() const { return x_vel_; } double GetCovAbsAbs() const { return p_abs_abs_; } double GetCovAbsVel() const { return p_abs_vel_; } double GetCovVelVel() const { return p_vel_vel_; } }; #endif // KALMANFILTER_H
f8948400cf2c01c502615624847b1e65429e7d82
3e957667997b0ac40319d68981a734b4800ee05d
/cpp/tablica2w.cpp
d741138187bee35473039eaaed4b0d7bdd6740b6
[]
no_license
weronikaramus/gitrepo
9ab9070bfe7ace6e3345dc6224b3bc4a5544ef06
3a6d92cbd8db4cb1e6eff10fe4a8e3f25d0c03e9
refs/heads/master
2021-06-27T23:08:03.695422
2020-10-08T10:37:38
2020-10-08T10:37:38
148,303,896
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
tablica2w.cpp
#include <iostream> #include <iomanip> using namespace std; #define N 11 #define M 11 int main(int argc, char **argv) { int tab2w[N][M]; int i, j; srand(time(NULL)); //inicjacja generatora liczb pseudolosowych for(i=1; i < N; i++){ // cout << "*** Tablica " << i << " ***" << endl; for(j=1; j < M; j++){ // cout << i << "-" << j << endl; tab2w[i][j] = i*j; cout << setw(4) << tab2w[i][j] << " "; } cout << endl; } return 0; }
b50dfa48941cd9446c6bbd87f7ed6244be98c694
d0ce9a4d75d935cf1aeb39854af635b2fb2ad8a9
/data-science_01-master/C++ Algo Files/spoj/Broken Keyboard.cpp
694567e24495e2da1d2f465281ee96db5c5e68db
[]
no_license
developer-rishabh/Programmes
d9e840ddb3460277fd8730152a129287c593a360
5178cf6ede953c16ba35336e9fce6c323d84c3db
refs/heads/master
2020-12-24T10:40:53.679762
2016-11-08T01:25:18
2016-11-08T01:25:18
73,136,324
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
Broken Keyboard.cpp
#include <bits/stdc++.h> using namespace std; int main() { string s; int n; cin>>n; while(n!=0) { int i; getchar(); getline(cin,s); int k=s.length(); set<char>set_CH; map<char,int>CH_map; for (i=0;i<k && i<n;i++) { if(!CH_map[s[i]]) { CH_map[s[i]]=1; set_CH.insert(s[i]); } else { CH_map[s[i]]++; } } int u=0,d=i-u; while(i<k) { set_CH.insert(s[i]); CH_map[s[i]]++; if(set_CH.size()>n) { while(CH_map[s[u]]>1) CH_map[s[u++]]--; CH_map[s[u]]=0; set_CH.erase(s[u++]); } i++; d=max(d,i-u); } cout<<d<<endl; cin>>n; } return 0; }
a51bc8204f6540591b5fd9dca7c458d0619a8c7b
1e17f6f0f9756d6043eb2a2d71dfd0e6c09590b2
/périmé/scripts/pycsw/geos-3.3.3/src/geomgraph/EdgeIntersectionList.cpp
b98388e9491260202af20bb29e9ec280c8fdb95a
[ "MIT", "LGPL-2.1-only" ]
permissive
federal-geospatial-platform/fgp-metadata-proxy
20e300b68eedfb29eed3e1cd24a69cf3c52898c3
82368614a2658260c0f09a1b5d341918310626e5
refs/heads/master
2023-08-09T14:03:35.522230
2023-08-03T15:10:11
2023-08-03T15:10:11
160,414,397
10
7
MIT
2023-05-01T23:16:00
2018-12-04T20:24:01
C++
UTF-8
C++
false
false
4,676
cpp
EdgeIntersectionList.cpp
/********************************************************************** * $Id: EdgeIntersectionList.cpp 3340 2011-05-10 09:51:31Z strk $ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geomgraph/EdgeIntersectionList.java rev. 1.5 (JTS-1.10) * **********************************************************************/ #include <geos/geomgraph/EdgeIntersectionList.h> #include <geos/geomgraph/EdgeIntersection.h> #include <geos/geomgraph/Edge.h> #include <geos/geomgraph/Label.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/CoordinateArraySequence.h> // shouldn't be using this #include <geos/geom/Coordinate.h> #include <sstream> #include <string> #include <vector> #include <set> #include <utility> // std::pair #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #if GEOS_DEBUG || GEOS_DEBUG_INTERSECT #include <iostream> #endif using namespace std; using namespace geos::geom; namespace geos { namespace geomgraph { // geos.geomgraph EdgeIntersectionList::EdgeIntersectionList(Edge *newEdge): edge(newEdge) { } EdgeIntersectionList::~EdgeIntersectionList() { for (EdgeIntersectionList::iterator it=nodeMap.begin(), endIt=nodeMap.end(); it!=endIt; ++it) { delete *it; } } EdgeIntersection* EdgeIntersectionList::add(const Coordinate& coord, int segmentIndex, double dist) { EdgeIntersection *eiNew=new EdgeIntersection(coord, segmentIndex, dist); pair<EdgeIntersectionList::iterator, bool> p = nodeMap.insert(eiNew); if ( p.second ) { // new EdgeIntersection inserted return eiNew; } else { delete eiNew; return *(p.first); } } bool EdgeIntersectionList::isEmpty() const { return nodeMap.empty(); } bool EdgeIntersectionList::isIntersection(const Coordinate& pt) const { EdgeIntersectionList::const_iterator it=nodeMap.begin(), endIt=nodeMap.end(); for (; it!=endIt; ++it) { EdgeIntersection *ei=*it; if (ei->coord==pt) return true; } return false; } void EdgeIntersectionList::addEndpoints() { int maxSegIndex=edge->getNumPoints()-1; add(edge->pts->getAt(0), 0, 0.0); add(edge->pts->getAt(maxSegIndex), maxSegIndex, 0.0); } void EdgeIntersectionList::addSplitEdges(vector<Edge*> *edgeList) { // ensure that the list has entries for the first and last point // of the edge addEndpoints(); EdgeIntersectionList::iterator it=nodeMap.begin(); // there should always be at least two entries in the list EdgeIntersection *eiPrev=*it; ++it; while (it!=nodeMap.end()) { EdgeIntersection *ei=*it; Edge *newEdge=createSplitEdge(eiPrev,ei); edgeList->push_back(newEdge); eiPrev=ei; it++; } } Edge * EdgeIntersectionList::createSplitEdge(EdgeIntersection *ei0, EdgeIntersection *ei1) { #if GEOS_DEBUG cerr<<"["<<this<<"] EdgeIntersectionList::createSplitEdge()"<<endl; #endif // GEOS_DEBUG int npts=ei1->segmentIndex-ei0->segmentIndex+2; const Coordinate& lastSegStartPt=edge->pts->getAt(ei1->segmentIndex); // if the last intersection point is not equal to the its segment // start pt, add it to the points list as well. // (This check is needed because the distance metric is not totally // reliable!). The check for point equality is 2D only - Z values // are ignored bool useIntPt1=ei1->dist>0.0 || !ei1->coord.equals2D(lastSegStartPt); if (!useIntPt1) --npts; #if GEOS_DEBUG cerr<<" npts:"<<npts<<endl; #endif // GEOS_DEBUG vector<Coordinate> *vc=new vector<Coordinate>(); vc->reserve(npts); vc->push_back(ei0->coord); for(int i=ei0->segmentIndex+1; i<=ei1->segmentIndex;i++) { if ( ! useIntPt1 && ei1->segmentIndex == i ) { vc->push_back(ei1->coord); } else { vc->push_back(edge->pts->getAt(i)); } } if (useIntPt1) { vc->push_back(ei1->coord); } CoordinateSequence* pts=new CoordinateArraySequence(vc); return new Edge(pts, new Label(*(edge->getLabel()))); } string EdgeIntersectionList::print() const { std::stringstream ss; ss << *this; return ss.str(); } std::ostream& operator<< (std::ostream&os, const EdgeIntersectionList& e) { os << "Intersections:" << std::endl; EdgeIntersectionList::const_iterator it=e.begin(), endIt=e.end(); for (; it!=endIt; ++it) { EdgeIntersection *ei=*it; os << *ei << endl; } return os; } } // namespace geos.geomgraph } // namespace
0327f933fc9239919168d7eff96692794c00c5e0
52bbfa038663d7564a8e4df85e4bd0c332cb242f
/Urho3DDebugCamera/ThirdPersonDebugCamera.hpp
61ab8bfc778d3e07b299c835932f8fb5aee1cded
[ "MIT" ]
permissive
KonstantinTomashevich/gamedev-utils
b5fa1f665e42e5cb62fb1b6ea53982ecc60f1442
e210616667a621391898ea3aaf773cf5d07275b9
refs/heads/master
2020-03-22T14:09:46.579126
2018-11-12T08:19:24
2018-11-12T08:19:24
140,157,569
1
0
MIT
2018-07-12T17:51:48
2018-07-08T10:20:51
C++
UTF-8
C++
false
false
1,643
hpp
ThirdPersonDebugCamera.hpp
#pragma once #include "DebugCameraBase.hpp" #include <Urho3D/Core/Context.h> #include <Urho3D/Scene/Node.h> #include <Urho3D/Input/Input.h> class ThirdPersonDebugCamera : public DebugCameraBase { URHO3D_OBJECT (ThirdPersonDebugCamera, DebugCameraBase) public: explicit ThirdPersonDebugCamera (Urho3D::Context *context); virtual ~ThirdPersonDebugCamera () = default; float GetMoveSpeed () const; void SetMoveSpeed (float moveSpeed); float GetRotationSpeed () const; void SetRotationSpeed (float rotationSpeed); Urho3D::Key GetKeyForward () const; void SetKeyForward (Urho3D::Key keyForward); Urho3D::Key GetKeyBackward () const; void SetKeyBackward (Urho3D::Key keyBackward); Urho3D::Key GetKeyUp () const; void SetKeyUp (Urho3D::Key keyUp); Urho3D::Key GetKeyDown () const; void SetKeyDown (Urho3D::Key keyDown); Urho3D::Key GetKeyLeft () const; void SetKeyLeft (Urho3D::Key keyLeft); Urho3D::Key GetKeyRight () const; void SetKeyRight (Urho3D::Key keyRight); Urho3D::Key GetKeyRotateLeft () const; void SetKeyRotateLeft (Urho3D::Key keyRotateLeft); Urho3D::Key GetKeyRotateRight () const; void SetKeyRotateRight (Urho3D::Key keyRotateRight); protected: virtual void HandleSceneUpdate (Urho3D::StringHash eventType, Urho3D::VariantMap &eventData); private: float moveSpeed_; float rotationSpeed_; Urho3D::Key keyForward_; Urho3D::Key keyBackward_; Urho3D::Key keyUp_; Urho3D::Key keyDown_; Urho3D::Key keyLeft_; Urho3D::Key keyRight_; Urho3D::Key keyRotateLeft_; Urho3D::Key keyRotateRight_; };
f45ce9bee2e770988fc28e52a00a9e38711dd63f
69e1199b2daffa17e4842e94a54be152df540828
/怀化学院程序设计在线/Wacmian数字.cpp
198189ed8d6f1d3dbc231041717f90751faa97a3
[]
no_license
shaobozhong/myAcmCodes
8c63e7992d0975626e6e583a49e59fe03f73017c
55b31b8a4600fd3084795f71ac0d244cbdc58800
refs/heads/master
2023-08-04T20:05:29.165456
2023-07-26T03:19:52
2023-07-26T03:19:52
21,147,335
0
1
null
2023-07-26T03:19:53
2014-06-24T00:49:13
null
UTF-8
C++
false
false
578
cpp
Wacmian数字.cpp
#include<iostream> #include<cstring> #include<cmath> using namespace std; int main() { int i,sum,len; char str[1000]; while(cin>>str,strcmp(str,"#")!=0) { sum=0; len=(int)strlen(str); for(i=0;i<len;++i) { switch(str[len-i-1]) { case '%':break; case ')': sum+=(int)pow(6.0,i);break; case '~': sum+=(int)2*pow(6.0,i); break; case '@': sum+=(int)3*pow(6.0,i); break; case '?': sum+=(int)4*pow(6.0,i);break; case 92: sum+=(int)5*pow(6.0,i);break; case '$': sum-=(int)pow(6.0,i); } } cout<<sum<<endl; } return 0; }
5c89f05484c0ef301828c036386cbb39872f12b9
198806ccd0b5a7d476c701be5943e9a7afacb7d0
/xdaq/include/ws/eventing/ServiceAdapterBase.h
1a4a99cefac6a620350ba6293c5034d4fe03e875
[]
no_license
marcomuzio/EMULib_CLCT_Timing
df5999b5f1187725d7f5b6196ba566045ba60f55
04e930d46cadaa0c73b94a0c22e4478f55fac844
refs/heads/master
2021-01-16T13:47:26.141865
2014-08-14T12:04:33
2014-08-14T12:04:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
h
ServiceAdapterBase.h
// $Id: ServiceAdapterBase.h,v 1.4 2008/07/18 15:27:50 gutleber Exp $ /************************************************************************* * XDAQ Components for Distributed Data Acquisition * * Copyright (C) 2000-2009, CERN. * * All rights reserved. * * Authors: J. Gutleber and L. Orsini * * * * For the licensing terms see LICENSE. * * For the list of contributors see CREDITS. * *************************************************************************/ #ifndef _ws_eventing_ServiceAdapterBase_h_ #define _ws_eventing_ServiceAdapterBase_h_ #include "toolbox/Properties.h" #include "ws/eventing/StorageAdapter.h" namespace ws { namespace eventing { class ServiceAdapterBase { public: ServiceAdapterBase( StorageAdapter* sa); StorageAdapter* getAdapter(); void setAdapter (StorageAdapter* ai); toolbox::Properties& getProperties(); protected: toolbox::Properties properties_; StorageAdapter* adapter_; }; } } #endif
78c7191553166c294d83a7d5c4ec4252ecfe6434
b91ce8cd68a993b6569f0fbeb9b44811d1dcd492
/src/stream/analysis/RtCurrentActivation.cpp
c4b50bedc3bb54bfbb59187ee501a5282bf48997
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
gablab/murfi2
27f54adf178277d764c4dfe1da69ead1ad4cfcfa
21fc77d722d88cbf16f64665cf25e0792a3e1b98
refs/heads/master
2023-07-31T11:40:19.701781
2023-06-15T21:00:49
2023-06-15T21:00:49
11,222,191
8
9
NOASSERTION
2023-06-15T21:18:13
2013-07-06T18:06:58
C++
UTF-8
C++
false
false
9,085
cpp
RtCurrentActivation.cpp
/*========================================================================= * RtCurrentActivation.cpp is the implementation of a class * * ****************************************************************************/ #include "RtDesignMatrix.h" #include"RtCurrentActivation.h" #include"RtMRIImage.h" #include"RtActivation.h" #include"RtDataIDs.h" #include"RtExperiment.h" #include"RtElementAccess.h" #include"util/timer/timer.h" #include"debug_levels.h" string RtCurrentActivation::moduleString(ID_CURRENTACTIVATION); // default constructor RtCurrentActivation::RtCurrentActivation() : RtStreamComponent() { componentID = moduleString; steadyStateResidual = NULL; numDataPointsForErrEst = std::numeric_limits<unsigned int>::max(); } // destructor RtCurrentActivation::~RtCurrentActivation() { } // initialize the estimation algorithm for a particular image size void RtCurrentActivation::initEstimation(RtMRIImage &dat, RtMaskImage *mask) { } // process an option in name of the option to process val text of the option // node bool RtCurrentActivation::processOption(const string &name, const string &text, const map<string, string> &attrMap) { // look for known options if (name == "modelFitModuleID") { modelFitModuleID = text; return true; } if (name == "modelFitRoiID") { modelFitRoiID = text; return true; } if (name == "numDataPointsForErrEst") { return RtConfigVal::convert<unsigned int>(numDataPointsForErrEst, text); } if (name == "saveResult") { return RtConfigVal::convert<bool>(saveResult, text); } return RtStreamComponent::processOption(name, text, attrMap); } // validate the configuration bool RtCurrentActivation::validateComponentConfig() { bool result = true; if (modelFitModuleID.empty()) { cerr << "RtCurrentActivation::process: modelFitModuleID is empty" << endl; result = false; } if (modelFitRoiID.empty()) { cerr << "RtCurrentActivation::process: modelFitRoiID is empty" << endl; result = false; } return result; } // process a single acquisition int RtCurrentActivation::process(ACE_Message_Block *mb) { ACE_TRACE(("RtCurrentActivation::process")); timer tim; if(printTiming) { tim.start(); } // get pointer to message RtStreamMessage *msg = (RtStreamMessage*) mb->rd_ptr(); // get the current image to operate on RtMRIImage *dat = (RtMRIImage*) msg->getCurrentData(); // check for validity of data if (dat == NULL) { cerr << "RtCurrentActivation::process: data passed is NULL" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: data passed is NULL" << endl; log(logs); } return 0; } // get mask from msg RtMaskImage *mask = getMaskFromMessage(*msg); // check validity of mask if (mask == NULL) { cerr << "RtCurrentActivation::process: mask is NULL" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: mask is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } // initialize the computation if necessary if (needsInit) { initEstimation(*dat, mask); } // get design // TODO this may not work if there are more than one design matrix RtDataID tempDataID; tempDataID.setDataName(NAME_DESIGN); // debug // getDataStore().getAvailableData(); RtDesignMatrix *design = static_cast<RtDesignMatrix*>( getDataStore().getData(tempDataID)); if(design == NULL) { cerr << "error: could not find design matrix in datastore!" << endl; cerr << "searched for design matrix id: " << tempDataID << endl; return 0; } // allocate a new data image for the stats RtActivation *currentActivation = new RtActivation(*dat); // setup the data id currentActivation->getDataID().setFromInputData(*dat, *this); currentActivation->getDataID().setDataName(NAME_ACTIVATION); currentActivation->getDataID().setRoiID(modelFitRoiID); currentActivation->initToNans(); // get the residual and the beta images for discounting nuissance // signals // find the betas RtActivation **betas = new RtActivation*[design->getNumColumns()]; for(unsigned int j = 0; j < design->getNumColumns(); j++) { betas[j] = (RtActivation*) msg->getData(modelFitModuleID, string(NAME_BETA) + "_" + design->getColumnName(j), modelFitRoiID); // check for found if (betas[j] == NULL) { cerr << "RtCurrentActivation:process: beta " << j << " is null" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: beta " << j << " is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } } // get residual from message if timepoint is less than // numDataPointsForErrEst otherwise use the steady state // residual value RtActivation *residual; if (dat->getDataID().getTimePoint() < numDataPointsForErrEst) { // get residual off of msg residual = (RtActivation *) msg->getData(modelFitModuleID, NAME_RESIDUAL_MSE, modelFitRoiID); // save off residual steadyStateResidual = residual; } else { // post-numDataPointsForErrEst, use saved residual residual = steadyStateResidual; } // check that residual is not null if (residual == NULL) { cerr << "RtCurrentActivation:process: residual is null" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: residual is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } // get this design matrix row vnl_vector<double> Xrow = design->getRow(dat->getDataID().getTimePoint()-1); // include this timepoint for each voxel RtElementAccess datAc(dat, mask); RtElementAccess resAc(residual, mask); vector<unsigned int> inds = datAc.getElementIndices(); for(vector<unsigned int>::iterator it = inds.begin(); it != inds.end(); it++) { // get voxel intensity double y = datAc.getDoubleElement(*it); double *betavals = new double[Xrow.size()]; // compute error double err = y; for (unsigned int j = 0; j < Xrow.size(); j++) { if (!design->isColumnOfInterest(j)) { double beta = betas[j]->getPixel(*it); err -= beta * Xrow[j]; betavals[j] = beta; } else { // for debug output betavals[j] = betas[j]->getPixel(*it); } } // compute the dev and current activation (magic happens here) double dev = sqrt(resAc.getDoubleElement(*it) / (residual->getDataID().getTimePoint())); currentActivation->setPixel(*it, err / dev); if (dumpAlgoVars && dat->getDataID().getTimePoint() > 2) { dumpFile << dat->getDataID().getTimePoint() << " " << *it << " " << y << " " << err << " " << Xrow[0] << " " << residual->getPixel(*it) << " " << dev << " " << currentActivation->getPixel(*it) << " "; for (unsigned int b = 0; b < design->getNumColumns(); b++) { dumpFile << betavals[b] << " "; } dumpFile << endl; } delete [] betavals; } setResult(msg, currentActivation); setResult(msg, residual); delete [] betas; if(printTiming) { tim.stop(); cout << "RtCurrentActivation process at tr " << dat->getDataID().getTimePoint() << " elapsed time: " << tim.elapsed_time()*1000 << "ms" << endl; } if(print) { cout << "RtCurrentActivation: done at tr " << dat->getDataID().getTimePoint() << endl; } if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation: done at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } if(saveResult) { string fn = getExperimentConfig().getVolFilename( dat->getDataID().getSeriesNum(), dat->getDataID().getTimePoint()); string stem = getExperimentConfig().get("study:volumeFileStem").str(); currentActivation->setFilename(fn.replace(fn.rfind(stem), stem.size(), "curact")); currentActivation->save(); } return 0; } // start a logfile void RtCurrentActivation::startDumpAlgoVarsFile() { dumpFile << "started at "; printNow(dumpFile); dumpFile << endl << "time_point " << "voxel_index " << "voxel_intensity " << "activation_signal " << "condition " << "residual " << "dev " << "current_activation "; // aka feedback for (int b = 0; b < 3; b++) { dumpFile << "beta[" << b << "] "; } dumpFile << "end" << endl; }
c186d39c04f10eabfde66eced70d7cececbd1354
93551335720c7cca0936dc032ddb903493136fd5
/test/database-fixture.h
59466e0cb8f15423922cf127d7cb4587d50e4a68
[]
no_license
prismskylabs/IndexedBuffer
dba5bb75a15954eba9513f89e9735918c2358560
f0021356faf1307c4f6deb9fe9edacb02a8f5c20
refs/heads/master
2022-04-30T12:22:29.990081
2022-03-19T00:20:39
2022-03-19T00:20:39
48,079,550
0
0
null
null
null
null
UTF-8
C++
false
false
1,853
h
database-fixture.h
#include <map> #include <string> #include <boost/filesystem.hpp> #include <gtest/gtest.h> #include <sqlite3.h> #include "filesystem-fixture.h" #include "indexed/database.h" namespace fs = ::boost::filesystem; class DatabaseFixture : public FilesystemFixture { protected: using Record = std::map<std::string, std::string>; virtual void SetUp() { FilesystemFixture::SetUp(); fs::create_directory(buffer_path_); db_path_ = buffer_path_ / "prism_indexed_data.db"; db_string_ = db_path_.string(); table_name_ = "prism_indexed_data"; } sqlite3* openDatabase() { sqlite3* sqlite_db; if (sqlite3_open(db_string_.data(), &sqlite_db) != SQLITE_OK) { throw prism::indexed::DatabaseException{sqlite3_errmsg(sqlite_db)}; } return sqlite_db; } int closeDatabase(sqlite3* db) { return sqlite3_close(db); } static int callback(void* response_ptr, int num_values, char** values, char** names) { auto response = (std::vector<Record>*) response_ptr; auto record = Record(); for (int i = 0; i < num_values; ++i) { if (values[i]) { record[names[i]] = values[i]; } } response->push_back(record); return 0; } std::vector<Record> execute(const std::string& sql) { std::vector<Record> response; auto db = openDatabase(); char* error; int rc = sqlite3_exec(db, sql.data(), &callback, &response, &error); if (rc != SQLITE_OK) { auto error_string = std::string{error}; sqlite3_free(error); throw prism::indexed::DatabaseException{error_string}; } return response; } fs::path db_path_; std::string db_string_; std::string table_name_; };
0d121688ba792aca61acb30ff62c687fe1d2c03c
20c83c64dfb375ac0fe984f02c21ab44f9730e5a
/move_group/src/PubPointCloudCollision.cpp
746951c1d0ac1dd585da698759908ef1b92ede3f
[]
no_license
weili666/move_group
3d752d141527188036bbce13f4badd289216fcdd
0616144c477ab25efd2d258328e2bd7793b2dea0
refs/heads/master
2021-05-16T07:13:56.412642
2020-09-01T06:53:50
2020-09-01T06:53:50
103,650,822
0
0
null
null
null
null
UTF-8
C++
false
false
6,016
cpp
PubPointCloudCollision.cpp
#include "ros/ros.h" #include <sensor_msgs/PointCloud2.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/voxel_grid.h> #include <opencv/cv.hpp> #include <opencv/highgui.h> #include <opencv2/core/eigen.hpp> #include <moveit/move_group_interface/move_group.h> #include "ompl/util/Time.h" #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit_msgs/AttachedCollisionObject.h> #include <moveit_msgs/CollisionObject.h> #include <moveit/robot_state/robot_state.h> typedef move_group_interface::MoveGroup C_moveGroup; typedef moveit::planning_interface::MoveGroup::Plan S_Plan; typedef moveit::planning_interface::PlanningSceneInterface S_PlanningSceneInterface; using namespace std; int n = 0; class PubCircumstance { public: PubCircumstance(ros::NodeHandle& nh_):nh(nh_) { display_Point3 = nh.advertise<sensor_msgs::PointCloud2>("/camera/depth/points_filter", 1, true); display_Marker = nh.advertise<visualization_msgs::MarkerArray>("/marker/depth/points_filter", 1, true); planning_scene_diff_publisher = nh.advertise<moveit_msgs::PlanningScene>("planning_scene", 1); ros::Subscriber sub = nh.subscribe("/xtion/depth_registered/points", 1, & PubCircumstance::Cloud_Cb, this); ros::spin(); } void Cloud_Cb( const sensor_msgs::PointCloud2ConstPtr& input ); void Read_Rt(); private: ros::NodeHandle nh; ros::Publisher display_Point3; ros::Publisher display_Marker; ros::Publisher planning_scene_diff_publisher; cv::Mat R_external; cv::Mat t_external; cv::Mat R_checkerboard; cv::Mat t_checkerboard; cv::Mat R_real; cv::Mat t_real; }; void PubCircumstance::Cloud_Cb( const sensor_msgs::PointCloud2ConstPtr& input ) { pcl::PointCloud < pcl::PointXYZRGB > cloud; pcl::PointCloud < pcl::PointXYZRGB > cloudrt; visualization_msgs::MarkerArray markerArray; std::vector<moveit_msgs::CollisionObject> collision_objects; moveit_msgs::PlanningScene planning_scene; double height_table = 0.73; pcl::fromROSMsg(*input,cloud); Read_Rt(); for( int i = 0; i < cloud.points.size(); i ++ ) { cv::Mat xp(3,1,CV_32F); cv::Mat xnew(3,1,CV_32F); xp.at<float>(0,0) = cloud.points[i].x; xp.at<float>(1,0) = cloud.points[i].y; xp.at<float>(2,0) = cloud.points[i].z; xnew = R_real*xp + t_real; pcl::PointXYZRGB p; p.x = xnew.at<float>(0,0); p.y = xnew.at<float>(1,0); p.z = xnew.at<float>(2,0) + height_table; if(p.z > height_table) { p.r = cloud.points[i].r; p.g = cloud.points[i].g; p.b = cloud.points[i].b; cloudrt.push_back(p); } } sensor_msgs::PointCloud2 output; pcl::toROSMsg(cloudrt,output); output.header.frame_id = "world_frame"; display_Point3.publish(output); } void PubCircumstance::Read_Rt() { ifstream ifile; ifile.open("/home/weili/simple_kinova/src/camera_calibration/saved_image/extern_matrix.txt"); char buffer[256]; int num=0; int num_of_ros = 6; vector< vector<char> > data_; vector<char> data_iter; if(!ifile.is_open()) {cout << "Error opening file"; exit (1);} while(num_of_ros) { data_iter.clear(); ifile.getline(buffer,100); for(int i=0;i<256;i++) { if((buffer[i]=='[')||(buffer[i]==' ')) { continue; } else if(buffer[i]==',') { data_.push_back(data_iter); data_iter.clear(); num++; continue; } else if(buffer[i]==';') { data_.push_back(data_iter); data_iter.clear(); num++; break; } else if(buffer[i]==']') { data_.push_back(data_iter); data_iter.clear(); num++; break; } else { data_iter.push_back(buffer[i]); } } num_of_ros--; } double ddata[12]; for(int i=0;i<12;i++) { string data; for(int j=0;j<data_[i].size();j++) { data+=data_[i][j]; } ddata[i]=atof(data.c_str()); } ros::Rate loop_rate(10000); R_external.create(3,3,CV_32F); t_external.create(3,1,CV_32F); R_external.at<float>(0,0) = ddata[0]; R_external.at<float>(0,1) = ddata[1]; R_external.at<float>(0,2) = ddata[2]; R_external.at<float>(1,0) = ddata[3]; R_external.at<float>(1,1) = ddata[4]; R_external.at<float>(1,2) = ddata[5]; R_external.at<float>(2,0) = ddata[6]; R_external.at<float>(2,1) = ddata[7]; R_external.at<float>(2,2) = ddata[8]; t_external.at<float>(0,0) = ddata[9]/1000; t_external.at<float>(1,0) = ddata[10]/1000; t_external.at<float>(2,0) = ddata[11]/1000; R_checkerboard=R_external.inv(); t_checkerboard = -R_checkerboard*t_external; cv::Mat R_ch2re(3,3,CV_32F); R_ch2re.at<float>(0,0) = 0; R_ch2re.at<float>(0,1) = 1; R_ch2re.at<float>(0,2) = 0; R_ch2re.at<float>(1,0) = -1; R_ch2re.at<float>(1,1) = 0; R_ch2re.at<float>(1,2) = 0; R_ch2re.at<float>(2,0) = 0; R_ch2re.at<float>(2,1) = 0; R_ch2re.at<float>(2,2) = 1; R_real = R_ch2re*R_checkerboard; //cout<<"R_real:"<<R_real<<endl; t_real = R_ch2re*t_checkerboard; //cout<<"t_real:"<<t_real<<endl; } int main(int argc,char **argv) { ros::init(argc, argv, "pub_point_cloud_collision"); ros::NodeHandle node_handle; PubCircumstance pubc(node_handle); return 0; }
343150d73ef121302672e5dfa3bb99dc91925db7
09c5c4baed3d26701e866be100e4e52d9a34b856
/StudyAlone/C_Practice/DiskManager/main.cpp
a3cc2979b78a2bab3a473dc28812da1250c9f4c6
[]
no_license
sangdo913/Algorithms
556ac5fc789e35df2f65601e4439caca967edd7b
ee11265895d8ce3314f009df38166defc4b946c7
refs/heads/master
2022-09-11T12:00:58.615980
2022-07-31T11:11:04
2022-07-31T11:11:04
116,484,870
3
0
null
null
null
null
UTF-8
C++
false
false
4,129
cpp
main.cpp
#include <stdio.h> #include "user.cpp" #include <time.h> #include <memory.h> static char dummy1[5][1024][1024]; static char disk[16][1024][1024]; static int disk_id; static int disk_total; static char file_name[100][16]; static int file_size[100]; static char dummy2[6][1024][1024]; static int SCORE = 0; static int seed = 3; static int MOD = 1 << 16; static int PANELTY = 10000; extern void init(); extern void read_file(char* filename, int offset, char* data, int size); extern void insert_file(char* filename, int offset, char* data, int size); extern void delete_file(char* filename, int offset, int size); static int pseudo_rand(void) { seed = seed * 214013 + 2531011; return (seed >> 16) & 0x7FFF; } static unsigned long hash(const char *str, int str_len) { unsigned long hash = 5381; for (int i = 0; i < str_len; i++) hash = (((hash << 5) + hash) + str[i]) % MOD; return hash % MOD; } bool change_disk(int disk) { if (disk >= 16 || disk < 0) return false; disk_id = disk; return true; } bool read_disk(int sector, char* data) { if (sector >= 1024 || sector < 0) return false; memcpy(data, &(disk[disk_id][sector][0]), 1024); return true; } bool write_disk(int sector, char* data) { if (sector >= 1024 || sector < 0) return false; memcpy(&(disk[disk_id][sector][0]), data, 1024); return true; } static void _build(void) { init(); for (int c = 0; c < 100; c++) { for (int l = 0; l < 16; l++) file_name[c][l] = 'A' + (pseudo_rand() % 26); file_size[c] = 0; } } static void _insert(void) { char data[4096]; char file_name_arg[17]; int file = pseudo_rand() % 100; int offset = (pseudo_rand() * pseudo_rand()) % (file_size[file] + 1); int data_size = pseudo_rand() % 4096 + 1; for (register int i = 0; i < data_size; i++) data[i] = pseudo_rand() % 255 + 1; for (register int i = 0; i < 16; i++) file_name_arg[i] = file_name[file][i]; insert_file(file_name_arg, offset, data, data_size); file_size[file] += data_size; disk_total += data_size; // if(fcnt[5] != file_size[file]){ // printf("wrong\n"); // int debug = 1; // } // else printf("%d %d\n", fcnt[5], file_size[file]); } static void _delete(void) { char file_name_arg[17]; int file = pseudo_rand() % 100; int offset = (pseudo_rand() * pseudo_rand()) % (file_size[file] + 1); int data_size = pseudo_rand() % 4096 + 1; if (file_size[file] - offset < data_size) data_size = file_size[file] - offset; if (data_size == 0) return; for (register int i = 0; i < 16; i++) file_name_arg[i] = file_name[file][i]; delete_file(file_name_arg, offset, data_size); file_size[file] -= data_size; disk_total -= data_size; // if(fcnt[5] != file_size[file]){ // int debug = 1; // printf("wrong\n"); // } // else printf("%d %d %d\n", file, fcnt[5], file_size[file]); } static void _verify(int file) { char file_name_arg[17]; char data[4096]; int correct_ans = 0; int offset = (pseudo_rand() * pseudo_rand()) % (file_size[file]); int data_size = pseudo_rand() % 4096 + 1; if (file_size[file] - offset < data_size) data_size = file_size[file] - offset; for (register int i = 0; i < 16; i++) file_name_arg[i] = file_name[file][i]; read_file(file_name_arg, offset, data, data_size); int user_ans = hash(data, data_size); scanf("%d", &correct_ans); if (correct_ans != user_ans) SCORE += PANELTY; } int main(void) { freopen("0Text.txt", "r", stdin); // printf("---------------\n"); clock_t START = clock(); for (int T = 0; T < 10; T++) { _build(); disk_total = 0; while (disk_total < 10 * 1024 * 1024) { switch (pseudo_rand() % 10) { case 0: case 1: case 2: case 3: case 4: case 5: _insert(); break; case 6: case 7: case 8: case 9: _delete(); break; } } for (int i = 0; i < 100; i++){ if (file_size[i] == 0)continue; _verify(i); } // printf("tc : %d // score : %d\n", T, SCORE); } // printf("%lf\n", (double)(clock() - START) / (CLOCKS_PER_SEC)); SCORE += (clock() - START) / (CLOCKS_PER_SEC / 1000); if (SCORE < PANELTY) printf("PASS\n"); else printf("FAIL\n"); // printf("SCORE: %d\n", SCORE); }
d6619c2a6719d6442023f59a1138392491ac30fe
aabf2d9eacfc7bdafce823920507c073b94d24f5
/RaccoonBranch/Raccoon/Raccoon with Burn/IDT-Lib/IDT-Srv/VaultIC100Adapter.cpp
b68fb2ecb359161ef22e37b36f1ab8fbe7ebd60a
[]
no_license
SlavaC1/ControlSW
90a5cf3709ea3d49db5126f0091c89428f5e1f49
6c8af513233a5d3d7c7f0d8b4d89c0ee69a661cb
refs/heads/master
2021-01-10T15:47:23.183784
2016-03-04T13:33:26
2016-03-04T13:33:26
53,054,100
0
0
null
null
null
null
UTF-8
C++
false
false
22,041
cpp
VaultIC100Adapter.cpp
#include "stdafx.h" #include "VaultIC100Adapter.h" #include "IDTHWInf.h" #include "vaultic_apdu.h" #include "Utils.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <iostream> using namespace std; using namespace RSCommon; namespace StratasysIDTSrv { #define COUNTER_NUMBER 1 #define COUNTER_GROUP 1 #define CERTIFICATE_PATH "/cert/.cer" #define DEVICE_MANUFACTURER_PASSWORD "C908010C049D31876FEFE6DBF746CE2DB041327492B1BD724B7889D80C0E5995" VaultIC100Adapter::VaultIC100Adapter() : m_theBaseApi(NULL), m_cartridgeInfo(new VLT_TARGET_INFO()), m_bUseUsb(false) { } VaultIC100Adapter::~VaultIC100Adapter() { Cleanup(); } void VaultIC100Adapter::Cleanup() { if (m_theBaseApi != NULL) { m_bIsInitialized = false; } delete m_cartridgeInfo; m_theBaseApi = NULL; } int VaultIC100Adapter::InitHW(unsigned char *pucCartridgesCount) { LOG_EXT(LEVEL_DEBUG, "Initializing hardware..."); int returnValue; int status = 0; unsigned int uiDeviceSerialNumber = 0; int cartridgesCount; #ifdef ENABLE_USB returnValue = ParseDeviceSerialNumber(&uiDeviceSerialNumber); m_bUseUsb = ((returnValue == VLT_OK) && (uiDeviceSerialNumber != 0)); #endif if (m_bUseUsb) { cartridgesCount = 1; status = 1; } else { IdtClose(); returnValue = IdtInit(&cartridgesCount); if (returnValue == FALSE) { return FCB_INIT_FAILED; } returnValue = GetInPlaceStatus(&status); if (returnValue != IDTLIB_SUCCESS) { return returnValue; } } m_ucCartridgesCount = *pucCartridgesCount = (unsigned char)cartridgesCount; if (status != 0) { unsigned char cartridgeNum = 0; while (cartridgeNum < m_ucCartridgesCount) { if ((status & (1 << cartridgeNum)) != 0) { break; } cartridgeNum++; } if (cartridgeNum < m_ucCartridgesCount) { returnValue = InitLibrary(cartridgeNum, uiDeviceSerialNumber); } } return returnValue; } /// <summary> /// Initializes VaultIC100 library. /// </summary> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::InitLibrary(unsigned char ucCartridgeNum, unsigned int uiDeviceSerialNumber) { LOG_EXT(LEVEL_DEBUG, "Initializing VaultIC100 library..."); int returnValue; // Get VaultIC100 definitions VLT_INIT_COMMS_PARAMS commParams; commParams.u8CommsProtocol = VLT_TWI_COMMS; commParams.Params.VltBlockProtocolParams.VltPeripheralParams.PeriphParams.VltTwiParams.u16BusTimeout = 250; commParams.Params.VltBlockProtocolParams.VltPeripheralParams.PeriphParams.VltTwiParams.u32msTimeout = 4000; commParams.Params.VltBlockProtocolParams.VltPeripheralParams.PeriphParams.VltTwiParams.u8Address = 0x5F; commParams.Params.VltBlockProtocolParams.u16BitRate = 100; commParams.Params.VltBlockProtocolParams.u8CheckSumMode = BLK_PTCL_CHECKSUM_SUM8; commParams.Params.VltBlockProtocolParams.u32AfterHdrDelay = 1000; commParams.Params.VltBlockProtocolParams.u32InterBlkDelay = 1000; commParams.Params.VltBlockProtocolParams.u32InterHdrByteDelay = 1000; commParams.Params.VltBlockProtocolParams.u16msSelfTestDelay = 2500; commParams.Params.VltBlockProtocolParams.VltPeripheralParams.u32SerialNo = uiDeviceSerialNumber; IdtSelectChannel(ucCartridgeNum); returnValue = VltInitLibrary(&commParams); if (returnValue != VLT_OK) { return returnValue; } m_theBaseApi = VltGetApi(); m_bIsInitialized = true; return IDTLIB_SUCCESS; } #ifdef ENABLE_USB int VaultIC100Adapter::ParseDeviceSerialNumber(unsigned int *puiDeviceSerialNumber) { VLT_STS status = VLT_OK; // // Determine the size of the xml string that will be returned on the second call, // set the stringSize parameter to zero and the string to NULL. On return the // stringSize will be set to the actual number of characters of the XML string // that contains the list of devices. VLT_U32 stringSize = 0; if( VLT_OK != ( status = VltFindDevices( &stringSize, NULL ) ) ) { return status; } // // Allocate enough memory to hold the xml string with the list of // devices. VLT_PU8 pXmlString = (VLT_PU8)NULL; if( NULL == ( pXmlString = (VLT_PU8)malloc(stringSize ) ) ) { status = VLT_FIND_DEVS_MALLOC_FAIL; return status; } // // Now call the VltFindDevices again with all the appropriate parameters // On return the pXmlString will be filled with the device list. if( VLT_OK != ( status = VltFindDevices( &stringSize, pXmlString ) ) ) { free(pXmlString); return status; } // // Assign the XML string to a standard string string strXMLDevs =(const char*)pXmlString; free(pXmlString); status = ParseDeviceSerialNumber(strXMLDevs, puiDeviceSerialNumber); return status; } int VaultIC100Adapter::ParseDeviceSerialNumber(string strXmlDevs, unsigned int *puiDeviceSerialNumber) { if (VLT_ENABLE_AARDVARK == VLT_DISABLE) { *puiDeviceSerialNumber = 0; return VLT_OK; } VLT_STS status = VLT_FAIL; // Check if there are any PC/SC readers connected bool readerFound = false; string strReaderName(""); const char *pXmlData = "<peripheral idx=\"00\">"; const char *interfaceNodeName = "<interface type=\"aardvark\">"; size_t startPos, endPos; startPos = strXmlDevs.find(interfaceNodeName); if( string::npos != startPos ) { endPos = strXmlDevs.find("</interface>", startPos); if( string::npos == endPos) { status = VLT_MALFORMED_XML_AARDVARK_INTFC; return status; } string strDevice( strXmlDevs.substr( startPos, ( endPos - startPos ) ) ); // Reset start pointer & item number startPos = 0; do { // It does so check for entries for a reader startPos = strDevice.find("<peripheral idx=", startPos); if (string::npos == startPos) { // No more reader in the list = end of loop break; } else { // Start of the reader name is after the opening tag, // end position is at beginning of the closing tag startPos += strlen(pXmlData); endPos = strDevice.find("</peripheral>", startPos); if (string::npos == endPos) { break; } // Get the device serial number strReaderName = strDevice.substr(startPos, (endPos - startPos)); readerFound = true; } } while (true); } if (!readerFound) { //status = VLT_NO_READER_CONNECTED; //return status; *puiDeviceSerialNumber = 0; return VLT_OK; } startPos = strXmlDevs.find(interfaceNodeName); startPos = strXmlDevs.find(pXmlData, startPos); startPos += strlen(pXmlData); endPos = strXmlDevs.find("</peripheral>", startPos); // Get the reader name strReaderName = strXmlDevs.substr(startPos, (endPos - startPos)); *puiDeviceSerialNumber = strtoul(strReaderName.c_str(), NULL, 10); status = VLT_OK; return status; } #endif #if (ENABLE_BURNING == 1) int VaultIC100Adapter::Login() { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; const char* textualPassword = DEVICE_MANUFACTURER_PASSWORD; unsigned char passwordLength = (unsigned char)strlen(textualPassword); unsigned char *password = new unsigned char[passwordLength / 2]; HexStringToByteArray(textualPassword, passwordLength, password); LOG_EXT(LEVEL_DEBUG, "Logging in as manufacturer..."); returnValue = m_theBaseApi->VltSubmitPassword(passwordLength / 2, password); delete[] password; if (returnValue != VLT_OK) { if (returnValue = 0x6300) { return IDT_LOCKED; } return LOGIN_FAILED; } LOG_EXT(LEVEL_DEBUG, "Setting creation mode..."); returnValue = m_theBaseApi->VltSetStatus(VLT_CREATION); if (returnValue != VLT_OK) { if (returnValue == 0x6985) { return ACCESS_DENIED; } return TRANSITION_FAILED; } return IDTLIB_SUCCESS; } int VaultIC100Adapter::Configure() { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Setting K-283 curve..."); unsigned char ucCurve = VLT_ECDSA_CURVE_K283; returnValue = m_theBaseApi->VltSetConfig(VLT_ECDSA_DOMAIN_PARAM_CHOICE, VLT_ECDSA_PARAMS_CHOICE_SZ, &ucCurve); if (returnValue != VLT_OK) { return CONFIGURATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Setting non-FIPS mode..."); unsigned char ucFipsMode = 0; //unsigned char ucFipsMode = 1; returnValue = m_theBaseApi->VltSetConfig(VLT_FIPS_MODE, VLT_FIPS_MODE_SZ, &ucFipsMode); if (returnValue != VLT_OK) { return CONFIGURATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Enforce I2C communication..."); unsigned char ucCommunicationChannel = 3; //always use I2C returnValue = m_theBaseApi->VltSetConfig(VLT_COMMS_CHANNEL_ACCESS, VLT_COMMS_CHANNEL_SZ, &ucCommunicationChannel); if (returnValue != VLT_OK) { return CONFIGURATION_FAILED; } return IDTLIB_SUCCESS; } int VaultIC100Adapter::SetKeys(const unsigned char *aucPubKS) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Writing host ID..."); VLT_FILE_PRIVILEGES KeyPrivileges = { 0x03, 0x00, 0x0, 0x2 }; VLT_KEY_OBJECT KeyObj; KeyObj.u8KeyID = VLT_KEY_HOST_DEVICE_ID; KeyObj.data.HostDeviceIdKey.u16StringLen = VLT_HOST_DEV_ID_STRING_LENGTH; KeyObj.data.HostDeviceIdKey.pu8StringId = aucHostID; returnValue = m_theBaseApi->VltPutKey((VLT_U8)enHostKeyGroup, (VLT_U8)enHostDeviceIDKeyIndex, &KeyPrivileges, &KeyObj); if (returnValue != VLT_OK) { return KEY_GENERATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Writing device ID..."); unsigned char aucDeviceID[VLT_HOST_DEV_ID_STRING_LENGTH]; unsigned char ucDeviceIDLength; GetSerialNumber(aucDeviceID, &ucDeviceIDLength); memset(aucDeviceID + ucDeviceIDLength, '.', VLT_HOST_DEV_ID_STRING_LENGTH - ucDeviceIDLength); KeyObj.data.HostDeviceIdKey.pu8StringId = aucDeviceID; returnValue = m_theBaseApi->VltPutKey((VLT_U8)enDeviceKeyGroup, (VLT_U8)enHostDeviceIDKeyIndex, &KeyPrivileges, &KeyObj); if (returnValue != VLT_OK) { return KEY_GENERATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Writing host public key..."); ECDSA<EC2N, SHA256>::PublicKey pubKS; pubKS.Load(StringSource(aucPubKS, PUBLIC_KEY_SIZE, true).Ref()); EC2NPoint Q = pubKS.GetPublicElement(); VLT_U8 Qx[KEY_COEFF_SIZE]; VLT_U8 Qy[KEY_COEFF_SIZE]; Q.x.Encode(Qx, sizeof(Qx)); Q.y.Encode(Qy, sizeof(Qy)); KeyObj.u8KeyID = VLT_KEY_ECDSA_GF2M_PUB; KeyObj.data.EcdsaPubKey.u16QLen = KEY_COEFF_SIZE; KeyObj.data.EcdsaPubKey.pu8Qx = Qx; KeyObj.data.EcdsaPubKey.pu8Qy = Qy; KeyObj.data.EcdsaPubKey.u8DomainParamsGroup = (VLT_U8)enDeviceKeyGroup; KeyObj.data.EcdsaPubKey.u8DomainParamsIndex = (VLT_U8)enDomainParamsKeyIndex; KeyObj.data.EcdsaPubKey.u8Assurance = 0; returnValue = m_theBaseApi->VltPutKey((VLT_U8)enHostKeyGroup, (VLT_U8)enPublicKeyIndex, &KeyPrivileges, &KeyObj); if (returnValue != VLT_OK) { return KEY_GENERATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Generating device private and public key pair..."); VLT_KEY_GEN_DATA keyGeneratorData; keyGeneratorData.u8AlgoID = VLT_ALG_KPG_ECDSA_GF2M; keyGeneratorData.EcdsaKeyGenObj.u8DomainParamsGroup = enDeviceKeyGroup; keyGeneratorData.EcdsaKeyGenObj.u8DomainParamsIndex = enDomainParamsKeyIndex; returnValue = m_theBaseApi->VltGenerateKeyPair((VLT_U8)enDeviceKeyGroup, (VLT_U8)enPublicKeyIndex, (VLT_U8)enDeviceKeyGroup, (VLT_U8)enPrivateKeyIndex, &keyGeneratorData); if (returnValue != VLT_OK) { return KEY_GENERATION_FAILED; } return IDTLIB_SUCCESS; } int VaultIC100Adapter::SetCounter(unsigned int uiCouterValue) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Reset counter value to " << uiCouterValue << "..."); unsigned char ucCounterMode = VLT_DIRECT_MODE; returnValue = m_theBaseApi->VltSetConfig( VLT_COUNTER_MODE_PARAM, VLT_COUNTER_MODE_SZ, &ucCounterMode); if (returnValue != VLT_OK) { return COUNTER_SET_FAILED; } returnValue = m_theBaseApi->VltSetSecureCounters(COUNTER_NUMBER, COUNTER_GROUP, sizeof(uiCouterValue), (VLT_PU8)(&uiCouterValue)); if (returnValue != VLT_OK) { return COUNTER_SET_FAILED; } ucCounterMode = VLT_COUNTER_MODE; returnValue = m_theBaseApi->VltSetConfig( VLT_COUNTER_MODE_PARAM, VLT_COUNTER_MODE_SZ, &ucCounterMode); if (returnValue != VLT_OK) { return COUNTER_SET_FAILED; } return IDTLIB_SUCCESS; } int VaultIC100Adapter::GenerateCertificate(const unsigned char *aucMaterialInfo, unsigned short usMaterialInfoLength, const unsigned char *aucPrvKS, unsigned char *aucCertificate, unsigned short *usCertificateLength) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Reading device public key..."); unsigned char aucQx[KEY_COEFF_SIZE]; unsigned char aucQy[KEY_COEFF_SIZE]; VLT_KEY_OBJECT read_key; read_key.u8KeyID = VLT_KEY_ECDSA_GF2M_PUB; read_key.data.EcdsaPubKey.u16QLen = KEY_COEFF_SIZE; read_key.data.EcdsaPubKey.pu8Qx = aucQx; read_key.data.EcdsaPubKey.pu8Qy = aucQy; returnValue = m_theBaseApi->VltReadKey((VLT_U8)enDeviceKeyGroup, (VLT_U8)enPublicKeyIndex,&read_key); if (returnValue != VLT_OK) { return KEY_GENERATION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Generating certificate file..."); try { IDTagAdapter::GenerateCertificate(aucMaterialInfo, usMaterialInfoLength, read_key.data.EcdsaPubKey.pu8Qx, read_key.data.EcdsaPubKey.pu8Qy, aucPrvKS, aucCertificate, usCertificateLength); } catch (exception& e) { LOG_EXT(LEVEL_ERROR, "Exception caught: " << e.what() << "."); return INVALID_HOST_KEY; } return IDTLIB_SUCCESS; } int VaultIC100Adapter::WriteCertificate(unsigned char *aucCertificate, unsigned short usCertificateLength) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Writing certificate file..."); VLT_SELECT respData; returnValue = m_theBaseApi->VltSelectFile((const VLT_U8*)CERTIFICATE_PATH, (VLT_U8)strlen(CERTIFICATE_PATH), &respData); if (returnValue != VLT_OK) { return CERTIFICATE_WRITE_FAILED; } unsigned short offset = 0; while (offset < usCertificateLength) { VLT_U8 dataLength = (VLT_U8)min((VLT_U16)(usCertificateLength - offset), (VLT_U16)VLT_MAX_APDU_SND_DATA_SZ); returnValue = m_theBaseApi->VltWriteFile(aucCertificate + offset, dataLength); if (returnValue != VLT_OK) { if (returnValue == VLT_EOF || returnValue == 0x9001) { // reached end of file break; } return CERTIFICATE_WRITE_FAILED; } offset += dataLength; } m_theBaseApi->VltSeekFile(0); return IDTLIB_SUCCESS; } int VaultIC100Adapter::Logout() { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } int returnValue; LOG_EXT(LEVEL_DEBUG, "Setting operational mode..."); returnValue = m_theBaseApi->VltSetStatus(VLT_OPERATIONAL_ACTIVE); if (returnValue != VLT_OK) { return TRANSITION_FAILED; } LOG_EXT(LEVEL_DEBUG, "Logging out as manufacturer..."); returnValue = m_theBaseApi->VltCancelAuthentication(); if (returnValue != VLT_OK) { return LOGIN_FAILED; } return IDTLIB_SUCCESS; } #endif /// <summary> /// Reads certificate file. /// </summary> /// <param name="ucCartridgeNum">The cartridge number.</param> /// <param name="aucCertificate">The certificate (output parameter).</param> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::ReadIDCertificate(unsigned char *aucCertificate) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } VLT_SELECT respData; LOG_EXT(LEVEL_DEBUG, "Reading certificate file..."); int returnValue = m_theBaseApi->VltSelectFile((const VLT_U8*)CERTIFICATE_PATH, (VLT_U8)strlen(CERTIFICATE_PATH), &respData); if (returnValue != VLT_OK) { return returnValue; } unsigned short offset = 0; while (offset < CERTIFICATE_SIZE) { VLT_U16 readLength = min(VLT_MAX_APDU_RCV_DATA_SZ, (VLT_U16)(CERTIFICATE_SIZE - offset)); returnValue = m_theBaseApi->VltReadFile(&readLength, (VLT_PU8)aucCertificate + offset); if (returnValue != VLT_OK) { if (returnValue == VLT_EOF || returnValue == 0x9001) { // reached end of file break; } return returnValue; } offset += readLength; } return IDTLIB_SUCCESS; } bool VaultIC100Adapter::IsCertificateEmpty(const unsigned char *aucCertificate) { if (aucCertificate == NULL) { return true; } int i; unsigned char emptyFileIndicator = aucCertificate[0]; for (i = 0; i < CERTIFICATE_SIZE - 12; i++) { if (aucCertificate[i] != emptyFileIndicator) { return false; } } for (; i< CERTIFICATE_SIZE; i++) { if (aucCertificate[i] != 0) { return false; } } return true; } /// <summary> /// Sends challenge to be signed by device. /// </summary> /// <param name="ucCartridgeNum">The cartridge number.</param> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::ChallengeHostDevice(unsigned char ucCartridgeNum, const unsigned char *aucHostChallenge, unsigned short usHostChallengeLength, unsigned char *aucDeviceChallenge, unsigned short *pusDeviceChallengeLength, unsigned char *aucSignedDeviceChallenge, unsigned short *pusSignedDeviceChallengeLength) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } LOG_EXT(LEVEL_DEBUG, "Perform internal authentication..."); int returnValue = m_theBaseApi->VltInternalAuthenticate(VLT_USER, VLT_APPROVED_USER, (VLT_U8)usHostChallengeLength, aucHostChallenge, aucDeviceChallenge, pusSignedDeviceChallengeLength, aucSignedDeviceChallenge); if (returnValue != VLT_OK) { return returnValue; } unsigned short offset = VLT_INTERNAL_AUTH_DEV_CHALLENGE_LENGTH; memcpy(aucDeviceChallenge + offset, aucHostChallenge, usHostChallengeLength); offset += usHostChallengeLength; memcpy(aucDeviceChallenge + offset, aucHostID, sizeof(aucHostID)); offset += sizeof(aucHostID); *pusDeviceChallengeLength = offset; return IDTLIB_SUCCESS; } /// <summary> /// Gets the current volume of a cartridge. /// </summary> /// <param name="ucCartridgeNum">The cartridge number.</param> /// <param name="puiCurrentVolume">The cartridge current volume (output parameter).</param> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::GetCurrentVolume(unsigned char ucCartridgeNum, unsigned int *puiCurrentVolume) { CounterResponse signedVolume; int returnValue = DecreaseConsumption(ucCartridgeNum, 0, &signedVolume); *puiCurrentVolume = signedVolume.GetCounterValue(); return returnValue; } /// <summary> /// Decreases consumption from cartridge current volume. /// </summary> /// <param name="ucCartridgeNum">The cartridge number.</param> /// <param name="uiConsumption">The volume consumption.</param> /// <param name="newSignedVolume">The cartridge new volume and its signature by PrvKC (output parameter).</param> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::DecreaseConsumption(unsigned char ucCartridgeNum, unsigned int uiConsumption, CounterResponse *newSignedVolume) { if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } LOG_EXT(LEVEL_DEBUG, "Generate random bytes for nounce..."); VLT_COUNTER_DATA counterData; int returnValue = m_theBaseApi->VltGenerateRandom(VLT_NOUNCE_LENGTH, counterData.nounce.u8Nounce); if (returnValue != VLT_OK) { return GENERATE_RANDOM_FAILED; } LOG_EXT(LEVEL_DEBUG, "Decrementing counter by " << uiConsumption << "..."); counterData.amount.u8AmountLength = VLT_COUNTER_LENGTH; memcpy(counterData.amount.u8Amount, &uiConsumption, sizeof(unsigned int)); counterData.nounce.u8NounceLength = VLT_NOUNCE_LENGTH; unsigned char signature[SIGNATURE_SIZE]; VLT_COUNTER_RESPONSE counterResponse; counterResponse.pu8Signature = signature; counterResponse.u16SignatureLength = SIGNATURE_SIZE; returnValue = m_theBaseApi->VltDecrementCounter(COUNTER_NUMBER, COUNTER_GROUP, &counterData, &counterResponse); if (returnValue != VLT_OK) { if (returnValue == 0x6A80) { return MATERIAL_OVERCONSUMPTION; } return returnValue; } newSignedVolume->SetCounterValue(counterResponse.u8CntValue); newSignedVolume->SetMessage(counterResponse.u8Rnd, m_cartridgeInfo->au8Serial, counterData.nounce.u8Nounce); newSignedVolume->SetSignature(counterResponse.pu8Signature, counterResponse.u16SignatureLength); return IDTLIB_SUCCESS; } int VaultIC100Adapter::GetInPlaceStatus(int *pStatus) { if (m_bUseUsb) { if (!m_bIsInitialized) { return FCB_GET_IN_PLACE_STATUS_FAILED; } *pStatus = 1; return IDTLIB_SUCCESS; } return IDTagAdapter::GetInPlaceStatus(pStatus); } /// <summary> /// Gets the serial numbe of a cartridge. /// </summary> /// <param name="ucCartridgeNum">The cartridge number.</param> /// <param name="ucSerialNumberLength">The cartridge serial number (output parameter).</param> /// <returns>0 on success, non-zero for failures.</returns> int VaultIC100Adapter::GetSerialNumber(unsigned char *aucSerialNumber, unsigned char *ucSerialNumberLength) { if (m_cartridgeInfo == NULL) { return 1; } memcpy(aucSerialNumber, m_cartridgeInfo->au8Serial, VLT_CHIP_SERIAL_NUMBER_LENGTH); *ucSerialNumberLength = VLT_CHIP_SERIAL_NUMBER_LENGTH; return IDTLIB_SUCCESS; } int VaultIC100Adapter::SwitchToCartridge(unsigned char ucCartridgeNum) { int returnValue; if (!m_bIsInitialized) { returnValue = InitLibrary(ucCartridgeNum, 0); if (returnValue != IDTLIB_SUCCESS) { return returnValue; } } if (m_theBaseApi == NULL) { return HW_NOT_INITIALIZED; } returnValue = IDTagAdapter::SwitchToCartridge(ucCartridgeNum); if (returnValue != IDTLIB_SUCCESS) { return returnValue; } returnValue = m_theBaseApi->VltGetInfo(m_cartridgeInfo); if (returnValue != VLT_OK) { return returnValue; } return IDTLIB_SUCCESS; } }
ebf65cda2e64768053d1bcc385b2b69911556ad0
f3a3ab4d9cb33d962175fb574bc4804007ba0e3a
/Germany.cpp
c3f720c869123d35c9dc53916fd75f589e542cf9
[]
no_license
jcostello93/162_Final
0888b0c67e7d69d946736ed64f8add727f95f38d
ee91cea5ba8858dd08b9884939d3c90d999248b2
refs/heads/master
2020-12-03T03:55:00.299306
2017-06-29T15:00:51
2017-06-29T15:00:51
95,787,854
0
0
null
null
null
null
UTF-8
C++
false
false
5,073
cpp
Germany.cpp
#include "Germany.hpp" /***************************************************************** * default constructor * The default constructor initializes the name to the country and the * checkpoint variables to false. ******************************************************************/ Germany::Germany() { name = "Germany"; optionA = optionB = optionC = beer = false; } Germany::~Germany() { } /*************************************************************** * explore() * This is a virtual function from Country. It takes the player * through the city and send him to the next country. ***************************************************************/ void Germany::explore(Player *p) { cout << "\nAhhh Munich ... I had a great time here." << endl; cout << "...but I cant really remember the city. " << endl; char c = menu1(); while (moveOn == false) { if (beer == true) { if (c == 'a') { cout << "\nOk, starting to remember now. " << endl; cout << "\nWell, it's beautiful, but I don't see my laptop. " << endl; cout << "\nHey, this promotion gives me a free bus rise to Prague. Cool!" << endl; cout << "\na. Add promotion to inventory. " << endl; cout << "b. Leave it. " << endl; InputValidation i; char z = i.getChar2ab(); if (z == 'a' || z == 'A') { p->checkSize("Ticket to Prague"); p->setBusTicket(true); } if (z == 'b' || z == 'B') { cout << "Well, I can only carry so much anyway." << endl; } optionA = true; } if (c == 'b') { cout << "\nI should hold back. Got a long journey ahead of me. " << endl; } if (c == 'c') { hostel(p); optionC = true; } } if (beer == false) { if (c == 'a') { cout << "\nNope, don't remember any of this. " << endl; } if (c == 'b') { cout << "\nAhh, I love this Augistiner Beer. " << endl; cout << "\nYou know... I'm starting to recognize these streets. " << endl; optionB = true; beer = true; } if (c == 'c') { cout << "\nNot sure where the hostel is..." << endl; } } if (optionA == true && optionB == true && optionC == true && beer == true) { moveOn = true; } if (p->getMoney() <= 0) { return; } if (moveOn == false) { c = menu1(); } } moveOn = false; c = menu2(p); if (c == 'a' || c == 'A') { p->setCountry(west->getName()); cout << "To " << p->getCountry() << "?" << endl; cout << "That'll be $20. " << endl; p->withdraw(20); } if (c == 'b' || c == 'B') { p->setCountry(south->getName()); cout << "To " << p->getCountry() << "?" << endl; cout << "That'll be $20. " << endl; p->withdraw(20); } if (c == 'c' || c == 'C') { p->setCountry(east->getName()); cout << "To " << p->getCountry() << "?" << endl; if (p->getBusTicket() == false) { cout << "That'll be $25. " << endl; p->withdraw(25); } else { cout << "Cool, free ride!" << endl; p->removeItem("Ticket to Prague"); } } } /*************************************************************** * hostel() * This is a virtual function from Country. It simulates * a conversation with a hostel employee. ***************************************************************/ void Germany::hostel(Player *p) { InputValidation i; cout << "\nEmployee: Hi. " << endl; cout << "\na. Hi, I've lost my laptop. Can you please check if it's here?" << endl; i.getChar1(); cout << "\nEmployee: Ehh. What's in it for me?" << endl; cout << "\na.Well, here's what I have" << endl; char c = i.getChar1(); cout << "Inventory: " << endl; p->printInventory(); cout << "\nThat's nice, but I'll settle for $100. " << endl; cout << "\na. Ok, fine. "; cout << "\nb. You're asking money just to check? Get lost." << endl; c = i.getChar2ab(); if (c == 'a') { p->withdraw(100); cout << "\nSorry, nothing there. " << endl; } } /*************************************************************** * menu1() * The first menu is for things to do in the city. ***************************************************************/ char Germany::menu1() { cout << "\nWhat did I do here, again?" << endl; cout << "\na. Go to the Frauenkirche. " << endl; cout << "\nb. Go to the Hofbraeuhaus. " << endl; cout << "\nc. Go to the hostel. " << endl; InputValidation i; char c = i.getChar3(); return c; } /*************************************************************** * menu2() * The second menu is for selecting the next country. ***************************************************************/ char Germany::menu2(Player* p) { cout << "\nWell that was frustrating. At least the beer was good. " << endl; if (p->getBusTicket()) { cout << "\nAnd I've got a free bus ticket from Munich to Prague!" << endl; } cout << "\nSo, where will it be?" << endl; cout << "\na. Switzerland." << endl; cout << "b. Austria. " << endl; cout << "c. Czech Republic. " << endl; InputValidation i; char c = i.getChar3(); return c; }
113504dc131b3af5b4b0222338195cba3e7abb76
167daf99f3f246bd397244d1ae53a5b01c31da87
/AtCoder/ABC178/C1.cpp
72c8b9daa5dfbd36abef2b60716df1739f6a5f1f
[]
no_license
richardjcy1/CP
24e591eb9b4c74ba741864ffc14f70f87b1e2917
1ca523c33738caf1632b814314556d1d5d2879f1
refs/heads/main
2023-04-11T13:20:47.414133
2021-03-20T22:56:33
2021-03-20T22:56:33
308,985,668
0
0
null
2021-03-20T22:56:34
2020-10-31T22:51:38
null
UTF-8
C++
false
false
614
cpp
C1.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; ll power(ll a, ll n, ll p) { a %= p; ll res = 1; while (n) { if (n & 1) { res *= a; res %= p; } a = (a * a) % p; n >>= 1; } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; ll ans = power(10, n, mod) - 2 * power(9, n, mod) % mod; ans = (ans + mod) % mod; ans += power(8, n, mod); ans %= mod; cout << ans << endl; return 0; }
5a3725b5d3c04ea4bb1072d88093acb5ebd0d324
abd788d721384699cec9c4fe785752c4c8b1f9c1
/Demo004/Demo004/DlgSelect/DlgSelect.h
99199eefbce6ca78a4e39ae55e61acf45fcdb215
[]
no_license
liuyuwang2016/My-Qt-Projects
8b5ae943c2e09ada082b0e6c46ba51cfff735ba2
13fd36bcb2238650051a057b4d0e61b4c111ad8f
refs/heads/master
2020-03-06T17:32:26.224345
2018-06-25T14:00:56
2018-06-25T14:00:56
126,991,657
0
0
null
null
null
null
GB18030
C++
false
false
708
h
DlgSelect.h
#ifndef DLGSELECT_H #define DLGSELECT_H #include <QDialog> #include "ui_DlgSelect.h" class DlgSelect : public QDialog { Q_OBJECT public: DlgSelect(QStringList* numbers, QWidget *parent = 0); ~DlgSelect(); //定时器 virtual void timerEvent(QTimerEvent* event); //窗口被关闭 virtual void closeEvent(QCloseEvent* event); private slots: int onSelectNext(); private: int saveResults(); private: Ui::DlgSelect ui; QIcon m_iconStart, m_iconStop; QStringList* m_numbers; int m_timerId; bool m_working;//正在抽奖 int m_now;//当前显示 int* m_flags;//不重复抽取 int m_total;//能够被抽取的总个数 int m_selected;//已经被抽取的个数 }; #endif // DLGSELECT_H
ed6a1ac6eb1b11a247845c4d2fc2e5087787fee4
9964db8a800baf9f6096b56e41292a4a8ffaeda8
/opencl_gpu_codes/particleF_laneD/3_rng+2/src/robot.cpp
d40320e19b6672b7539a2931ed93f335735c1fc1
[]
no_license
nikmad/dless_tech
7c6f7acf80b0b673e5e1122479ebf9a4cc2ae249
dc9444aab5de8a2e0f139c1c47bc991eb021fabc
refs/heads/master
2021-01-18T23:59:03.868284
2016-11-06T08:41:01
2016-11-06T08:41:01
72,837,079
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
robot.cpp
// (C) 2013, Nikhil Madduri, <nikhil.madduri@stud-mail.uni-wuerzburg.de> #include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include "RNG.h" #include "robot.h" using namespace std; using namespace Eigen; void move_line(linestruct *line, noiseStruct *noise, float turnAngle, float moveDistance, int imgrows, int imgcols) { RNG rng(time(NULL)); line->theta = line->theta + turnAngle + rng.gaussian(noise->turnNoise); line->theta = cyclicWorld(line->theta, PI); moveDistance = moveDistance + rng.gaussian(noise->forwardNoise); float xincept = line->x[0]+moveDistance; float r=0.0; for(int l=0; l<imgrows; l++) { line->y[l] = l; r = line->y[l]/sin(line->theta); line->x[l] = abs((int)(xincept + r * (cos(line->theta)))); line->x[l] = cyclicWorld(line->x[l], imgcols); } } float cyclicWorld(float a, float b) { if (a>=0) return a-b*(int)(a/b); else return a+b*(1+(int)(abs(a/b))); } float gaussian(float mu, float sigma, float x) { return (1/sqrt(2.*PI*pow(sigma,2)))*exp(-0.5*pow((x-mu),2)/pow(sigma,2)); }
19cf469ef7eca2c3ecc3b1e7ac5524cc05033485
5c734be19e15b3f7871a68073cd5a2eddc891e96
/Yim/30. Shortest Path Algorithm/PROMISES.cpp
0cced402921250e48658b8f8dc5b2b370e82611e
[]
no_license
vinus322/Algorithm-study
3af98e36b90aafab3ae3ae707f4dfc10580cea16
bf4e98682d86edfd375e719fb26e401c26d156d6
refs/heads/master
2022-11-17T04:13:47.295832
2020-07-12T14:04:26
2020-07-12T14:04:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,410
cpp
PROMISES.cpp
/* * Date : 2020.07.12 * Language : C++ * Complexity : O(V^3 + N*V^2) * Data Structure : * Algorithm : Floyd * * Problem : https://www.algospot.com/judge/problem/read/PROMISES */ #include <stdio.h> #include <algorithm> #include <iostream> #define INF 1e9 using namespace std; int V, N, M; long long adj[201][201]; bool update(int a, int b, int c) { if (adj[a][b] <= c) return false; for (int x = 0; x < V; ++x) { for (int y = 0; y < V; ++y) { adj[x][y] = min(adj[x][y], min(adj[x][a] + c + adj[b][y], adj[x][b] + c + adj[a][y])); } } return true; } int main() { int tc; int a, b, c; int ret; scanf("%d", &tc); while (tc--) { ret = 0; scanf("%d %d %d", &V, &M, &N); for (int i = 0; i < V; ++i) for (int j = 0; j < V; ++j) { if (i == j) adj[i][i] = 0; else adj[i][j] = INF; } for (int i = 0; i < M; ++i) { scanf("%d %d %d", &a, &b, &c); if (adj[a][b] == INF || (adj[a][b] !=INF && adj[a][b] > c)) adj[a][b] = adj[b][a] = c; } for (int k = 0; k < V; ++k) { for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]); } } } for (int i = 0; i < N; ++i) { scanf("%d %d %d", &a, &b, &c); if (!update(a, b, c)) { ret++; } } printf("%d\n", ret); } return 0; }
d28760b9fbf3d552cd504e0e039c46712102f482
2922f5512a4741f1cc084a0857704fa2c88fcce9
/engqtest/plotter_code/cubic.cpp
d8b9af0a61236e8c7b2d6632bfec050100c29623
[]
no_license
RickKoenig/engq
3544a7c01ff6b05c732a19607ee5424e0086e7f3
87ea08727bc0aea508221f0210e1f8f52ef066b9
refs/heads/master
2023-07-26T06:35:31.377976
2022-04-05T05:52:53
2022-04-05T05:52:53
242,048,482
0
0
null
null
null
null
UTF-8
C++
false
false
4,755
cpp
cubic.cpp
#define CUBIC #ifdef CUBIC #define MAXROOTS 5 #define MAXPERMS 120 // roots and symmetry pointf2 roots[5] = { {.25f,0}, {2.25f,0}, {.5f,0}, {.75f,0}, {.95f,0} }; pointf2 res[MAXROOTS][MAXPERMS]; pointf2 respow[MAXROOTS][MAXPERMS]; float rootsep = .02f; S32 permnum = -1; S32 resnum = -1; S32 drawpow = 1; S32 nroots = 3; S32 nperms; S32 resp = 3; // a power of resolvents S32 drawroots = 1; S32 drawres = 1; U32 ffact(U32 n) { U32 i; U32 p = 1; for (i=2;i<=n;++i) p *= i; return p; } void calccubic() { nroots = range(0,nroots,MAXROOTS); nperms = ffact(nroots); complex w[MAXROOTS]; S32 i,j,k; for (i=0;i<nroots;++i) { w[i] = complex(cosf(i*TWOPI/nroots),sinf(i*TWOPI/nroots)); } // complex w0 = 1; // complex w1(-.5f,sqrtf(3.0f)*.5f); // complex w2 = w1.conjugate(); // static bool once; // if (!once) { // roots[0] = w0; // roots[1] = w1; // roots[2] = w2; // once = true; // } S32 perm[MAXROOTS]; for (i=0;i<nroots;++i) perm[i] = i; j = 0; do { for (k=0;k<nroots;++k) { complex sum = 0; for (i=0;i<nroots;++i) { sum = sum + w[(i*k)%nroots]*roots[perm[i]]; } res[k][j] = sum; } ++j; } while (next_permutation(perm,perm+nroots)); /* // e res[0][0] = (complex)roots[0] + roots[1] + roots[2]; res[1][0] = (complex)roots[0] + w1*roots[1] + w2*roots[2]; res[2][0] = (complex)roots[0] + w2*roots[1] + w1*roots[2]; // ab res[0][1] = (complex)roots[1] + roots[0] + roots[2]; res[1][1] = (complex)roots[1] + w1*roots[0] + w2*roots[2]; res[2][1] = (complex)roots[1] + w2*roots[0] + w1*roots[2]; // ac res[0][2] = (complex)roots[2] + roots[1] + roots[0]; res[1][2] = (complex)roots[2] + w1*roots[1] + w2*roots[0]; res[2][2] = (complex)roots[2] + w2*roots[1] + w1*roots[0]; // bc res[0][3] = (complex)roots[0] + roots[2] + roots[1]; res[1][3] = (complex)roots[0] + w1*roots[2] + w2*roots[1]; res[2][3] = (complex)roots[0] + w2*roots[2] + w1*roots[1]; // abc res[0][4] = (complex)roots[1] + roots[2] + roots[0]; res[1][4] = (complex)roots[1] + w1*roots[2] + w2*roots[0]; res[2][4] = (complex)roots[1] + w2*roots[2] + w1*roots[0]; // acb res[0][5] = (complex)roots[2] + roots[0] + roots[1]; res[1][5] = (complex)roots[2] + w1*roots[0] + w2*roots[1]; res[2][5] = (complex)roots[2] + w2*roots[0] + w1*roots[1]; */ for (i=0;i<nperms;++i) { for (j=0;j<nroots;++j) { complex p = 1; for (k=0;k<resp;++k) p = p * (complex)res[j][i]; respow[j][i] = p; } } } void drawcubic() { #define NCOLORS 6 C32 colors[NCOLORS]={C32(255,205,155),C32LIGHTRED,C32LIGHTGREEN,C32LIGHTBLUE,C32LIGHTCYAN,C32LIGHTMAGENTA}; pointf2x zerop; S32 i; if (drawroots) for (i=0;i<nroots;++i) { drawflinec(roots[i],zerop,C32DARKGRAY); } for (i=0;i<nperms;++i) { // if (permnum>=0 && permnum!=i) // continue; C32 c1,c2,c3; c1 = c2 = c3 = colors[i%NCOLORS]; c1.r /= 2; c1.g /= 2; c1.b /= 2; c2.r /= 4; c2.g /= 4; c2.b /= 4; c2.r *= 3; c2.g *= 3; c2.b *= 3; float rs = permnum>=0 ? 0 : rootsep; S32 j; for (j=0;j<nroots;++j) { if (resnum<0 || resnum==j) { if (permnum<0 || permnum==i) { if (/*j>0 && */drawpow) drawflinec(pointf2x(respow[j][i].x+rs*i,respow[j][i].y+rs*i),zerop,c3); if (drawres) drawflinec(pointf2x(res[j][i].x+rs*i,res[j][i].y+rs*i),zerop,c3); } } } } drawfpoint(pointf2(),C32WHITE); #if 0 const float MAXXY=20; const S32 NSEG=300; // draw points S32 i; for (i=0;i<MAXPNTS;++i) { drawfpoint(pnts[i],C32BLACK); pointi2 pi; // pi=math2screen(pnts[i]); // outtextxybf32(B32,pi.x-8,pi.y+10,C32BLACK,C32YELLOW,"P%c",'A'+i); } // draw line from pa to pb /* pointf2 p0,p1; const float enlarge=1.5f; const float diff=(pnts[1].x-pnts[0].x)*.5f; const float sum= (pnts[1].x+pnts[0].x)*.5f; p0.x=-diff*enlarge+sum; p1.x=diff*enlarge+sum; p0.y=linm*p0.x+linb; p1.y=linm*p1.x+linb; drawfline(p0,p1,C32BLACK);*/ drawfline(pnts[0],pnts[1],C32BLACK); #endif // drawfunction(sinfun); // drawfunction(expe); // drawfunction(exp10); // drawfunction(exp10le); // drawfunction(root3_0); // drawfunction(root3_1); // drawfunction(root3_2); // drawfunction(xs); // drawfunction(beercan); // drawfunction(quintic); // drawfunction(seventh); // drawfunction(sinf); // drawfunction2(circ); // drawfunctionrk2d(objstate,offsets,2,initf,changef); // drawfunction(tant); #if 0 drawfline(pointf2x(0.0f,0.0f),pointf2x(v1start,0.0f),C32RED); drawfline(pointf2x(v1start,0.0f),pointf2x(v1start,v1*vscale),C32RED); drawfline(pointf2x(v1start,v1*vscale),pointf2x(v1end,v1*vscale),C32RED); drawfline(pointf2x(v1end,v1*vscale),pointf2x(v1end,0.0f),C32RED); drawfline(pointf2x(v1end,0.0f),pointf2x(1.0f,0.0f),C32RED); drawfunctionrk2d(objstate,offsets,3,initfs,changefs); #endif } #endif
8199b159c2d7624af212a08e17b00badb0e4587c
0c28e7d86bd3fd920149301117a74221ae3a6a4f
/17130130312-曹晨瑶-OOP第1次实验成果/source_1_3/test.cpp
486f566e77af6fa09e4e14add5985973c5b091ce
[]
no_license
CCYmowang/c-
2f13b219571f73da68766b840843b229bd004059
a15e1e929b7c702b5afcba8b0ba95140351bcbe9
refs/heads/master
2021-01-04T08:11:30.614105
2020-02-14T11:14:38
2020-02-14T11:14:38
240,458,737
0
0
null
null
null
null
GB18030
C++
false
false
759
cpp
test.cpp
#include"test.h" #include<iostream> using namespace std; void itoa(int n,char* str) { if(n==-2147483648){//异常处理 //cout<<""; char *p="-2147483648"; char *pp=str; while(*p!='\0') { *pp=*p; pp++; p++; } *pp='\0'; //cout<<str; return ; } char *p=str; if(n<0) { n=0-n; *p='-'; p++; }//将负数转化为整数 int stack[50];//堆栈数组 int top=0;//栈顶指针 while(n){//中间过程 stack[top]=n%10; n=n/10; top++; } top--; while(top!=-1){ *p=stack[top]+'0';//转化 //cout<<*str; p++; top--; } *p='\0'; }
4d2bd9b56b1cc8625b5c301d0f69093a1a20f04b
5dc725a83c3bf0dccb9fd6db73e30ca6e0cf8499
/ex7/ex7.cpp
f1986aae2fe899c75a2d96dbcff6cb1511c12e8d
[]
no_license
Zhenghao-Liu/Lab_report_of_data_structure
7f1a29819fc4d68ae7c42428941f8c6116c7c5b5
a78b1afb920b1c9e92635435a6cfe6cd175e9dc4
refs/heads/master
2021-06-14T02:57:45.942550
2021-02-15T12:44:14
2021-02-15T12:44:14
150,260,450
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
ex7.cpp
//#include "pch.h" #include <iostream> using namespace std; void quick_sort(int samples[], int low, int high); int main() { cout << "Please input the number of samples : "; int number_of_samples; cin >> number_of_samples; if (number_of_samples < 0) return -1; cout << "Please input the samples : "; int *samples = new int[number_of_samples + 1]; samples[0] = number_of_samples; for (int i = 0; i < number_of_samples; ++i) cin >> samples[i + 1]; cout << "---------------------" << endl << "original sample sequence : "; for (int i = 0; i < number_of_samples; ++i) cout << samples[i + 1] << " "; quick_sort(samples, 1, number_of_samples); cout << endl << "final quick sort result : "; for (int i = 0; i < number_of_samples; ++i) cout << samples[i + 1] << " "; delete[] samples; return 0; } int QUICK_SORT_TIMES = 0;//为了输出第一次快速排序结果而设置 void quick_sort(int samples[], int low, int high) { if (low >= high) return; int pivotkey = samples[low], empty_location = low, left = low, right = high; ++QUICK_SORT_TIMES; while (low < high) { for (; high > low; --high) if (samples[high] < pivotkey) { samples[empty_location] = samples[high]; empty_location = high; ++low; break; } for (; high > low; ++low) if (samples[low] > pivotkey) { samples[empty_location] = samples[low]; empty_location = low; --high; break; } } samples[empty_location] = pivotkey; if (1 == QUICK_SORT_TIMES) { cout << endl << "the first quick sort result : "; for (int i = 0; i < samples[0]; ++i) cout << samples[i + 1] << " "; } quick_sort(samples, left, empty_location - 1); quick_sort(samples, empty_location + 1, right); }
80f5b4f6989806007ba1f2b4067401ab8bbd5d8d
d21c3427800f8dd1fcbf34cd2768a65fdcae3a27
/code/cytosim/src/sim/trapper_prop.h
2e9443d1835fac086c348400c4ebc3b89f5b2cb0
[]
no_license
manulera/LeraRamirez2019
b4e5637b76b988e3ae32177e7e894f85f9b6e109
bc42559d500d6e3270d1e8ab0e033a9e980b5e48
refs/heads/master
2023-02-12T22:56:05.410164
2021-01-13T10:10:24
2021-01-13T10:10:24
329,267,089
0
0
null
null
null
null
UTF-8
C++
false
false
2,414
h
trapper_prop.h
// Cytosim was created by Francois Nedelec. Copyright 2007-2017 EMBL. #ifndef trapper_prop_H #define trapper_prop_H #include "couple_prop.h" #include "trapper.h" /// Additional Property for Trapper /** @ingroup Properties */ class TrapperProp : public CoupleProp { friend class Trapper; friend class TrapperLong; public: /// The target property std::string target_prop_name; HandProp * target_prop; /// The lattice on which the target single moves got from the properties unsigned int target_lat; /// Rate of trapping singles when they are attached to the microtubule real trapping_rate; /// Rate of untrapping real untrapping_rate; /// Force of the bond between couple and single real untrapping_force; /// Integer indicating whether the single is attached to the hand on the same filament (0), on the other filament (1), or in the center (2) bool trap_other_filament; /// The trapping rate from solution to any trapper (regardless of its binding stage) real trapping_rate_solution; private: real trapping_rate_dt; real untrapping_rate_dt; real inv_untrapping_force; /// In this version of the trapper, the trapper stiffness corresponds to the weight of the linker for the TriLink when all three heads are connected. In the current situation, where we connect the three hands to a central dragless point with linkers of equal stiffness. If only two hands are connected (like in a normal couple), stiffness should be the one given by CoupleProp->stiffness, therefore, the stiffness of the linker when the three elements are connected is CoupleProp->stiffness*2/3 real trap_stiffness; real trapping_rate_solution_dt; public: /// constructor TrapperProp(const std::string& n) : CoupleProp(n) { clear(); } /// destructor ~TrapperProp() { } /// return a Trapper with this property Couple * newCouple(Glossary*) const; /// set default values void clear(); /// set from a Glossary void read(Glossary&); /// compute values derived from the parameters void complete(Simul const*); /// return a carbon copy of object Property* clone() const { return new TrapperProp(*this); } /// write all values void write_values(std::ostream &) const; }; #endif
702694d1e7c2c3011d17477b759d0dc207acafc2
679cc9a70ddf33e74244221a355ad837b8d6df1d
/kpix/KpixCalibRead.h
f527b8aa706d1bc6786ee2fdf7d6f04c6b51ab03
[]
no_license
Lycoris2017/KPiX-Lycoris
3d23c44a3bb3c76c6b2ffd46c45d7a48a9e9f928
745d8d942c0fdbe3e33aaf119bec9f488f0e1ab5
refs/heads/kpix.master
2021-07-01T05:44:28.308236
2019-06-20T14:04:03
2019-06-20T14:04:03
113,307,104
0
1
null
2018-02-06T12:55:30
2017-12-06T11:21:15
C++
UTF-8
C++
false
false
5,488
h
KpixCalibRead.h
//----------------------------------------------------------------------------- // File : KpixCalibRead.h // Author : Ryan Herbst <rherbst@slac.stanford.edu> // Created : 05/31/2012 // Project : KPIX Control Software //----------------------------------------------------------------------------- // Description : // This class is used to extract calibration constants from an XML file. //----------------------------------------------------------------------------- // Copyright (c) 2012 by SLAC. All rights reserved. // Proprietary and confidential to SLAC. //----------------------------------------------------------------------------- // Modification history : // 05/31/2012: created //----------------------------------------------------------------------------- #ifndef __KPIX_CALIB_READ_H__ #define __KPIX_CALIB_READ_H__ #include <string> #include <map> #include <sys/types.h> #include <libxml/tree.h> using namespace std; #ifdef __CINT__ #define uint unsigned int #endif //! Class used to parse and read calibration run data. class KpixCalibRead { // Class for channel data class KpixCalibData { public: // values double baseMean; double baseRms; double baseFitMean; double baseFitSigma; double baseFitMeanErr; double baseFitSigmaErr; double baseFitChisquare; double calibGain; double calibIntercept; double calibGainErr; double calibInterceptErr; double calibChisquare; double calibGainRms; string calibCrossTalk; uint badChannel; // Init KpixCalibData () { baseMean = 0; baseRms = 0; baseFitMean = 0; baseFitSigma = 0; baseFitMeanErr = 0; baseFitSigmaErr = 0; baseFitChisquare = 0; calibGain = 0; calibIntercept = 0; calibGainErr = 0; calibGainRms = 0; calibInterceptErr = 0; calibChisquare = 0; calibCrossTalk = ""; badChannel = 0; } }; // Structure for ASIC class KpixCalibAsic { public: KpixCalibData *data[1024][4][2]; KpixCalibAsic () { for (uint x=0; x < 1024; x++) for (uint y=0; y < 4; y++) { data[x][y][0] = new KpixCalibData; data[x][y][1] = new KpixCalibData; } } ~KpixCalibAsic () { for (uint x=0; x < 1024; x++) for (uint y=0; y < 4; y++) { delete data[x][y][0]; delete data[x][y][1]; } } }; // Vector of KPIXs map<string,KpixCalibAsic *> asicList_; // Parse XML level void parseXmlLevel ( xmlNode *node, string kpix, uint channel, uint bucket, uint range ); // Return pointer to ASIC, optional creation KpixCalibData *findKpix ( string kpix, uint channel, uint bucket, uint range, bool create ); public: //! Calib Data Class Constructor KpixCalibRead ( ); //! Calib Data Class DeConstructor ~KpixCalibRead ( ); //! Parse XML file bool parse ( string calibFile ); //! Get baseline mean value double baseMean ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline rms value double baseRms ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline guassian fit mean double baseFitMean ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline guassian fit sigma double baseFitSigma ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline guassian fit mean error double baseFitMeanErr ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline guassian fit sigma error double baseFitSigmaErr ( string kpix, uint channel, uint bucket, uint range ); //! Get baseline guassian fit chisquare double baseFitChisquare ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration gain double calibGain ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration intercept double calibIntercept ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration gain error double calibGainErr ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration gain rms double calibGainRms ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration intercept error double calibInterceptErr ( string kpix, uint channel, uint bucket, uint range ); //! Get calibration chisquare double calibChisquare ( string kpix, uint channel, uint bucket, uint range ); //! Get crosstalk string string calibCrossTalk ( string kpix, uint channel, uint bucket, uint range ); //! Get bad channel flag uint badChannel ( string kpix, uint channel ); //! Get calibration value by name double calibByName ( string kpix, uint channel, uint bucket, uint range, string name ); }; #endif
4cb157d48c77a5e025a278d10183fe9d1cdef95f
49f39fae1f10ad77a3c5e45e38dd6fd8266003b9
/uc/hal_arduino/example_driver.ino
8821f8da85eb7026b0fd5b581be4711f84544c77
[]
no_license
dkulik/generators
71281d98420f536b7f799ba578ae729a2cf6bfbb
e926393f0578d198929ff3a78498420c838e8b5b
refs/heads/master
2023-06-26T09:15:18.491137
2021-07-21T12:58:51
2021-07-21T12:58:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
ino
example_driver.ino
#include "src/hal_arduino/hal_arduino.h" #include "src/bindings/errors.h" // Forward declare the example functions. extern "C" void example_setup(TF_HalContext *hal); extern "C" void example_loop(TF_HalContext *hal); // Change this to your port assignment. // If you use a HAT or one or more Breakout Bricklets // you have to connect and list all chip select // signals, to make sure the signals are separated // correctly. TF_Port ports[2] = {{ .chip_select_pin=9, .port_name = 'A' }, { .chip_select_pin=8, .port_name = 'B' } }; // Used to report any error encountered while running the example. extern "C" void check(int e_code, const char *c) { if (e_code == TF_E_OK) { return; } tf_hal_printf("Failed to %s: %s (error code %d)\n", c, tf_hal_strerror(e_code), e_code); } TF_HalContext hal; void setup() { Serial.begin(115200); delay(3000); Serial.println("Hello World!"); check(tf_hal_create(&hal, ports, sizeof(ports)/sizeof(ports[0])), "hal create"); example_setup(&hal); } void loop() { example_loop(&hal); }
8c5e2d6254b6fe4d2c81e9c42cdf6e0ba256d030
7c623e9f635c36fd8b4f6417e26dc52365848763
/Udp.h
2853a2b4ddd7f4d25e618e335f1b38f0f7668578
[]
no_license
armandnaessens/pp4
17810c6094556a5a3464cf51178f7560c7ace839
e5eb30593890d3c63df91618cd56e2de7516959e
refs/heads/master
2020-03-09T18:22:34.350526
2018-04-10T12:44:13
2018-04-10T12:44:13
128,930,715
0
0
null
null
null
null
UTF-8
C++
false
false
452
h
Udp.h
#ifndef UDP_H #define UDP_H #include <stdint.h> class Udp { public: uint16_t src_port, dst_port, length, checksum; public: Udp(); Udp(int data[]); Udp(uint16_t src, uint16_t dst, uint16_t len); public: uint16_t get_src_port(); void set_src_port(uint16_t); uint16_t get_dst_port(); void set_dst_port(uint16_t); uint16_t get_length(); void set_length(uint16_t); uint16_t get_checksum(); void set_checksum(); }; #endif // !UDP_H
6ecf034723ded797147f79e8c7904dbc797f18a7
7e45f33da2e2a6e79e9ea169844f5d7bdd720a4a
/src/token.cc
6302b79aac4ddac7e641d50e3dda3bb888a95e17
[ "MIT" ]
permissive
neeilan/neeilang
77933b97951b1f9fa95689c9f03cfe18d82ac6cd
5025abcfbe824685ee55037764b54a4f4206cdcc
refs/heads/master
2023-09-05T13:37:46.297308
2023-08-30T00:14:50
2023-08-30T00:14:50
211,744,890
54
5
MIT
2020-03-19T00:37:58
2019-09-30T00:30:43
C++
UTF-8
C++
false
false
971
cc
token.cc
#include "token.h" #include <string> #include <vector> // Since enum names cannot be printed directly, we use this // workaround. static std::vector<std::string> token_names{ "LEFT_PAREN", "RIGHT_PAREN", "LEFT_BRACE", "RIGHT_BRACE", "LEFT_BRACKET", "RIGHT_BRACKET", "COMMA", "DOT", "MINUS", "PLUS", "SEMICOLON", "COLON", "SLASH", "STAR", "BANG", "BANG_EQUAL", "EQUAL", "EQUAL_EQUAL", "GREATER", "GREATER_EQUAL", "LESS", "LESS_EQUAL", "IDENTIFIER", "STRING", "NUMBER", "AND", "CLASS", "ELSE", "FALSE", "FN", "LAMBDA", "FOR", "IF", "NIL", "OR", "PRINT", "RETURN", "SUPER", "THIS", "TRUE", "VAR", "WHILE", "EOF"}; std::string Token::str() const { return token_names[type] + " " + lexeme + ((type == NUMBER || type == STRING) ? " " + literal : ""); }
bc7ab076750ecf2eb3a02cb087f2a1959cb8d596
2a07792d3715fcef59e67c48a5053fb19caeb93c
/client_led_slider.cpp
0042b2596bf2c4eb6a64e6effcd40b56c6446bc1
[ "MIT" ]
permissive
chenphilip888/rpi3b-qt5-wifi
8a8fbdf1b24452b50a4e7b1189b21ec55acd25a7
3c6cd5fa2acf0406f23e563c4e4ec7046df4ce5c
refs/heads/main
2023-03-24T03:49:14.967995
2021-03-20T05:04:14
2021-03-20T05:04:14
349,313,485
0
0
null
null
null
null
UTF-8
C++
false
false
1,978
cpp
client_led_slider.cpp
#include "client_led_slider.h" #include <QHBoxLayout> #include <QStatusBar> #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <time.h> #include <string.h> #include <stdlib.h> #define HOST "192.168.86.213" #define PORT 8888 int make_socket() { int sock; struct sockaddr_in serv_addr; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons( PORT ); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, HOST, &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } return sock; } Client_led_slider::Client_led_slider(QWidget *parent) : QMainWindow(parent) { QWidget* widget = new QWidget(this); QHBoxLayout *hbox = new QHBoxLayout(widget); slider = new QSlider(Qt::Horizontal, this); slider->setRange(0, 100); hbox->addWidget(slider); widget->setLayout(hbox); setCentralWidget(widget); statusBar(); connect(slider, &QSlider::valueChanged, this, &Client_led_slider::send_led); sock = make_socket(); } void Client_led_slider::send_led() { int valread; char led[4]; sprintf(led, "%d", slider->value()); char buffer[1024] = {0}; send(sock , led, strlen(led) , 0 ); valread = read( sock, buffer, 1024 ); buffer[valread] = '\0'; statusBar()->showMessage(buffer); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Client_led_slider window; window.resize(300, 70); window.setWindowTitle("client led slider"); window.show(); return app.exec(); }
fc3fc5d9b1f5707d336947cd06e8531f1d3ce15f
c05aa99876d763d5fa44619878187e57b5c33ecc
/NodeMCU_Code/NodeMCU_Code.ino
ad46eb51dd694125ada2bedff6ce83f762416dfa
[ "MIT" ]
permissive
harshit7rathore/Smart-Building-Energy-Management-System
8320de46f86e1f822de37584ec5a30fa18e2326e
a0676a646b7c2af9fb9aa08148d0a64450cf32b9
refs/heads/master
2022-12-12T13:31:09.193888
2020-09-10T06:57:57
2020-09-10T06:57:57
262,074,163
0
1
null
2020-05-07T15:55:31
2020-05-07T14:31:55
null
UTF-8
C++
false
false
1,904
ino
NodeMCU_Code.ino
#include <ESP8266WiFi.h> #include <FirebaseArduino.h> #include <DHT.h>; #include <Wire.h> #include <Adafruit_ADS1015.h> #define FIREBASE_HOST "smart-india-hackathon-harshit.firebaseio.com" #define FIREBASE_AUTH "bcMEsNxHijOr75VEuLHyTx3nSR0g1VIA2j3o5abV" #define WIFI_SSID "HARSHIT" #define WIFI_PASSWORD "12345678" Adafruit_ADS1115 ads(0x48); #define DHTPIN D7 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); void setup() { // float hum; // float temp; // int IR Serial.begin(115200); dht.begin(); ads.begin(); pinMode(D3,OUTPUT); // connect to wifi. WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); } void loop() { int LDR = ads.readADC_SingleEnded(0); Serial.print("Light Intensity: "); Serial.println(LDR, DEC); Firebase.setInt("LDR", LDR); float hum = dht.readHumidity(); float temp= dht.readTemperature(); Serial.print("Humidity: "); Serial.print(hum); Serial.print(" %, Temp: "); Serial.print(temp); Serial.println(" Celsius"); Firebase.setFloat("Temp", temp); Firebase.setFloat("Humidity", hum); int gas = analogRead(A0); Serial.print("AirQua="); Serial.print(gas, DEC); Serial.println(" PPM"); Firebase.setInt("Air_Quality", gas); Serial.println("."); Serial.println("."); Serial.println("."); char LDR_OUT = Firebase.getInt("LDROUT"); Serial.print("LDR OUT: "); Serial.println(LDR_OUT, DEC); if(LDR_OUT == 0) digitalWrite(D3,LOW); if(LDR_OUT == 1) digitalWrite(D3,HIGH); Serial.println("."); Serial.println("."); delay(10); }
c29f66a0057fc56e8b9801c6bab9f8efd5080150
08ef7a8640aeceb9f446f6aac3658d8608be2ffb
/FoggyLog/FoggyLog.cpp
3d509d8cff99d5388f2668445b52caa2dee15462
[]
no_license
davidemoraschi/FoggyLog
a408019f3d8f567ea8df302b0ada1ba941d3210a
328c36478fae24a49a95dbeb5ad6e8be75781752
refs/heads/master
2021-01-19T04:02:09.904684
2016-08-23T12:56:11
2016-08-23T12:56:11
63,422,312
0
0
null
null
null
null
UTF-8
C++
false
false
1,775
cpp
FoggyLog.cpp
// SensorWebPC.cpp // Pass the port name in the command line - e.g. sensorwebpc comm2 #include "stdafx.h" #include <windows.h> void PrintError( LPCSTR str) { LPVOID lpMessageBuffer; int error = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language (LPTSTR) &lpMessageBuffer, 0, NULL ); printf("%s: (%d) %s\n\n",str,error,lpMessageBuffer); LocalFree( lpMessageBuffer ); } int main(int argc, char* argv[]) { // open port for I/O HANDLE h = CreateFileA(argv[1], GENERIC_READ|GENERIC_WRITE, 0,NULL, OPEN_EXISTING,0,NULL); if(h == INVALID_HANDLE_VALUE) { PrintError("E012_Failed to open port"); } else { // set timeouts COMMTIMEOUTS cto = { 1, 100, 1000, 0, 0 }; DCB dcb; if(!SetCommTimeouts(h,&cto)) PrintError("E013_SetCommTimeouts failed"); // set DCB memset(&dcb,0,sizeof(dcb)); dcb.DCBlength = sizeof(dcb); dcb.BaudRate = 19200; dcb.fBinary = 1; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; // dcb.fOutxCtsFlow = 1; // dcb.fRtsControl = DTR_CONTROL_HANDSHAKE; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.ByteSize = 8; if(!SetCommState(h,&dcb)) PrintError("E014_SetCommState failed"); char buf[7]; DWORD read = 0; DWORD write=1; // Number of bytes to write to serial port buf[0] = 72; // Decmial value to write to serial port WriteFile(h,buf,write,&write,NULL); // write is updated with the number of bytes written ReadFile(h,buf,sizeof(buf),&read,NULL); // read is updated with the number of bytes read DWORD i; for (i=0; i<read; i++) printf("%i ", (unsigned char)buf[i]); CloseHandle(h); } return 0; }
5035389fa8413581dfbc2d0d1bf5c4d97a094623
1cbde47c1f484d46d703d59c75ac53ba03386956
/src/Platform/Postgresql.h
1df54265ed31629d3f279f507db68b562b389c0b
[]
no_license
mrAndersen/dsync
c4094400bf491c7884209c7e6c506930ea89e92b
5ea5aa7dbe456807876ab6f71e10b773bf62899e
refs/heads/master
2020-03-28T09:22:20.885689
2018-09-15T14:59:35
2018-09-15T14:59:35
148,031,796
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
Postgresql.h
#ifndef DSYNC_POSTGRESQL96_H #define DSYNC_POSTGRESQL96_H #include "AbstractPlatform.h" #include <pqxx/connection.hxx> class Postgresql : public Platform { private: pqxx::connection *connection = nullptr; public: std::vector<std::vector<std::string>> execute(const std::string &sql); std::vector<std::string> getTables(); long getTableSize(const std::string &table) override; void refreshDatabaseInfo() override; bool isTableFieldNullable(const std::string &table, const int &fieldIndex) override; std::string implodeRow(const std::string &table, const std::vector<std::string> &array) override; std::string getTableDdl(const std::string &table) override; void connect(); Postgresql(); virtual ~Postgresql(); }; #endif //DSYNC_POSTGRESQL96_H
d6f06b717eb0f5d7985bed9f2fa6ddb0157012c0
b40e2b6708fca5c0707805694613e9a17661275a
/Source/PlatformerGame/Private/UI/Menu/PlatformerLevelSelect.h
9038ab9f06276dff296640158ffe14f6b8a5ab82
[]
no_license
subor/sample_ue4_platformer
8fb03370769beb89880336957e2dbfe35495a322
d863fbce9698bf0c6a8bbdec54c0e295c57b2a20
refs/heads/master
2020-03-27T14:53:05.053775
2018-12-19T08:41:12
2018-12-19T08:41:12
146,684,338
2
0
null
2019-03-01T03:24:26
2018-08-30T02:23:42
C++
UTF-8
C++
false
false
358
h
PlatformerLevelSelect.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameMenuBuilder.h" class FPlatformerLevelSelect : public FGameMenuPage { public: /** sets owning player controller */ void MakeMenu(TWeakObjectPtr<APlayerController> _PCOwner); void OnUIPlayStreets(); void GoBack(); void ShowLoadingScreen(); void OnMenuHidden(); };
7c00edc2958007983ae7d990d6893f5ed2c5bd8b
d9b4adb8bdd3a19859b050c1735d06a380bb9929
/poj-cpp/3278/13863278_RE.cpp
83fa67b5426190b6a90f05a5278143473276c394
[]
no_license
conwnet/way-of-algorithm
eea4901ab62a6bc189e5c60209dc1e8610f76806
201df876cf55a7eae7e55789f2fa43d2f2545628
refs/heads/master
2021-07-31T19:17:48.871429
2021-07-24T17:42:30
2021-07-24T17:42:30
75,063,660
20
2
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
13863278_RE.cpp
#include <cstdio> #include <cstring> #include <queue> using namespace std; int N, K, vst[300000], time[100001]; int bfs(int n, int k); int main(){ int s, i, t, mins; while(~scanf("%d%d", &N, &K)){ if(N>=K){ printf("%d\n", N-K); continue; } mins = N-K; s = 0; t = N; if(t<K){ s++; t *= 2; } bfs(N, K); printf("%d\n", time[K]); } return 0; } int bfs(int n, int k){ queue<int> q; memset(vst, 0, 1200000); q.push(n); while(1){ if(q.front()==k) return 1; if(q.front()>0 && !vst[q.front()-1]){ vst[q.front()-1] = 1; time[q.front()-1] = time[q.front()]+1; q.push(q.front()-1); } if(q.front()<k && !vst[q.front()+1]){ vst[q.front()+1] = 1; time[q.front()+1] = time[q.front()]+1; q.push(q.front()+1); } if(q.front()<k && !vst[q.front()*2]){ vst[q.front()*2] = 1; time[q.front()*2] = time[q.front()]+1; q.push(q.front()*2); } q.pop(); } return 0; }
40277d8e66af909e42604257239d801cb5daf730
b1c6fe68b890e3244e3dbbac337908006afd05c2
/House/House/Flat.cpp
cd9583f5109d29e860244eeb221044416f677fba
[]
no_license
AleksandrZhyts/SecondTerm
6fe7d1d694568d220c80b2bb74cee0c70814d763
f601383ae804e8d5ff224a39c980e9eef42d5459
refs/heads/master
2020-07-02T17:07:37.414840
2017-02-26T17:00:11
2017-02-26T17:00:11
74,293,805
0
0
null
null
null
null
UTF-8
C++
false
false
4,123
cpp
Flat.cpp
#include "stdafx.h" #include "Flat.h" Flat::Flat() { roommates = NULL; h_phone = NULL; number_roommates = 0; num_rooms = 0; total_space = 0.0; living_space = 0.0; kitchen_space = 0.0; price = 0.0; floor = 0; std::cout << "Constructor Flat" << std::endl; } Flat::Flat(const Flat& fl) { num_rooms = fl.num_rooms; total_space = fl.total_space; living_space = fl.living_space; kitchen_space = fl.kitchen_space; price = fl.price; floor = fl.floor; h_phone = new char[strlen(fl.h_phone) + 1]; strcpy_s(h_phone, strlen(fl.h_phone) + 1, fl.h_phone); number_roommates = fl.number_roommates; roommates = new Man[fl.number_roommates]; for (unsigned int i(0); i < number_roommates; i++) { roommates[i] = fl.roommates[i]; } } bool Flat::operator==(const Flat& fl) { return (total_space == fl.total_space); } bool Flat::operator>(const Flat& fl) { return (price > fl.price); } unsigned int Flat::getNumber_roommates() { return number_roommates; } double Flat::getPrice() { return price; } void Flat::register_Person() { Man *temp; temp = new Man[number_roommates + 1]; for (unsigned int i(0); i < number_roommates; i++) { temp[i] = roommates[i]; } std::cin.get(); std::cin >> temp[number_roommates]; delete[] roommates; number_roommates++; roommates = temp; } int Flat::search_person(char *name) { unsigned int i = 0; while (i < number_roommates) { if (_stricmp(name, roommates[i].getFio()) == 0) return i; else i++; } return -1; } void Flat::check_out_Person(char* name) { int index = search_person(name); if (index == -1) std::cout << "\nThis person doesn't leave in the flat\n"; else { std::cout <<" Person was check out\n"; Man *temp = new Man[number_roommates - 1]; unsigned int i = 0, j = 0; while (i < number_roommates) { if (i == index) i++; temp[j++] = roommates[i++]; } delete[] roommates; number_roommates--; roommates = temp; } } void Flat::operator=(const Flat& fl) { this->~Flat(); num_rooms = fl.num_rooms; total_space = fl.total_space; living_space = fl.living_space; kitchen_space = fl.kitchen_space; floor = fl.floor; h_phone = new char[strlen(fl.h_phone) + 1]; strcpy_s(h_phone, strlen(fl.h_phone) + 1, fl.h_phone); number_roommates = fl.number_roommates; roommates = new Man[fl.number_roommates]; for (unsigned int i(0); i < number_roommates; i++) { roommates[i] = fl.roommates[i]; } } std::istream& operator >> (std::istream& is, Flat& fl) { std::cout << "Enter number of roommates : "; is >> fl.number_roommates; is.get(); fl.roommates = new Man[fl.number_roommates]; for (unsigned int i(0); i < fl.number_roommates; i++) { std::cout << "Enter " << i + 1 << " members" << std::endl; is >> fl.roommates[i]; } std::cout << "Enter home phone : "; fl.h_phone = new char[13]; is.getline(fl.h_phone, 12); std::cout << "Enter number of rooms : "; is >> fl.num_rooms; std::cout << "Enter total space in the flat : "; is >> fl.total_space; std::cout << "Enter living space in the flat : "; is >> fl.living_space; std::cout << "Enter kitchen space in the flat : "; is >> fl.kitchen_space; std::cout << "Enter floor number : "; is >> fl.floor; std::cout << "Enter price : "; is >> fl.price; return is; } std::ostream& operator << (std::ostream& os, Flat& fl) { std::cout << "****************************" << std::endl; os << "There are " << fl.number_roommates << " members in the flat\n"; for (unsigned int i(0); i < fl.number_roommates; i++) { os << fl.roommates[i]; std::cout << "****************************" << std::endl; } os << "Number of rooms : " << fl.num_rooms << std::endl;; os << "Total space : " << fl.total_space << std::endl; os << "Living space : " << fl.living_space << std::endl; os << "Kitchen space : " << fl.kitchen_space << std::endl; os << "Number of floors : " << fl.floor << std::endl; os << "Price : " << fl.price << std::endl; return os; } Flat::~Flat() { delete[] h_phone; h_phone = NULL; delete[] roommates; roommates = NULL; std::cout << "Destructor flat" << std::endl; }
393e2ffd3c78f42ffcf8bdf70b86984265976a5c
aa1e770aa1444aa2354fb92654b1d3956d2548c6
/lib/WeatherBlockAP/include/APIData.h
5849e3bc7c9d1b561c45ec6eabe2c7c4a6d8a68f
[]
no_license
cwmli/weather-block
64939f6c839a7635ec8138dd7b26b48909c7d138
a3f38d0c1cb324e4e18e41d301d56907ed642311
refs/heads/master
2021-12-15T00:20:49.585777
2021-12-05T02:40:28
2021-12-05T02:40:28
188,610,530
0
0
null
2020-01-07T04:15:14
2019-05-25T20:42:49
C++
UTF-8
C++
false
false
1,934
h
APIData.h
#ifndef APIDATA_H #define APIDATA_H #include <map> #include <time.h> #include "APIParseRule.h" struct APIData { String name; String url; bool isActive; unsigned long refreshTime; unsigned long lastRefreshed = 0; std::map<String, String> data; std::map<String, APIParseRule> parseRules; APIData() {} APIData(String name, String url, long time) : name(name), url(url), refreshTime(time) { lastRefreshed = 0; } String parseRulesString() { String res; for (auto it = parseRules.begin(); it != parseRules.end(); it++) { if (it->second.type == APIValueType::ICON) { res += it->first + " " + it->second.x + " " + it->second.y + " ffffff " + it->second.type; } else { unsigned long hex = (it->second.color.r << 16) | (it->second.color.g << 8) | (it->second.color.b); res += it->first + " " + it->second.x + " " + it->second.y + " " + String(hex, HEX) + " " + it->second.type; } if (next(it) != parseRules.end()) { res += ","; } } return res; } void parseRulesString(char * content) { parseRules.clear(); char * endparserule; char * parserule = strtok_r(content, ",", &endparserule); while(parserule != NULL) { char * values[5]; byte index = 0; char * endrule; char * rule = strtok_r(parserule, " ", &endrule); while (rule != NULL) { values[index++] = rule; rule = strtok_r(NULL, " ", &endrule); } parseRules.insert(std::make_pair( values[0], APIParseRule{ atoi(values[1]), atoi(values[2]), CRGB(strtoul(values[3], NULL, HEX)), static_cast<APIValueType>(atoi(values[4])) } )); // Serial.printf("Parserule: %s | Tokens: %s, %s, %s, %s\n", parserule, values[0], values[1], values[2], values[3]); parserule = strtok_r(NULL, ",", &endparserule); } } }; #endif
96bd4606d10c4212059634d407d26a68e600c30d
bc2a6e1f41ced330c04c199d0e13f7f8b82bd6ef
/src/halibs/include/avr-halib/common/cdeviceframe.h
a29d0f61d7812b9d97a70d8fccefc2650af52311
[]
no_license
SoCXin/MEGA328P
372187c044c402ae90c3c3192b4d90f8ea996f3e
321166c6f287e441d0ae906ecfddc5d3cff706f2
refs/heads/master
2023-04-27T02:10:27.492148
2021-05-18T07:51:01
2021-05-18T07:51:01
157,304,433
0
0
null
null
null
null
UTF-8
C++
false
false
10,685
h
cdeviceframe.h
#pragma once #include "delegate.h" #include "cframe.h" /** \brief Base class of the CFrame implementation. * * \tparam character device the CFrame is based on * \tparam type to determin the size of a frame (default <code>uint8_t</code>) * \tparam usable payload size */ template <class BaseCDevice, class FLT = uint8_t, FLT PL = 255> class CDeviceFrameBase: public BaseCDevice { public: /** \brief layer specific information */ typedef struct { enum { payload = PL /*!< available payload*/ }; } info; /** \brief layer specific message object */ typedef struct { FLT size; /**< number of data bytes */ uint8_t payload[info::payload]; /**< data of the message object */ } mob_t; }; /** \brief This class realizes a bit stuffing by implementing a micro layer. * * \tparam character device the CDeviceFrame is based on * \tparam type to determin the size of a frame (default <code>uint8_t</code>) * \tparam usable payload size * \tparam State Machine to use */ template <class BaseCDevice, class FLT = uint8_t, FLT PL = 255, class StateMachine = CFrame<> > class CDeviceFrameNoInt: public CDeviceFrameBase<BaseCDevice, FLT, PL> { protected: /** \brief TODO \todo */ typedef CDeviceFrameBase<BaseCDevice, FLT, PL> basetype; public: /*! \brief type of the class*/ typedef CDeviceFrameNoInt<BaseCDevice, FLT, PL, StateMachine> type; /** \brief TODO \todo */ typedef typename basetype::info info; /** \brief TODO \todo */ typedef typename basetype::mob_t mob_t; CDeviceFrameNoInt() {} ~CDeviceFrameNoInt() {} /** \brief Send a message. * * \param[in] data buffer to be send * \param[in] size size of the data * \return Returns the size of the data send (zero if unsuccessfull). */ FLT send(const uint8_t* data, FLT size) { if ( size <= 0 ) return 0; // stop if there is no data StateMachine cframe; FLT result = size; basetype::put( cframe.startFrame()); for(int i = 0 ; i < size; i++) { do { while(!this->ready()); basetype::put(cframe.transformOut(data[i])); } while(cframe.again()); } while(!this->ready()); basetype::put(cframe.endFrame()); return result; } /** \brief Sends a message. * * \param[in] message source message object * \return Returns the size of the data send (zero if unsuccessfull). */ FLT send(const mob_t& message) { return send(message.payload, message.size); } /** \brief Reads the last message received. * * \param[out] data buffer for received data * \param[in] size available size of the provided buffer * \return Returns the size of the message payload (zero if unsuccessfull). */ FLT recv(uint8_t* data, FLT size) { FLT count = 0; StateMachine cframe; for (char * buffer = (char *) data;/* cframe.finished() breaks loop */;) { char c; while( !basetype::get(c) ); if( cframe.transformIn(c) ) { if(count == size) { cframe.resetRx(); count = 0; buffer = (char *) data; } else { *buffer = c; buffer++; count++; } } else if(cframe.restarted()) { count = 0; buffer = (char *) data; } else if (cframe.finished()) { break; } } return count; } /** \brief Reads the last message received. * * \param[out] message destination message object * \return Returns the size of the message payload (zero if unsuccessfull). */ FLT recv(mob_t& message) { message.size = recv(message.payload, info::payload); return message.size; } }; /** * \brief This class realizes a bit stuffing by implementing a micro layer. * * \tparam character device the CDeviceFrame is based on * \tparam type to determin the size of a frame (default <code>uint8_t</code>) * \tparam usable payload size * \tparam State Machine to use */ template <class BaseCDevice, class FLT = uint8_t, FLT PL = 255, class StateMachine= CFrame<> > class CDeviceFrame: public CDeviceFrameBase<BaseCDevice, FLT, PL> { protected: /** \brief TODO \todo */ typedef CDeviceFrameBase<BaseCDevice, FLT, PL> basetype; public: /** \brief type of the class */ typedef CDeviceFrame<BaseCDevice, FLT, PL, StateMachine> type; /** \brief TODO \todo */ typedef typename basetype::info info; /** \brief TODO \todo */ typedef typename basetype::mob_t mob_t; protected: /** \brief layer specific data object */ typedef struct { FLT position; /**< current position in the message */ mob_t data; /**< data packet including size and payload */ } mobState_t; /** \brief TODO \todo */ mobState_t recvMob; /** \brief TODO \todo */ mobState_t sendMob; /** \brief TODO \todo */ StateMachine cframe; /** \brief TODO \todo */ void getonReceive() { char c; if ( recvMob.position == info::payload ) cframe.resetRx(); basetype::get( c ); if(cframe.transformIn(c)) { recvMob.data.payload[recvMob.data.size++] = (uint8_t) c; } else if(cframe.restarted()) { recvMob.data.size = 0; } else if(cframe.finished()) { this->sendonReceive(); } } /** \brief TODO \todo */ void putonReady() { if(cframe.readyToStart() && sendMob.position == 0 && sendMob.data.size > 0) basetype::put(cframe.startFrame()); else if(!cframe.sending()) { basetype::disableonReady(); this->sendonReady(); } else { if(sendMob.position == sendMob.data.size) basetype::put(cframe.endFrame()); else { basetype::put(cframe.transformOut(sendMob.data.payload[sendMob.position])); if (!cframe.again()) sendMob.position++; } } } /** \brief TODO \todo */ void sendonReady() { while(!cframe.sending()) if(this->onReady.isEmpty()) break; else { this->onReady(); break; } } /** \brief TODO \todo */ void sendonReceive() { while(cframe.finished()) if(this->onReceive.isEmpty()) break; else { this->onReceive(); break; } } public: /** \brief TODO \todo */ avr_halib::common::Delegate<> onReady; /** \brief TODO \todo */ avr_halib::common::Delegate<> onReceive; /** \brief TODO \todo */ CDeviceFrame() { recvMob.position = 0; recvMob.data.size = 0; sendMob.position = 0; sendMob.data.size = 0; //------------------------------------------------------- basetype::onReady.template bind< type, & type::putonReady >(this); basetype::onReceive.template bind<type ,& type::getonReceive>(this); basetype::enableonReceive(); } /** \brief TODO \todo */ ~CDeviceFrame() {} /** \brief TODO \todo */ void enableonReady() { sendonReady(); } /** \brief TODO \todo */ void enableonReceive() { sendonReceive(); } /** \brief Send a message. * * \param[in] data buffer to be send * \param[in] size size of the data * \return Returns the size of the data send (zero if unsuccessfull). */ FLT send(const uint8_t* data, FLT size) { if(cframe.sending()) return 0; sendMob.data.size = 0; sendMob.position = 0; for (; sendMob.data.size < size; sendMob.data.size++) { sendMob.data.payload[sendMob.data.size] = data[sendMob.data.size]; } cframe.resetTx(); // use delegates of BaseCDevice to put data on medium basetype::enableonReady(); return sendMob.data.size; } /** \brief Sends a message. * * \param[in] message source message object * \return Returns the size of the data send (zero if unsuccessfull). */ FLT send(const mob_t& message) { return send(message.payload, message.size); } /** \brief Reads the last message received. * * \param[out] data buffer for received data * \param[in] size available size of the provided buffer * \return Returns the size of the message payload (zero if unsuccessfull). */ FLT recv(uint8_t* data, FLT size) { FLT count = 0; if ( cframe.finished() && (recvMob.data.size <= size) ) { for (; count < recvMob.data.size; count++) data[count] = recvMob.data.payload[count]; cframe.resetRx(); } return count; } /** \brief Reads the last message received. * * \param[out] message destination message object * \return Returns the size of the message payload (zero if unsuccessfull). */ FLT recv(mob_t& message) { message.size = recv(message.payload, info::payload); return message.size; } };
3d07df6181b6c0d4edd816744aa9e31c2f767d31
2d8204c2349a8b763604dbbd9b35e6a46921c6fc
/july_28(Polymorphis)/july_28/Rect.h
4b8f8ea59f96a63e75360e060718a33ba9f614b4
[]
no_license
OnkarYadav96/CPP
1677a1c7aa91ce8cb824467de8519528438a9e52
bebd77d371dd4bd24c4618ec97be4046b91c5df8
refs/heads/master
2022-12-01T06:29:32.461707
2020-08-16T13:37:07
2020-08-16T13:37:07
282,574,520
1
0
null
null
null
null
UTF-8
C++
false
false
143
h
Rect.h
#pragma once #include"Shape.h" class cRect :public cShape { int len, bre; public: cRect(); cRect(int, int); void CalArea(); };
43e53430d27a9c4e45d74830a0d24e64625181af
85d9ae988a154ccedc05ccb3f4bc2a402314257a
/GeometryLibrary/src/Cone3D.cpp
a3e7c2c7ecb2318c4c8b478bd62f3b5a45a6ebfe
[ "Apache-2.0" ]
permissive
TB989/Fierce-Engine
cbc660aa2e2cbb9c4dfab0a8f185fa8bae4a2c5b
46db83d1bcf89e463b56ecae817854a9d892eb9a
refs/heads/main
2023-08-07T13:15:31.683001
2023-07-22T16:11:20
2023-07-22T16:11:20
244,148,022
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
Cone3D.cpp
#include "Geometry.h" void Cone3D::getVertices(std::vector<float>& vertices, bool loadTextureCoordinates, bool loadNormals,int numPoints, float angle, float innerRadius, int numRings) { if (loadTextureCoordinates) { addVertex3D(vertices, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f); } else { addVertex3D(vertices, 0.0f, 0.0f, -0.5f); } addCircleVertices3D(vertices, loadTextureCoordinates, 0.0f, 0.0f, -0.5f, numPoints, 0.5f, angle); if (loadTextureCoordinates) { addVertex3D(vertices, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f); } else { addVertex3D(vertices, 0.0f, 0.0f, 0.5f); } } void Cone3D::getIndices(std::vector<unsigned int>& indices, int numPoints, float angle, float innerRadius, int numRings) { addCircleIndices(indices, numPoints, angle, 0, 1, false); addCircleIndices(indices, numPoints, angle, numPoints+1, 1, true); if (angle != 360.0f) { addTriangleIndices(indices, 0, 1, numPoints + 1, true); addTriangleIndices(indices, numPoints, 0, numPoints + 1, true); } }
8417dd148d5599fbcf9a7723427ebf0affa27aac
afdc82729b1ae1e1a11fc0d63d4990a7972a9fd6
/mace/ops/delegator/eltwise.h
fe66f35462270535bfda14fb50b907e3309dee6b
[ "Apache-2.0" ]
permissive
gasgallo/mace
79e759ceb9548fa69d577dd28ca983f87a302a5e
96b4089e2323d9af119f9f2eda51976ac19ae6c4
refs/heads/master
2021-06-23T19:09:24.230126
2021-03-02T12:23:05
2021-03-02T12:23:05
205,080,233
1
0
Apache-2.0
2019-08-29T04:27:36
2019-08-29T04:27:35
null
UTF-8
C++
false
false
1,776
h
eltwise.h
// Copyright 2020 The MACE Authors. All Rights Reserved. // // 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. // This implements matrix-vector multiplication described as // https://github.com/google/gemmlowp/blob/master/todo/fast-gemv.txt #ifndef MACE_OPS_DELEGATOR_ELTWISE_H_ #define MACE_OPS_DELEGATOR_ELTWISE_H_ #include "mace/core/ops/op_context.h" #include "mace/core/ops/op_delegator.h" #include "mace/core/registry/op_delegator_registry.h" #include "mace/core/types.h" #include "mace/ops/common/eltwise_type.h" namespace mace { namespace ops { namespace delegator { struct EltwiseParam : public DelegatorParam { explicit EltwiseParam(EltwiseType type) : type_(type) {} EltwiseType type_; }; class Eltwise : public OpDelegator { public: explicit Eltwise(const EltwiseParam &param) : OpDelegator(param), type_(param.type_) {} virtual ~Eltwise() = default; MACE_DEFINE_DELEGATOR_CREATOR(Eltwise) virtual MaceStatus Compute(const OpContext *context, const Tensor *input0, const Tensor *input1, Tensor *output) = 0; protected: EltwiseType type_; }; } // namespace delegator } // namespace ops } // namespace mace #endif // MACE_OPS_DELEGATOR_ELTWISE_H_
5b417c7230b94d9c58308dfe8a30512be5a14365
d9d118f4f1d626a750897babce33b3ce34f11575
/x451/resource/DisplayManagerResource/implementations/CDisplayManagerEventProvider.h
f498ec87e5c526a71d1251414696f89e2a23a34e
[]
no_license
HNarayana-youCanDoIt/Testproject
39af23d3ee4c2a413670c3dcd68dbd41424bbe91
226795327f50102989dfc8e12174823dddc2aa68
refs/heads/master
2023-03-26T05:57:57.044706
2021-03-31T11:14:53
2021-03-31T11:14:53
353,326,120
0
0
null
null
null
null
UTF-8
C++
false
false
5,183
h
CDisplayManagerEventProvider.h
/***************************************************************** * Project Harman Car Multimedia System * (c) copyright 2018 * Company Harman/Becker Automotive Systems GmbH * All rights reserved * Secrecy Level STRICTLY CONFIDENTIAL ****************************************************************/ /** * @file CDisplayManagerEventProvider.h * @ingroup HMIComponent * @author Vishal Chaudhary * @brief This file contains CDisplayManagerEventProvider class that * shall publish events whenever HMI DisplayManagerResource layer * receive some response or callbacks from DisplayManagerResource * proxy. */ #ifndef CDISPLAYMANAGEREVENTPROVIDER_H #define CDISPLAYMANAGEREVENTPROVIDER_H #include <QObject> using namespace std; /*! * @class CDisplayManagerDataEventProvider * @brief This class shall publish events whenever HMI DisplayManagerResource layer receive * some response or callbacks from BtResource proxy. */ class CDisplayManagerEventProvider: public QObject { Q_OBJECT public: CDisplayManagerEventProvider(QObject* pParent = 0); ~CDisplayManagerEventProvider(); signals: /******************************************************//** * @category SIGNALS * @brief Signals that shall be emitted to the application layer *******************************************************/ /** * @brief sigBrightnessLevelRespRecv: signal to update the * setBrightnessLevelAsuncReq() response. * @param void * @return void */ void sigBrightnessLevelRespRecv(); /** * @brief sigButtonPanelBrightnessLevelRespRecv: signal to update the * setButtonPanelBrightnessLevelAsyncReq() response. * @param void * @return void */ void sigButtonPanelBrightnessLevelRespRecv(); /** * @brief sigUpdateBrightnessLevel: signal to update the * brightness level. * @param iBrightnessLevel: brightness level. * @return void */ void sigUpdateBrightnessLevel(short iBrightnessLevel); /** * @brief sigUpdateButtonPanelBrightnessLevel: signal to update the * brightness level. * @param iBrightnessLevel: brightness level. * @return void */ void sigUpdateButtonPanelBrightnessLevel(short iBrightnessLevel); /** * @brief sigUpdateDisplayOnOffFeatureStatus: signal to update the * display OnOff feature status. * @param iDisplayOnOffFeatureStatus: DisplayOnOffFeatureStatus 1 if * enabled, else 0. * @return void */ void sigUpdateDisplayOnOffFeatureStatus(qint32 iDisplayOnOffFeatureStatus); /** * @brief sigUpdateNightModeStatus: signal to update the * DayNight status. * @param iNightModeStatus: night mode status 0 - disabled , 1 - * enabled * @return void */ void sigUpdateNightModeStatus(qint32 iNightModeStatus); public: /************************************************************************//** * @category METHODS * @brief Methods that would be used by the DisplayManagerResource * layer to indirectly emit signals to the DisplayManager application layer ************************************************************************/ /** * @brief updateBrightnessLevelResponse: Method to update the response * of setBrightnessLevelAsuncReq(), the value is used for debouncing * logic. * @param void. * @return void. */ void updateBrightnessLevelResponse(); /** * @brief updateButtonPanelBrightnessLevelResponse: Method to update the response * of setButtonPanelBrightnessLevelAsyncReq(), the value is used for debouncing * logic. * @param void. * @return void. */ void updateButtonPanelBrightnessLevelResponse(); /** * @brief updateBrightnessLevel: Method to update the brightness level. * @param iBrightnessLevel: Brightness level. * @return void. */ void updateBrightnessLevel(short iBrightnessLevel); /** * @brief updateButtonPanelBrightnessLevel: Method to update the brightness level. * @param iBrightnessLevel: Brightness level. * @return void. */ void updateButtonPanelBrightnessLevel(short iBrightnessLevel); /** * @brief updateDisplayOnOffFeatureStatus: Method to update the display * on/off feature status. * @param iDisplayOnOffFeatureStatus: Display on/off feature status 1 if * enabled, else 0. * @return void. */ void updateDisplayOnOffFeatureStatus(qint32 iDisplayOnOffFeatureStatus); /** * @brief updateNightModeStatus: Method to update the NightMode * status. * @param iNightModeStatus: night mode status 0 - disabled , 1 - * enabled * @return void. */ void updateNightModeStatus(qint32 iNightModeStatus); }; #endif // CDISPLAYMANAGEREVENTPROVIDER_H
f44aa92c6c1b1c3ad1cfca2532d6e14d0fe4a1de
1f3019ccf04713f4c0be87a883d38e5720225525
/mp6/kdtree.cpp
a77d51a929bd8175bb9f8f78a6dc5a62a7b2ca49
[]
no_license
liuruoqian/CS225
8aabdc199e0e95ff7410ded1e43fa701eb4bcb86
f4df5ad4c7808d4ebce604d7eb48484318abd081
refs/heads/master
2021-01-09T05:46:33.096739
2017-02-12T22:29:04
2017-02-12T22:29:04
80,801,209
0
1
null
2017-02-12T20:33:20
2017-02-03T05:49:21
null
UTF-8
C++
false
false
6,202
cpp
kdtree.cpp
/** * @file kdtree.cpp * Implementation of KDTree class. */ template <int Dim> bool KDTree<Dim>::smallerDimVal(const Point<Dim>& first, const Point<Dim>& second, int curDim) const { /** * @todo Implement this function! */ if (first[curDim] < second[curDim]) return true; else if (first[curDim] == second[curDim]) return (first < second); else return false; } template <int Dim> bool KDTree<Dim>::shouldReplace(const Point<Dim>& target, const Point<Dim>& currentBest, const Point<Dim>& potential) const { /** * @todo Implement this function! */ int disCurr = 0; int disPot = 0; for (int i = 0; i < Dim; i ++){ disCurr = disCurr + pow(target[i] - currentBest[i], 2); disPot = disPot + pow(target[i] - potential[i], 2); } if(disPot < disCurr) return true; else if (disCurr == disPot) return (potential < currentBest); else return false; } template <int Dim> KDTree<Dim>::KDTree(const vector<Point<Dim>>& newPoints) { /** * @todo Implement this function! */ points = newPoints; KDTree_helper(0, points.size()-1, 0); } template <int Dim> void KDTree<Dim>::KDTree_helper(int left, int right, int dim){ if (left >= right) return; int n = (left + right)/2; select (left, right, n, dim); if (n - left <= 1 && right - n <= 1) return; else{ if (right - n > 1) KDTree_helper(n+1, right, (dim+1)%Dim); if (n - left > 1) KDTree_helper(left, n-1, (dim + 1)%Dim); } // the previous one only deal with part of the vector (left or right) /* int mindex; mindex = (left + right)/2; select(left, right, mindex, dim); if(left < mindex - 1) KDTree_helper(left, mindex - 1, (dim + 1) % Dim); if(right > mindex + 1) KDTree_helper(mindex + 1, right, (dim + 1) % Dim); */ } /* template <int Dim> void KDTree<Dim>::swap(Point<Dim> & first, Point<Dim> & second){ Point<Dim> t = first; first = second; second = t; } */ template <int Dim> int KDTree<Dim>::partition(int left, int right, int index, int dim){ Point<Dim> pivotValue = points[index]; std::swap(points[index], points[right]); int storeIndex = left; for (int i = left; i < right; i++){ if (smallerDimVal(points[i], pivotValue, dim)){ std::swap(points[storeIndex], points[i]); storeIndex ++; } } std::swap(points[right], points[storeIndex]); return storeIndex; } // sort the vector from left to right, and let the median in the middle, // the elemetn on the left is lower than median, and element on the right // is larger than median template <int Dim> void KDTree<Dim>::select(int left, int right, int n, int dim){ if (left >= right) return ; int pivotIndex = (left + right)/2; pivotIndex = partition(left, right, pivotIndex, dim); if(n == pivotIndex) return ; else if (n < pivotIndex) select(left, pivotIndex-1, n, dim); else select(pivotIndex+1, right, n, dim); } /* template<int Dim> int KDTree<Dim>::getDistance(const Point<Dim> & point1, const Point<Dim> & point2) const { int distance = 0; for(int i = 0; i < Dim; i++) distance += (point1[i]-point2[i])*(point1[i]-point2[i]); return distance; } */ template <int Dim> Point<Dim> KDTree<Dim>::findNearestNeighbor(const Point<Dim>& query) const { /** * @todo Implement this function! */ //return Point<Dim>(); return findNN(query, 0, points.size()-1, 0); } template <int Dim> Point<Dim> KDTree<Dim>::findNN(const Point<Dim>& query, int left, int right, int dim) const{ Point<Dim> child; bool Left = false; int mid; if (left == right) return points[left]; // if vector points has only one element, return else{ mid = (left + right)/2; // parent node index!! if(smallerDimVal(query, points[mid], dim)){ if (mid - left < 1) return points[left]; else{ child = findNN(query, left, mid-1, (dim+1)%Dim); // parentIndex = mid; } Left = true; } else{ if (right - mid < 1) return points[right]; else{ child = findNN(query, mid+1, right, (dim+1)%Dim); // parentIndex = mid; } Left = false; } int distToPlane = pow(query[dim]-points[mid][dim],2); int distChild = 0; int distParent = 0; Point<Dim> bestNode; Point<Dim> opposite; int currRadius; for (int i = 0; i < Dim; i++){ distChild = distChild + pow(child[i]-query[i],2); distParent = distParent + pow(points[mid][i] - query[i], 2); } if(distParent < distChild){ bestNode = points[mid]; currRadius = distParent; } else if (distParent == distChild){ if (points[mid] < child){ bestNode = points[mid]; currRadius = distParent; } else{ bestNode = child; currRadius = distChild; } } else{ bestNode = child; currRadius = distChild; } if(distToPlane <= currRadius){ if (Left == true){ if (right - mid < 1) opposite = points[mid]; else opposite = findNN(query, mid+1, right, (dim+1)%Dim); } else{ if (mid - left < 1) opposite = points[mid]; else opposite = findNN(query, left, mid-1, (dim+1)%Dim); } if(shouldReplace(query, bestNode, opposite)) return opposite; else return bestNode; } else return bestNode; } }
ef0199d6b32a7343f1fae2f90c4940a314886a7b
de738ce5da87cb540384405407a210d4b37aeddf
/I/tarea1/App1.cpp
fa5fe80ab3eb587d4887249026605320e0b87b43
[]
no_license
rherdez/clase_Algoritmos
ff66f61b166b55f63d40b49e6662da6e7801a82f
50af6f47c35976ba7af39d31bf9d93eee7cef966
refs/heads/master
2023-08-24T19:12:16.518569
2021-11-11T01:58:07
2021-11-11T01:58:07
417,285,721
1
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
App1.cpp
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; int main(int argc, char** argv) { int dia; cout<<"Ingrese un numero"<<endl; cin>>dia; switch(dia){ case 1: cout<<"Domingo"<<endl; break; case 2: cout<<"Lunes "<<endl; break; case 3: cout<<"Martes"<<endl; break; case 4: cout<<"Miercoles"<<endl; break; case 5: cout<<"Jueves"<<endl; break; case 6: cout<<"Viernes"<<endl; break; case 7: cout<<"Sabado"<<endl; break; default: cout<<"Numero no valido"<<endl; } return 0; }
1ea91b353d2eec449afec0da682624f7a3209adf
310cfc54fc61cbb94c548f263df5035e0d3856e4
/lab-12/lab№12.2.cpp
8550534ca6552f2afcd2be137333931dbf49770d
[]
no_license
anusherv/introduction-to-programming
56098823f950eb5c84fae7b7b50e27028468eb12
417c687f0b4358721e9bbae30da1e7764ad45c40
refs/heads/main
2023-02-17T05:28:42.250843
2021-01-20T20:03:31
2021-01-20T20:03:31
331,413,140
0
0
null
null
null
null
UTF-8
C++
false
false
703
cpp
lab№12.2.cpp
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, "Russian"); int N,F; string C; string d[] = { "север", "запад", "юг", "восток" }; cout << "введите напрваление(полным словом)\n"; cin >> C; cout << "N="; cin >> N; if (C == "север") { F = 0; } else if (C == "запад") { F = 1; } else if (C == "юг") { F = 2; } else if (C == "восток") { F = 3; } switch (N) { case(0): cout << C; break; case(1): if (F == 3) cout << d[0]; else cout << d[F+1]; break; case(-1): if (F == 0) cout << d[2]; else cout << d[F-1]; break; } }
e999a02baaf6e1b3218fd3dfd78a1d0171a4fa8e
55263cf5b3e6e727d46e39a0f9a5bba050a2e090
/optimization/hessianapproximations.hh
7d0d8695dbd89be30597f5044df7e060e481e007
[]
no_license
qooldeel/adonis
a6fc4d2fc3cb23211ccd4830891b4dc599d53f9d
7222cb3d298306944548a8617a1db79d9333baab
refs/heads/master
2021-01-20T18:33:06.985900
2016-06-15T20:33:00
2016-06-15T20:33:00
61,237,667
0
0
null
null
null
null
UTF-8
C++
false
false
8,612
hh
hessianapproximations.hh
#ifndef HESSIAN_APPROXIMATION_FORMULAS_HH #define HESSIAN_APPROXIMATION_FORMULAS_HH #include "../common/globalfunctions.hh" #include "../common/elementaryoperations.hh" #include "../misc/operations4randomaccesscontainers.hh" namespace Adonis{ /** * \brief Hessian matrix updates * * NOTE: we assume that the Hessian is <I>dense</I>. Since the Hessian is * symmetric/hermitian, we only store the lower triangular part (then * column-wise) which is equivalent to storing the upper triangular * part (in row-wise fashion). All operations will be performed with * that storage format! */ template<class V, class UP> class MatrixUpdate{ private: UP& r2d(){return static_cast<UP&>(*this);} V& update(V& B, const V& xnext, const V& x, const V& gradxnext, const V& gradx){ return r2d().update_formula(B,xnext,x,gradxnext,gradx); } V& update(V& B, const V& p, const V& gradxnext, const V& gradx){ return r2d().update_formula(B,p,gradxnext,gradx); } protected: typedef typename V::value_type value_type; V sk_, yk_, dy1_,dy2_, Bs_; //! these are for general usage public: V& hessian_update(V& B, const V& xnext, const V& x, const V& gradxnext, const V& gradx){ return update(B,xnext,x,gradxnext,gradx); } V& hessian_update(V& B, const V& p, const V& gradxnext, const V& gradx){ return update(B,p,gradxnext,gradx); } void init(size_t dim, const value_type& d = value_type()){ sk_.resize(dim,d); yk_.resize(dim,d); } }; /** * \tparam C select Hessian update formula ('b','d' or 'i': BFGS, damped BFGS, * or inverse Hessian, respectively) * \tparam V array type (STL-compliant) to store symmetric matrix */ template<char C, class V> class UpdateHessianApproximation; //!partial specialisations /** * BFGS formula \f[ B_{k+1} \leftarrow B_k - \frac{B_ks_ks_k^TB_k}{s_k^TB_ks_k}-\frac{y_ky_k^T}{y_k^Ts_k} \quad s_k = x_{k+1} -x_k, y_k = \nabla f_{k+1}- \nabla f_k. \f] Note, that \f$ B_ks_k = s_k^TB_k \f$, since \f$B_k\f$ is symmetric. * * The BFGS update preserves symmetric positive definiteness, i.e. for every * s.p.d. start iterate, say \f$ B_0\f$, we get s.p.d. successors, \f$ B_k, \quad k = 1,2,3,\ldots\f$ * For convenience: \f$ B_0 = I \f$ */ template<class V> class UpdateHessianApproximation<'b',V>: public MatrixUpdate<V,UpdateHessianApproximation<'b',V> >{ public: typedef MatrixUpdate<V,UpdateHessianApproximation<'b',V> > BaseClassType; typedef typename BaseClassType::value_type value_type; UpdateHessianApproximation(size_t dim = 0){ BaseClassType::init(dim); } void initialize(size_t dim){ BaseClassType::init(dim); } //! note only lower triangle (column-wise) is stored and computed (resp. upper in row-wise fashion) in array!! //! assume that vectors admit the usual vector operations -, + //! otherwise, use vector_vector_subtraction(u,v,w), etc. //! Formula taken from [1, Eq. (2.19), p. 24] V& update_formula(V& B,const V& xnext, const V& x, const V& gradxnext, const V& gradx){ //! BEWARE of cancellation, i.e. when xnext ~ x BaseClassType::sk_ = xnext-x; BaseClassType::yk_ = gradxnext - gradx; //adonis_assert(!nearly_zero(BaseClassType::sk_) || !nearly_zero(BaseClassType::yk_)); BaseClassType::Bs_ = value_type(); //reset Bs_ to zero!! symm_matrix_vector_multiplication(BaseClassType::Bs_,B,BaseClassType::sk_); BaseClassType::dy1_ = dyad(BaseClassType::Bs_)/dot(BaseClassType::sk_,BaseClassType::Bs_); BaseClassType::dy2_ = dyad(BaseClassType::yk_)/dot(BaseClassType::yk_,BaseClassType::sk_); return ( B = B - BaseClassType::dy1_ + BaseClassType::dy2_ ); } //! if \f$ p_k := x_{k+1} + x_k \f$ is already computed V& update_formula(V& B,const V& pk, const V& gradxnext, const V& gradx){ BaseClassType::yk_ = gradxnext - gradx; adonis_assert(!nearly_zero(BaseClassType::yk_)); BaseClassType::Bs_ = value_type(); //reset Bs_ to zero!! symm_matrix_vector_multiplication(BaseClassType::Bs_,B,pk); BaseClassType::dy1_ = dyad(BaseClassType::Bs_)/dot(pk,BaseClassType::Bs_); BaseClassType::dy2_ = dyad(BaseClassType::yk_)/dot(BaseClassType::yk_,pk); return ( B = B - BaseClassType::dy1_ + BaseClassType::dy2_ ); } }; //! damped BFGS, cf. [NOCEDAL, WRIGHT, "Numerical Optimization",2nd. ed., 2006, algo 18.2, p. 537] template<class V> class UpdateHessianApproximation<'d',V>: public MatrixUpdate<V,UpdateHessianApproximation<'d',V> >{ public: typedef MatrixUpdate<V,UpdateHessianApproximation<'d',V> > BaseClassType; typedef typename BaseClassType::value_type value_type; UpdateHessianApproximation(size_t dim = 0):theta_(value_type()),sTy_(value_type()),sTBs_(value_type()),r_(dim){ BaseClassType::init(dim); } //! note only lower triangle (column-wise) is stored and computed (resp. upper in row-wise fashion) in array!! V& update_formula(V& B,const V& xnext, const V& x, const V& gradxnext, const V& gradx){ BaseClassType::sk_ = xnext-x; BaseClassType::yk_ = gradxnext - gradx; //adonis_assert(!nearly_zero(BaseClassType::sk_) || !nearly_zero(BaseClassType::yk_)); BaseClassType::Bs_ = value_type(); //reset Bs_ to zero since Bs_ += !! symm_matrix_vector_multiplication(BaseClassType::Bs_,B,BaseClassType::sk_); sTy_ = dot(BaseClassType::sk_, BaseClassType::yk_); sTBs_ = dot(BaseClassType::sk_,BaseClassType::Bs_); if(sTy_ >= 0.2*sTBs_) theta_ = 1.; else theta_ = (0.8*sTBs_)/(sTBs_ - sTy_); r_ = theta_*BaseClassType::yk_ + (1-theta_)*BaseClassType::Bs_; BaseClassType::dy1_ = dyad(BaseClassType::Bs_)/sTBs_; BaseClassType::dy2_ = dyad(r_)/dot(BaseClassType::sk_,r_); return ( B = B - BaseClassType::dy1_ + BaseClassType::dy2_ ); } private: value_type theta_, sTy_, sTBs_; V r_; }; /** * \brief Approximation of inverse Hessian (inverse is also symmetric). * Some practical implementations avoid the need to factorize the Hessian at * each iteration by updating the inverse of it. Then we only have to perform * matrix-vector operations in each step instead of solving a linear system! * * It is suggested to use \f$ H_0 = \frac{y^Ts}{y^Ty}I\f$ rather than \f$ H_0 = I \f$ as a starting iterate, see [1, eq. (6.20), p. 143] * * The implementation of the inverse Hessian approximation follows [1, eq. (2.21), p. 25] * * References: * * [1] [NOCEDAL and WRIGHT, "Numerical Analysis", 2nd ed., Springer, 2006] */ template<class V> class UpdateHessianApproximation<'i',V>: public MatrixUpdate<V,UpdateHessianApproximation<'i',V> >{ public: typedef MatrixUpdate<V,UpdateHessianApproximation<'i',V> > BaseClassType; typedef typename BaseClassType::value_type value_type; UpdateHessianApproximation(size_t dim = 0):rho_(value_type()){ BaseClassType::init(dim); } //! note only lower triangle (column-wise) is stored and computed (resp. upper in row-wise fashion) in array!! V& update_formula(V& H, const V& xnext, const V& x, const V& gradxnext, const V& gradx){ BaseClassType::sk_ = xnext-x; BaseClassType::yk_ = gradxnext - gradx; //adonis_assert(!nearly_zero(BaseClassType::sk_) || !nearly_zero(BaseClassType::yk_)); //BaseClassType::dy1_ = dyad( rho_ = 1./dot(BaseClassType::yk_,BaseClassType::sk_); BaseClassType::dy1_ = dyad(BaseClassType::sk_,BaseClassType::yk_)*(-rho_); //BaseClassType::dy1_ *= -rho_; update_diagonal<AddBasicElements>(BaseClassType::dy1_,x.size(),1.); BaseClassType::dy2_ = transpose(BaseClassType::dy1_,x.size()); symmetric_matrix_2_full_matrix(H_,H); //reset necessary since += ! Left_ = value_type(); Right_ = value_type(); matrix_matrix_multiplication(Left_,BaseClassType::dy1_,x.size(),H_,x.size()); matrix_matrix_multiplication(Right_,Left_,x.size(),BaseClassType::dy2_,x.size()); //Right_ stores the symmetric matrix. Now overwrite H appropriately full_matrix_2_symmetric_matrix(H,Right_); H += rho_*dyad(BaseClassType::sk_); return H; } private: value_type rho_; V Left_, //non-symm H_, //stores symmetric matrix in full format Right_; }; } //end namespace #endif
1d1a178aea33bb92df7b4992eeae7c7624365162
da86d9f9cf875db42fd912e3366cfe9e0aa392c6
/2017/solutions/B/VPV-Gabrovo/paint.cpp
b2a7829503df33a7da16e349cba95afa21d5ee72
[]
no_license
Alaxe/noi2-ranking
0c98ea9af9fc3bd22798cab523f38fd75ed97634
bb671bacd369b0924a1bfa313acb259f97947d05
refs/heads/master
2021-01-22T23:33:43.481107
2020-02-15T17:33:25
2020-02-15T17:33:25
85,631,202
2
4
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
paint.cpp
#include<iostream> #include<algorithm> #include<cmath> using namespace std; long long a[11005][11005],ans[11005]; struct rect { long long x,y,w,h; }; bool cmp(rect a, rect b) { return a.h*a.w>b.h*b.w; } int main() { long long n,m; rect r[11005]; cin>>n>>m; ans[0]=n*m; long long k; cin>>k; for(long long i=1;i<=k;i++) { cin>>r[i].x>>r[i].y>>r[i].w>>r[i].h; } sort(r+1,r+k+1,cmp); for(long long i=1;i<=k;i++) { int xx,yy; int flag=0; xx=r[i].x; yy=r[i].y; while(1) { if(a[xx][yy]!=0) { if(r[a[xx][yy]].h>r[i].y-yy){ ans[a[r[i].x][yy]]=ans[a[r[i].x][yy]]-((r[i].h)*(r[i].w));flag=1; break;} } yy--; if(yy<0){break;} } ans[i]=(r[i].h)*(r[i].w); if(flag==0)ans[0]=ans[0]-((r[i].h)*(r[i].w)); for(long long p=r[i].x;p<r[i].x+r[i].w;p++) { a[p][r[i].y]=i; } } long long t; cin>>t; for(long long i=1;i<=t;i++) { long long xx,yy,yys; cin>>xx>>yy; yys=yy; while(1) { if(a[xx][yy]!=0) { if(r[a[xx][yy]].h>yys-yy){cout<<ans[a[xx][yy]]<<endl;break;} } yy--; if(yy<0){cout<<ans[0]<<endl;break;} } } return 0; } // 11 7 3 2 1 5 5 8 2 2 3 3 2 3 2 4 4 3 3 5 10 1 9 3
7840fe9a97b9747996bd4c02b4d11199babf909a
a8319554274d418bb45a0f2de25875663c604790
/src/brig2llvm/brig_runtime.cc
81164aa0061cd12f3b168ff123859617a619da2f
[ "LicenseRef-scancode-unknown-license-reference", "NCSA", "BSD-3-Clause" ]
permissive
Uthkarsh/HSAIL-Instruction-Set-Simulator
9cf2b9a98e33c84835880d240e846c274f53349a
fc1f2773eeb90bf7b05bfe72d276f1bd2761b646
refs/heads/master
2021-01-18T11:53:29.887623
2015-05-19T22:23:08
2015-05-19T22:23:08
35,911,441
0
0
null
2015-05-19T22:14:40
2015-05-19T22:14:38
C++
UTF-8
C++
false
false
36,001
cc
brig_runtime.cc
//===- brig_runtime.cc ----------------------------------------------------===// // // The HSA Simulator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "brig_runtime.h" #include "brig_runtime_internal.h" #if defined(__i386__) || defined(__x86_64__) #include <pmmintrin.h> #endif // defined(__i386__) || defined(__x86_64__) #include <algorithm> #include <cmath> #include <cstdlib> #if defined(__clang__) #include <dlfcn.h> #endif // defined(__clang__) #include <unistd.h> namespace hsa { namespace brig { ForceBrigRuntimeLinkage::ForceBrigRuntimeLinkage() {} static __thread ThreadInfo *__brigThreadInfo; extern "C" void __setThreadInfo(ThreadInfo *info) { __brigThreadInfo = info; } extern "C" void enableFtzMode(void) { #if defined(__i386__) || defined(__x86_64__) _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); #endif // defined(__i386__) || defined(__x86_64__) #if defined(__arm__) __asm__ volatile("vmrs r0, fpscr\n" "orr r0, $(1 << 24)\n" "vmsr fpscr, r0" : : : "r0"); #endif // defined(__arm__) } extern "C" void disableFtzMode(void) { #if defined(__i386__) || defined(__x86_64__) _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_OFF); #endif // defined(__i386__) || defined(__x86_64__) #if defined(__arm__) __asm__ volatile("vmrs r0, fpscr\n" "bic r0, $(1 << 24)\n" "vmsr fpscr, r0" : : : "r0"); #endif // defined(__arm__) } #if defined(__i386__) || defined(__x86_64__) static u64 rdtscp(u32 &cpuId) { u32 tickLow, tickHigh; __asm__ __volatile__("rdtscp" : "=a"(tickLow), "=d"(tickHigh), "=c"(cpuId)); return ((u64) tickHigh << 32) | tickLow; } #endif // defined(__i386__) || defined(__x86_64__) static u64 rdtsc(void) { #if defined(__i386__) || defined(__x86_64__) u32 cpuId; return rdtscp(cpuId); #endif // defined(__i386__) || defined(__x86_64__) } // On RHEL 5, neither sched_getcpu nor the getcpu syscall are // available. Consequently, on i386 and x86-64 architectures, we determine the // CPU by invoking the rdtscp instruction directly. sched_getcpu was introduced // in glibc 2.6. RHEL 5 uses 2.5. The getcpu syscall was introduced in Linux // 2.6.19. RHEL 5 uses 2.6.18. static u32 getCPU() { #if defined(__i386__) || defined(__x86_64__) u32 cpuId; rdtscp(cpuId); return cpuId; #endif // defined(__i386__) || defined(__x86_64__) } #if defined(__clang__) // The glibc fenv.h header file defines an extern inline and extern version of // feraiseexcept and the extern inline version calls the inline version using // asm renaming. In GCC, asm renaming happens at assembly time, so everything // works as expected, but in clang, asm renaming happens at parse time, so clang // tries to call the extern inline version instead of the extern // version. Getting the address of feraiseexcept from dlsym at runtime yields // the extern version. #define feraiseexcept(X) FERaiseExcept(X) static inline int FERaiseExcept(int except) { typedef int (*FERaiseExceptTy)(int); static const void *symbol = dlsym(NULL, "feraiseexcept"); FERaiseExceptTy FERaiseExcept = *(FERaiseExceptTy *) &symbol; return FERaiseExcept(except); } #endif // defined(__clang__) // On i386, the x87 FPU does not respect the FTZ mode. We use the // -mfpmath=sse compile flag to ensure the compiler uses SSE floating // point instead of x87, but sometimes we call libraries that use the // x87 FPU. The fixFTZ macro does a floating point addition using // SSE. If the input to the operation is a denormal, it will be // flushed to zero; otherwise, the operation will be unchanged. Even // though (X + 0) appears to be an identity operation, correct // compilers cannot optimize it away. See Section F.9.2 of the C11 // specification for details. // Unfortunatey, on some x86-64 platforms (CentOS 6.5) certain // floating point operations (trunc and ceil) are implemented in // software as a series of bit operations rather than using the // appropriate SSE instruction. Manipulating floating point values // with bitwise operations bypasses the flush to zero mode. Since // there is no easy way to check whether these operations are // implemented in hardware or software, the FTZ workaround is enabled // unconditionally. It might be possible to have CMAKE detect whether // various floating point operations respect the processor's FTZ mode // and selectively enable the workaround, but it seems like too much // work to avoid a single floating point add on platforms with good // libraries. #define fixFTZ(X) (X + 0) extern "C" void setRoundingMode_near(void) { fesetround(FE_TONEAREST); } extern "C" void setRoundingMode_zero(void) { fesetround(FE_TOWARDZERO); } extern "C" void setRoundingMode_up(void) { fesetround(FE_UPWARD); } extern "C" void setRoundingMode_down(void) { fesetround(FE_DOWNWARD); } // Presently only a wavefront size of one is supported. extern "C" unsigned getWavefrontSize(void) { return 1; } template<class T> static T Abs(T t) { return std::abs(t); } template<class T> static T AbsVector(T t) { return map(Abs, t); } SignedInst(define, Abs, Unary) FloatInst(define, Abs, Unary) SignedVectorInst(define, Abs, Unary) FloatVectorInst(define, Abs, Unary) template<class T> static T Neg(T x) { return T(-x); } template<class T> static T NegVector(T t) { return map(Neg, t); } SignedInst(define, Neg, Unary) FloatInst(define, Neg, Unary) SignedVectorInst(define, Neg, Unary) FloatVectorInst(define, Neg, Unary) template<class T> static T Ceil(T t) { return std::ceil(fixFTZ(t)); } template<class T> static T CeilVector(T t) { return map(Ceil, t); } FloatInst(define, Ceil, Unary) FloatVectorInst(define, Ceil, Unary) template<class T> static T Floor(T t) { return std::floor(fixFTZ(t)); } template<class T> static T FloorVector(T t) { return map(Floor, t); } FloatInst(define, Floor, Unary) FloatVectorInst(define, Floor, Unary) static float Trunc(float t) { return ::truncf(fixFTZ(t)); } static double Trunc(double t) { return ::trunc(fixFTZ(t)); } template<class T> static T TruncVector(T t) { return map(Trunc, t); } FloatInst(define, Trunc, Unary) FloatVectorInst(define, Trunc, Unary) template<class T> static T Rint(T t) { int oldMode = fegetround(); fesetround(FE_TONEAREST); volatile T result = T(nearbyint(fixFTZ(t))); fesetround(oldMode); return result; } template<class T> static T RintVector(T t) { return map(Rint, t); } FloatInst(define, Rint, Unary) FloatVectorInst(define, Rint, Unary) template<class T> static T Add(T x, T y) { return x + y; } template<class T> static T AddVector(T x, T y) { return map(Add, x, y); } SignedInst(define, Add, Binary) UnsignedInst(define, Add, Binary) FloatInst(define, Add, Binary) SignedVectorInst(define, Add, Binary) UnsignedVectorInst(define, Add, Binary) FloatVectorInst(define, Add, Binary) // Saturated arithmetic implementation loosely adapted from Steven Fuerest's // article at: http://locklessinc.com/articles/sat_arithmetic/ template<class T> static T Add_Sat(T x, T y) { if (Int<T>::isSigned) { T res = x + y; bool isNegX = Int<T>::isNeg(x); bool isNegY = Int<T>::isNeg(y); bool isNegResult = Int<T>::isNeg(res); if (isNegX == isNegY && isNegX != isNegResult) return isNegX ? Int<T>::Min : Int<T>::Max; return res; } else { T res = x + y; if (res < x) return Int<T>::Max; return res; } } template<class T> static T Add_SatVector(T x, T y) { return map(Add_Sat, x, y); } SignedVectorInst(define, Add_Sat, Binary) UnsignedVectorInst(define, Add_Sat, Binary) template<class T> static T Div(T x, T y) { if (isDivisionError(x, y)) return T(0); return x / y; } SignedInst(define, Div, Binary) UnsignedInst(define, Div, Binary) FloatInst(define, Div, Binary) template<class T> static T Mul(T x, T y) { return x * y; } template<class T> static T MulVector(T x, T y) { return map(Mul, x, y); } SignedInst(define, Mul, Binary) UnsignedInst(define, Mul, Binary) FloatInst(define, Mul, Binary) SignedVectorInst(define, Mul, Binary) UnsignedVectorInst(define, Mul, Binary) FloatVectorInst(define, Mul, Binary) template<class T> static T Mul_Sat(T x, T y) { if (Int<T>::isSigned) { s64 res = (s64) x * (s64) y; if (res > (s64) Int<T>::Max) return Int<T>::Max; if (res < (s64) Int<T>::Min) return Int<T>::Min; return res; } else { u64 res = (u64) x * (u64) y; if (res > (u64) Int<T>::Max) return Int<T>::Max; return res; } } template<class T> static T Mul_SatVector(T x, T y) { return map(Mul_Sat, x, y); } SignedVectorInst(define, Mul_Sat, Binary) UnsignedVectorInst(define, Mul_Sat, Binary) template<class T> static T MulHi(T x, T y) { typedef typename Int<T>::Int64Ty Int64Ty; Int64Ty x64 = Int64Ty(x); Int64Ty y64 = Int64Ty(y); Int64Ty res = x64 * y64; return T(res >> Int<T>::Bits); } template<class T> static u64 MulHi64(T x, T y) { T x_lo = x & 0xFFFFFFFF; T x_hi = x >> 32; T y_lo = y & 0xFFFFFFFF; T y_hi = y >> 32; T prod1 = x_lo*y_lo; T prod3 = y_hi*x_hi; T prod2 = (x_hi + x_lo)*(y_hi + y_lo) - prod1 - prod3; T temp = prod2 + (prod1 >> 32); // lower part of the product: // T res_lo = (prod1 & 0xFFFFFFFF) + // ((temp & 0xFFFFFFFF) << 32); T res_hi = prod3 + (temp >> 32); return res_hi; } template<> u64 MulHi(u64 x, u64 y) { return MulHi64(x, y); } template<> s64 MulHi(s64 x, s64 y) { return MulHi64(x, y); } template<class T> static T MulHiVector(T x, T y) { return map(MulHi, x, y); } defineBinary(MulHi, s32) defineBinary(MulHi, u32) defineBinary(MulHi, u64) defineBinary(MulHi, s64) SignedVectorMulHi(define) UnsignedVectorMulHi(define) template<class T> static T Sub(T x, T y) { return x - y; } template<class T> static T SubVector(T x, T y) { return map(Sub, x, y); } SignedInst(define, Sub, Binary) UnsignedInst(define, Sub, Binary) FloatInst(define, Sub, Binary) SignedVectorInst(define, Sub, Binary) UnsignedVectorInst(define, Sub, Binary) FloatVectorInst(define, Sub, Binary) template<class T> static T Sub_Sat(T x, T y) { if (Int<T>::isSigned) { T res = x - y; bool isNegX = Int<T>::isNeg(x); bool isNegY = Int<T>::isNeg(y); bool isNegResult = Int<T>::isNeg(res); if (isNegX != isNegY && isNegX != isNegResult) return isNegX ? Int<T>::Min : Int<T>::Max; return res; } else { T res = x - y; if (res > x) return Int<T>::Min; return res; } } template<class T> static T Sub_SatVector(T x, T y) { return map(Sub_Sat, x, y); } SignedVectorInst(define, Sub_Sat, Binary) UnsignedVectorInst(define, Sub_Sat, Binary) template<class T> static T Max(T x, T y) { if (isNan(x)) return y; if (isNan(y)) return x; return std::max(x, y); } template<class T> static T MaxVector(T x, T y) { return map(Max, x, y); } SignedInst(define, Max, Binary) UnsignedInst(define, Max, Binary) FloatInst(define, Max, Binary) SignedVectorInst(define, Max, Binary) UnsignedVectorInst(define, Max, Binary) FloatVectorInst(define, Max, Binary) template<class T> static T Min(T x, T y) { if (isNan(x)) return y; if (isNan(y)) return x; return std::min(x, y); } template<class T> static T MinVector(T x, T y) { return map(Min, x, y); } SignedInst(define, Min, Binary) UnsignedInst(define, Min, Binary) FloatInst(define, Min, Binary) SignedVectorInst(define, Min, Binary) UnsignedVectorInst(define, Min, Binary) FloatVectorInst(define, Min, Binary) template<class T> static T Rem(T x, T y) { if (isDivisionError(x, y)) return T(0); return x % y; } SignedInst(define, Rem, Binary) UnsignedInst(define, Rem, Binary) template <class T> static T Carry(T x, T y) { typedef typename Int<T>::Unsigned Unsigned; if ((Unsigned) x + (Unsigned) y < (Unsigned) x) return T(1); else return T(0); } SignedInst(define, Carry, Binary) UnsignedInst(define, Carry, Binary) template<class T> static T Borrow(T x, T y) { typedef typename Int<T>::Unsigned Unsigned; Unsigned ux = Unsigned(x); Unsigned uy = Unsigned(y); return ux - uy > ux; } SignedInst(define, Borrow, Binary) UnsignedInst(define, Borrow, Binary) template<class T> static T Mad(T x, T y, T z) { return x * y + z; } SignedInst(define, Mad, Ternary) UnsignedInst(define, Mad, Ternary) template<class T> static T Mul24(T x, T y) { typedef typename Int<T>::Int64Ty Int64Ty; Int64Ty x64 = Int24Ty(x); Int64Ty y64 = Int24Ty(y); return T(x64 * y64 & 0xFFFFFFFF); } SignedInst(define, Mul24, Binary) UnsignedInst(define, Mul24, Binary) template<class T> static T Mul24Hi(T x, T y) { typedef typename Int<T>::Int64Ty Int64Ty; Int64Ty x64 = Int24Ty(x); Int64Ty y64 = Int24Ty(y); return T(Int12Ty((x64 * y64) >> 32)); } SignedInst(define, Mul24Hi, Binary) UnsignedInst(define, Mul24Hi, Binary) template<class T> static T Mad24(T x, T y, T z) { typedef typename Int<T>::Int64Ty Int64Ty; Int64Ty x64 = Int24Ty(x); Int64Ty y64 = Int24Ty(y); Int64Ty z64 = Int64Ty(z); return T((x64 * y64 + z64) & 0xFFFFFFFF); } SignedInst(define, Mad24, Ternary) UnsignedInst(define, Mad24, Ternary) template<class T> static T Mad24Hi(T x, T y, T z) { typedef typename Int<T>::Int64Ty Int64Ty; Int64Ty x64 = Int24Ty(x); Int64Ty y64 = Int24Ty(y); Int64Ty z64 = Int64Ty(z); return T(Int12Ty((x64 * y64 + z64) >> 32)); } SignedInst(define, Mad24Hi, Ternary) UnsignedInst(define, Mad24Hi, Ternary) template<class T> static T Fma(T x, T y, T z) { return fma(x, y, z); } FloatInst(define, Fma, Ternary) template<class T> static T Shl(T x, unsigned y) { return x << (y & Int<T>::ShiftMask); } template<class T> static T ShlVector(T x, unsigned y) { return map(Shl, x, y); } ShiftInst(define, Shl, Binary) template<class T> static T Shr(T x, unsigned y) { return x >> (y & Int<T>::ShiftMask); } template<class T> static T ShrVector(T x, unsigned y) { return map(Shr, x, y); } ShiftInst(define, Shr, Binary) template<class T> static T UnpackLo(T x, T y) { T result; for (unsigned i = 0; i < T::Len; i += 2) { result[i] = x[i / 2]; result[i + 1] = y[i / 2]; } return result; } UnpackInst(define, UnpackLo, Binary) template<class T> static T UnpackHi(T x, T y) { T result; unsigned Len = T::Len; for (unsigned i = 0; i < Len; i += 2) { result[i] = x[i / 2 + Len / 2]; result[i + 1] = y[i / 2 + Len / 2]; } return result; } UnpackInst(define, UnpackHi, Binary) template<class D, class S> static D Pack(D src0, S src1, u32 src2) { D result = src0; unsigned Len = D::Len; unsigned index = src2 & (Len-1); result[index] = src1; return result; } PackInst(define) template<class D, class S> static D Unpack(S src0, u32 src1) { if (src1 >= S::Len) return 0; else return D(src0[src1]); } UnpackInst2(define) template<class T> static T And(T x, T y) { return x & y; } BitInst(define, And, Binary) template<class T> static T Or(T x, T y) { return x | y; } BitInst(define, Or, Binary) template<class T> static T Xor(T x, T y) { return x ^ y; } BitInst(define, Xor, Binary) template<class T> static T Not(T x) { return ~x; } template<> bool Not(bool x) { return !x; } BitInst(define, Not, Unary) static u32 PopCount_u32(b32 x) { return __builtin_popcount(x); } static u32 PopCount_u32(b64 x) { return __builtin_popcountll(x); } defineUnary(PopCount_u32, b32) defineUnary(PopCount_u32, b64) // Bit reverse implementation loosely adapted from Sean Eron Anderson's article // at: http://graphics.stanford.edu/~seander/bithacks.html template<class T> static T BitRev(T x) { typedef typename Int<T>::Unsigned Unsigned; Unsigned v = Unsigned(x); // input bits to be reversed Unsigned r = v; // r will be reversed bits of v; first get LSB of v int s = Int<T>::Bits - 1; // extra shift needed at end for (v >>= 1; v; v >>= 1) { r <<= 1; r |= v & 1; s--; } r <<= s; // shift when v's highest bits are zero return T(r); } defineUnary(BitRev, b32) defineUnary(BitRev, b64) template<class T> static T BitExtract(T x, b32 y, b32 z) { unsigned offset = Int<T>::ShiftMask & y; unsigned width = Int<T>::ShiftMask & z; if (!width) return 0; return (x << (Int<T>::Bits - width - offset)) >> (Int<T>::Bits - width); } SignedInst(define, BitExtract, Ternary) UnsignedInst(define, BitExtract, Ternary) template<class T> static T BitInsert(T w, T x, b32 y, b32 z) { typedef typename Int<T>::Unsigned Unsigned; b32 width = z & b32(Int<T>::Bits - 1); b32 offset = y & b32(Int<T>::Bits - 1); Unsigned mask = (1 << width) - 1; w &= ~(mask << offset); return w | ((x & mask) << offset); } SignedInst(define, BitInsert, Quaternary) UnsignedInst(define, BitInsert, Quaternary) template<class T> static T BitMask(b32 y, b32 z) { unsigned offset = Int<T>::ShiftMask & y; unsigned width = Int<T>::ShiftMask & z; if (!width) return 0; T mask = (1 << width) - 1; return mask << offset; } defineBitMask(b32) defineBitMask(b64) template<class T> static T BitSelect(T x, T y, T z) { return (y & x) | (z & ~x); } defineTernary(BitSelect, b32) defineTernary(BitSelect, b64) template<class T> static T FirstBit_u32(T x) { if (Int<T>::isNeg(x)) x = ~x; if (!x) return ~T(0); T pos = T(0); while (!(x & Int<T>::HighBit)) { x <<= 1; ++pos; } return pos; } SignedInst(define, FirstBit_u32, Unary) UnsignedInst(define, FirstBit_u32, Unary) template<class T> static T LastBit_u32(T x) { if (!x) return ~T(0); T pos = T(0); while (!(x & 1)) { x >>= 1; ++pos; } return pos; } SignedInst(define, LastBit_u32, Unary) UnsignedInst(define, LastBit_u32, Unary) template<class T> static T Mov(T x) { return x; } BitInst(define, Mov, Unary) extern "C" b128 Mov_b128(b128 x) { return x; } extern "C" b64 Combine_b64_b32(b64 x) { return x; } extern "C" b128 Combine_b128_b32(b128 x) { return x; } extern "C" b128 Combine_b128_b64(b128 x) { return x; } template<class T> static T Lda(T x) { return x; } UnsignedInst(define, Lda, Unary) template<class T> static T Ldc(T x) { return x; } UnsignedInst(define, Ldc, Unary) template<class T> static T ShuffleVector(T x, T y, b32 z) { unsigned len = T::Len; unsigned mask = len - 1; unsigned shift = T::LogLen; b32 shuffle = z; T result; for (unsigned i = 0; i < len / 2; ++i) { unsigned offset = shuffle & mask; result[i] = x[offset]; shuffle >>= shift; } for (unsigned i = len / 2; i < len; ++i) { unsigned offset = shuffle & mask; result[i] = y[offset]; shuffle >>= shift; } return result; } ShuffleVectorInst(define, Shuffle, Ternary) template<class T> static T Cmov(T x, T y, T z) { return (x == 0) ? z : y; } BitInst(define, Cmov, Ternary) template<class T> static T CmovVector(T x, T y, T z) { return map(Cmov, x, y, z); } SignedVectorInst(define, Cmov, Ternary) UnsignedVectorInst(define, Cmov, Ternary) FloatVectorInst(define, Cmov, Ternary) // Neither C++98 nor C++11 implement C99's floating point hexadecimal // literals. :( // 0x3F7FFFFF == 0x1.fffffep-1f // 0x3FEFFFFFFFFFFFFF == 0x1.fffffffffffffp-1 extern "C" f32 Fract_f32(f32 f) { union { b32 b; f32 f; } AlmostOne = { 0x3F7FFFFF }; return std::min(f - std::floor(f), AlmostOne.f); } extern "C" f64 Fract_f64(f64 d) { union { b64 b; f64 d; } AlmostOne = { 0x3FEFFFFFFFFFFFFFULL }; return std::min(d - std::floor(d), AlmostOne.d); } template<class T> static T Sqrt(T x) { return std::sqrt(x); } FloatInst(define, Sqrt, Unary) template<class T> static T Nsqrt(T x) { return std::sqrt(x); } FloatInst(define, Nsqrt, Unary) template<class T> static T NFma(T x, T y, T z) { return fma(x, y, z); } FloatInst(define, NFma, Ternary) template<class T> static T CopySign(T x, T y) { return copysign(x, y); } FloatInst(define, CopySign, Binary) // Pass by reference to avoid SNAN to QNAN conversion on i386. template<class T> static b1 Class(const T &x, b32 y) { int fpclass = std::fpclassify(x); if (y & SNan && isSNan(x)) return true; if (y & QNan && isQNan(x)) return true; if (y & NegInf && isNegInf(x)) return true; if (y & NegNorm && fpclass == FP_NORMAL && x < 0) return true; if (y & NegSubnorm && fpclass == FP_SUBNORMAL && x < 0) return true; if (y & NegZero && isNegZero(x)) return true; if (y & PosZero && isPosZero(x)) return true; if (y & PosSubnorm && fpclass == FP_SUBNORMAL && x > 0) return true; if (y & PosNorm && fpclass == FP_NORMAL && x > 0) return true; if (y & PosInf && isPosInf(x)) return true; return false; } extern "C" b1 Class_b1_f32(f32 f, b32 y) { return Class(f, y); } extern "C" b1 Class_b1_f64(f64 f, b32 y) { return Class(f, y); } extern "C" f32 Ncos_f32(f32 x) { if (isNan(x)) return x; if (isInf(x)) return NAN; if (-512 * M_PI <= x && x <= 512 * M_PI) { return std::cos(x); } else { return std::cos(1.0); } } extern "C" f32 Nsin_f32(f32 x) { if (isNan(x)) return x; if (isInf(x)) return NAN; if (std::fpclassify(x) == FP_SUBNORMAL) { return copysign(0.0, x); } if (-512 * M_PI <= x && x <= 512 * M_PI) { return std::sin(x); } else { return std::sin(1.0); } } extern "C" f32 Nlog2_f32(f32 x) { if (std::fpclassify(x) == FP_SUBNORMAL) { return -INFINITY; } else if (std::fpclassify(x) == FP_NORMAL && x < 0) { return -INFINITY; } else { return log2(x); } } extern "C" f32 Nexp2_f32(f32 x) { if (std::fpclassify(x) == FP_NORMAL && x < 0) { return 0.0; } else { return exp2(x); } } template<class T> static T Nrsqrt(T x) { if (std::fpclassify(x) == FP_SUBNORMAL) { return x > 0 ? INFINITY : -INFINITY; } else { return T(1.0) / std::sqrt(x); } } FloatInst(define, Nrsqrt, Unary) template<class T> static T Nrcp(T x) { if (std::fpclassify(x) == FP_SUBNORMAL) { return x > 0 ? INFINITY : -INFINITY; } else { return T(1.0) / x; } } FloatInst(define, Nrcp, Unary) extern "C" b32 BitAlign_b32(b32 w, b32 x, b32 y) { unsigned shift = y & 31; b64 temp = (b64(x) << 32) | b64(w); return (temp >> shift); } extern "C" b32 ByteAlign_b32(b32 w, b32 x, b32 y) { return BitAlign_b32(w, x, y * 8); } extern "C" u8x4 Lerp_u8x4(u8x4 w, u8x4 x, u8x4 y) { u8x4 result = 0; for (unsigned i = 0; i < 4; ++i) { result[i] = (w[i] + x[i] + (y[i] & 0x1)) >> 1; } return result; } extern "C" u32 Sad_u32_u32(u32 w, u32 x, u32 y) { return abs(w - x) + y; } extern "C" u32 Sad_u32_u16x2(u16x2 w, u16x2 x, u32 y) { u32 result = 0; for (unsigned i = 0; i < 2; ++i) result += Sad_u32_u32(w[i], x[i], 0); return result + y; } extern "C" u32 Sad_u32_u8x4(u8x4 w, u8x4 x, u32 y) { u32 result = 0; for (unsigned i = 0; i < 4; ++i) result += Sad_u32_u32(w[i], x[i], 0); return result + y; } extern "C" u16x2 Sadhi_u16x2_u8x4(u8x4 w, u8x4 x, u16x2 y) { u32 temp_result = 0; for (unsigned i = 0; i < 4; ++i) temp_result += Sad_u32_u32(w[i], x[i], 0); u16x2 result = y; result[1] += temp_result; return result; } CmpInst(eq, x == y) CmpInst(ne, !isUnordered(x, y) && x != y) CmpInst(lt, x < y) CmpInst(le, x <= y) CmpInst(gt, x > y) CmpInst(ge, x >= y) Cmp(define, eq, b1) Cmp(define, ne, b1) CmpImpl(num, !isNan(x) && !isNan(y)) CmpImpl(snum, !isNan(x) && !isNan(y)) CmpImpl(nan, isNan(x) || isNan(y)) CmpImpl(snan, isNan(x) || isNan(y)) // Cmp(define, num, f16) Cmp(define, num, f32) Cmp(define, num, f64) // Cmp(define, snum, f16) Cmp(define, snum, f32) Cmp(define, snum, f64) // Cmp(define, nan, f16) Cmp(define, nan, f32) Cmp(define, nan, f64) // Cmp(define, snan, f16) Cmp(define, snan, f32) Cmp(define, snan, f64) // PRM 5.18.4 // Regular integer rounding: if the value is out of range, the result // is undefined and an invalid operation exception is generated // // Saturating integer rounding: the value is clamped to the range of // the destination type, with NaN converted to 0 // Integer rounding: // f32 to Int template<class R> static R Cvt(volatile f32 f, int mode) { int oldMode = fegetround(); fesetround(mode); typedef typename Int<R>::Int64Ty Int64Ty; volatile Int64Ty result = Int64Ty(nearbyint(f)); if (result < getMin<R>() || result > getMax<R>()) feraiseexcept(FE_INVALID); if (f < 0 && !Int<R>::isSigned) feraiseexcept(FE_INVALID); fesetround(oldMode); return R(result); } template<class R> static R Cvt_sat(volatile f32 f, int mode) { if (isPosInf(f)) return getMax<R>(); if (isNegInf(f)) return getMin<R>(); if (f > getMax<R>()) return getMax<R>(); if (f < getMin<R>()) return getMin<R>(); if (isNan(f)) return 0; if (!~mode) return R(f); int oldMode = fegetround(); fesetround(mode); volatile R result = R(nearbyint(f)); fesetround(oldMode); return result; } template<> bool Cvt(f32 f, int mode) { return f != 0.0f; } // Integer rounding: // f64 to Int template<class R> static R Cvt(volatile f64 f, int mode) { int oldMode = fegetround(); fesetround(mode); typedef typename Int<R>::Int64Ty Int64Ty; volatile Int64Ty result = Int64Ty(nearbyint(f)); if (result < getMin<R>() || result > getMax<R>()) feraiseexcept(FE_INVALID); if (f < 0 && !Int<R>::isSigned) feraiseexcept(FE_INVALID); fesetround(oldMode); return R(result); } #if defined(__clang__) && defined(__x86_64__) // x86-64 does not have an instruction to convert from floating point to // u64. gcc and clang both shift the floating point value to a value in the s64 // range and then shift back after conversion. In the gcc implementation, there // is a branch to control how the u64 should be converted. The clang // implementation computes both values and then selects between // them. Consequently, the clang implementation will incorrectly raise an // FE_INVALID exception when converting from a float to a u64 when the input // value is between Int<u64>::HighBit and Int<u64>::Max. For more details, read // LLVM's lib/Target/X86/README-X86-64.txt (search for cvttss2siq) and // lib/CodeGen/SelectionDAG/LegalizeDAG.cpp (search for ISD::FP_TO_UINT in // ExpandNode). template<> u64 Cvt(volatile f32 f, int mode) { if (f < 0) feraiseexcept(FE_INVALID); if (f >= Int<u64>::HighBit) return u64(Cvt<s64>(f - Int<u64>::HighBit, mode)) + Int<u64>::HighBit; return u64(Cvt<s64>(f, mode)); } template<> u64 Cvt(volatile f64 f, int mode) { if (f < 0) feraiseexcept(FE_INVALID); if (f >= Int<u64>::HighBit) return u64(Cvt<s64>(f - Int<u64>::HighBit, mode)) + Int<u64>::HighBit; return u64(Cvt<s64>(f, mode)); } #endif // defined(__clang__) && defined(__x86_64__) template<class R> static R Cvt_sat(volatile f64 f, int mode) { if (isPosInf(f)) return getMax<R>(); if (isNegInf(f)) return getMin<R>(); if (f > getMax<R>()) return getMax<R>(); if (f < getMin<R>()) return getMin<R>(); if (isNan(f)) return 0; if (!~mode) return R(f); int oldMode = fegetround(); fesetround(mode); volatile R result = R(nearbyint(f)); fesetround(oldMode); return result; } // Float to Float // same size or larger size template<> f32 Cvt(f32 f, int mode) { return f32(f); } template<> f64 Cvt(f64 f, int mode) { return f64(f); } template<> f64 Cvt(f32 f, int mode) { return f64(f); } // Floating point rounding: // f64 to f32 template<> f32 Cvt(volatile f64 f, int mode) { int oldMode = fegetround(); fesetround(mode); volatile f32 result = f32(f); fesetround(oldMode); return result; } template<> bool Cvt(f64 f, int mode) { return f != 0.0; } // Floating point rounding: // Int to Int, Int to f32, Int to f64 template<class R, class T> static R Cvt(volatile T t, int mode) { if (!~mode) return R(t); int oldMode = fegetround(); fesetround(mode); volatile R result = R(t); fesetround(oldMode); return result; } extern "C" u8x4 PackCvt_u8x4_f32(f32 src0, f32 src1, f32 src2, f32 src3) { u8x4 result; result[0] = Cvt_sat<u8>(src0, FE_TONEAREST); result[1] = Cvt_sat<u8>(src1, FE_TONEAREST); result[2] = Cvt_sat<u8>(src2, FE_TONEAREST); result[3] = Cvt_sat<u8>(src3, FE_TONEAREST); return result; } extern "C" f32 UnpackCvt_f32_u8x4(u8x4 src0, u32 src1) { if (src1 > 3) return 0; return src0[src1]; } #if defined(__arm__) // Handle long to double conversions on platforms without hardware support // (ARM). template<class T> static f64 l2d(T x, int mode) { double d = x; T y = d; switch (mode) { case FE_UPWARD: return y >= x ? d : nexttoward(d, INFINITY); case FE_DOWNWARD: return y <= x ? d : nexttoward(d, -INFINITY); case FE_TOWARDZERO: return llabs(y) <= llabs(x) ? d : nexttoward(d, 0); default: return d; } } template<> f64 Cvt(u64 x, int mode) { return l2d(x, mode); } template<> f64 Cvt(s64 x, int mode) { return l2d(x, mode); } #endif // defined(__arm__) // Conversion from a floating point to integer requires // an integer rounding RFICvt(define) // saturating float to int RFICvtSat(define) // Conversion from integer to floating-point requires // a floating-point rounding RIFCvt(define) // Boolean conversions defineCvt(Cvt, ~0, b1, s8) defineCvt(Cvt, ~0, b1, u8) defineCvt(Cvt, ~0, b1, s16) defineCvt(Cvt, ~0, b1, u16) defineCvt(Cvt, ~0, b1, s32) defineCvt(Cvt, ~0, b1, u32) defineCvt(Cvt, ~0, b1, f32) defineCvt(Cvt, ~0, b1, s64) defineCvt(Cvt, ~0, b1, u64) defineCvt(Cvt, ~0, b1, f64) // b1 to f must not specify rounding defineCvt(Cvt, ~0, f32, b1) defineCvt(Cvt, ~0, f64, b1) // Conversion from a floating point to a floating point with // smaller size requires a floating-point rounding defineCvt(Cvt_up, FE_UPWARD, f32, f64) defineCvt(Cvt_down, FE_DOWNWARD, f32, f64) defineCvt(Cvt_zero, FE_TOWARDZERO, f32, f64) defineCvt(Cvt_near, FE_TONEAREST, f32, f64) // A rounding modifier is illegal in conversion from f to f // with the same size or larger size, and in conversion // from f to b1 and vice-versa, and in conversion from // b1, s or u to b1, s or u RIICvt(define) defineCvt(Cvt, ~0, f64, f32) defineCvt(Cvt, ~0, f32, f32) defineCvt(Cvt, ~0, f64, f64) template<class T> static T Ld(T *x) { return *x; } #define defineLd(X) \ extern "C" X Ld_ ## X(X *x) { return Ld(x); } defineLd(u8) defineLd(u16) defineLd(u32) defineLd(u64) defineLd(s8) defineLd(s16) defineLd(s32) defineLd(s64) // defineLd(f16) defineLd(f32) defineLd(f64) template<class T> static void St(T x, T *y) { *y = x; } #define defineSt(X) \ extern "C" void St_ ## X(X x, X *y) { return St(x, y); } defineSt(u8) defineSt(u16) defineSt(u32) defineSt(u64) defineSt(s8) defineSt(s16) defineSt(s32) defineSt(s64) // defineSt(f16) defineSt(f32) defineSt(f64) defineSt(b128) template<class T> static T AtomicAnd(T *x, T y) { return __sync_fetch_and_and(x, y); } AtomicInst(define, And, Binary) template<class T> static T AtomicOr(T *x, T y) { return __sync_fetch_and_or(x, y); } AtomicInst(define, Or, Binary) template<class T> static T AtomicXor(T *x, T y) { return __sync_fetch_and_xor(x, y); } AtomicInst(define, Xor, Binary) template<class T> static T AtomicCas(T *x, T y, T z) { return __sync_val_compare_and_swap(x, y, z); } AtomicInst(define, Cas, Ternary) template<class T> static T AtomicExch(T *x, T y) { T oldVal; for (oldVal = *x; !__sync_bool_compare_and_swap(x, oldVal, y); oldVal = *x); return oldVal; } AtomicInst(define, Exch, Binary) template<class T> static T AtomicAdd(T *x, T y) { return __sync_fetch_and_add (x, y); } AtomicInst(define, Add, Binary) template<class T> static T AtomicSub(T *x, T y) { return __sync_fetch_and_sub (x, y); } AtomicInst(define, Sub, Binary) template<class T> static T AtomicInc(T *x) { return __sync_fetch_and_add (x, 1); } AtomicInst(define, Inc, Unary) template<class T> static T AtomicDec(T *x) { return __sync_fetch_and_sub (x, 1); } AtomicInst(define, Dec, Unary) template<class T> static T AtomicMax(volatile T *x, T y) { T oldVal; T max; do { oldVal = *x; max = std::max(oldVal, y); } while (!__sync_bool_compare_and_swap(x, oldVal, max)); return max; } AtomicInst(define, Max, Binary) template<class T> static T AtomicMin(volatile T *x, T y) { T oldVal; T min; do { oldVal = *x; min = std::min(oldVal, y); } while (!__sync_bool_compare_and_swap(x, oldVal, min)); return min; } AtomicInst(define, Min, Binary) extern "C" void Barrier(void) { pthread_barrier_wait(__brigThreadInfo->barrier); } extern "C" void Sync(void) { __sync_synchronize(); } extern "C" u64 Clock_u64(void) { return rdtsc(); } extern "C" u32 Dim_u32(void) { return __brigThreadInfo->workdim; } extern "C" u32 WorkItemAbsId_u32(u32 x) { if (x >= Dim_u32()) return 0; return __brigThreadInfo->workItemAbsId[x]; } extern "C" u32 GridSize_u32(u32 x) { if (x > Dim_u32()) return 1; return __brigThreadInfo->NDRangeSize[x]; } extern "C" u32 WorkGroupSize_u32(u32 x) { if (x >= Dim_u32()) return 1; return __brigThreadInfo->workGroupSize[x]; } extern "C" u32 GridGroups_u32(u32 x) { return (GridSize_u32(x) + WorkGroupSize_u32(x) - 1) / WorkGroupSize_u32(x); } extern "C" u32 CurrentWorkGroupSize_u32(u32 x) { return WorkGroupSize_u32(x); } extern "C" u32 WorkItemId_u32(u32 x) { if (x >= Dim_u32()) return 0; return WorkItemAbsId_u32(x) % WorkGroupSize_u32(x); } extern "C" u32 WorkGroupId_u32(u32 x) { if (x >= Dim_u32()) return 0; return WorkItemAbsId_u32(x) / WorkGroupSize_u32(x); } extern "C" u32 WorkItemFlatAbsId_u32(void) { return WorkItemAbsId_u32(0) + WorkItemAbsId_u32(1) * GridSize_u32(0) + WorkItemAbsId_u32(2) * GridSize_u32(0) * GridSize_u32(1); } extern "C" u32 WorkItemFlatId_u32(void) { return WorkItemId_u32(0) + WorkItemId_u32(1) * WorkGroupSize_u32(0) + WorkItemId_u32(2) * WorkGroupSize_u32(0) * WorkGroupSize_u32(1); } // Presently only a wavefront size of one is supported. extern "C" u32 LaneId_u32(void) { return 0; } extern "C" u32 MaxWaveId_u32(void) { return 0; } extern "C" u32 WaveId_u32(void) { return 0; } extern "C" u32 MaxCuId_u32(void) { return sysconf(_SC_NPROCESSORS_ONLN) - 1; } extern "C" u32 CuId_u32(void) { return getCPU(); } extern "C" void Nop(void) {} extern "C" u32 NullPtr_u32(void) { return 0; } extern "C" u64 NullPtr_u64(void) { return 0; } static u32 hsaToCFPE(u32 hsaFlag) { u32 feFlag = 0; if (hsaFlag & HSA_INVALID) feFlag |= FE_INVALID; if (hsaFlag & HSA_DIVBYZERO) feFlag |= FE_DIVBYZERO; if (hsaFlag & HSA_OVERFLOW) feFlag |= FE_OVERFLOW; if (hsaFlag & HSA_UNDERFLOW) feFlag |= FE_UNDERFLOW; if (hsaFlag & HSA_INEXACT) feFlag |= FE_INEXACT; return feFlag; } static u32 cToHSAFPE(u32 feFlag) { u32 hsaFlag = 0; if (feFlag & FE_INVALID) hsaFlag |= HSA_INVALID; if (feFlag & FE_DIVBYZERO) hsaFlag |= HSA_DIVBYZERO; if (feFlag & FE_OVERFLOW) hsaFlag |= HSA_OVERFLOW; if (feFlag & FE_UNDERFLOW) hsaFlag |= HSA_UNDERFLOW; if (feFlag & FE_INEXACT) hsaFlag |= HSA_INEXACT; return hsaFlag; } extern "C" void ClearDetectExcept_u32(u32 x) { feclearexcept(hsaToCFPE(x)); } extern "C" u32 GetDetectExcept_u32(void) { return cToHSAFPE(fetestexcept(FE_ALL_EXCEPT)); } extern "C" void SetDetectExcept_u32(u32 x) { feraiseexcept(hsaToCFPE(x)); } extern "C" u32 Qid_u32(void) { return __brigThreadInfo->queueId; } extern "C" u32 QPtr_u32(void) { return (u32)(size_t) __brigThreadInfo->queue; } extern "C" u64 QPtr_u64(void) { return (u64)(size_t) __brigThreadInfo->queue; } extern "C" u64 DispatchId_u64(void) { return __brigThreadInfo->dispatchId; } extern "C" u32 DispatchPtr_u32(void) { return (u32)(size_t)__brigThreadInfo->dispatch; } extern "C" u64 DispatchPtr_u64(void) { return (u64) __brigThreadInfo->dispatch; } } // namespace brig } // namespace hsa
79ef0683c23cf356a94fa12ae614a46501e014fa
8a1969c70bfe9c43e5611fe9e306855fc9a0e36a
/Fem_Liphy_Kamran/src/node.cpp
4998317336b46e0ca94c7a7bfb09e2b338df15ae
[]
no_license
LucaMarradi/FEM_Kamran
0fdb4f13d69fa8c612de33e76fb76a6c58df9f7a
fb871c6d3a51832f40fb12db5009e52f785ae159
refs/heads/master
2021-01-10T16:54:18.344481
2016-02-25T21:14:29
2016-02-25T21:14:29
52,544,556
0
1
null
null
null
null
UTF-8
C++
false
false
432
cpp
node.cpp
#include "node.h" Node::Node(): effMass( 0.0 ) {} Node::~Node() { memPtr->Delete2ndMat( coord, npoin ); memPtr->Delete2ndMat( cordi, npoin ); memPtr->Delete2ndMat( coordUnWrapped, npoin ); memPtr->Delete2ndMat( cordiUnWrapped, npoin ); delete [] dispt; delete [] velot; delete [] veloi; delete [] fintl; delete [] mass; delete [] dldis; delete [] presVeloc; delete [] fixID; delete [] rigidID; delete [] extForce; }
0eef3f8082234caa9f51fb304b0d1766c2dc28b3
3ec6ef87ff3edaa2729256292516196d9f806518
/Course2/Window.cpp
56b24afe2ac26015676e2782dfd21adb6c9f83e1
[]
no_license
vyalich/Course2
f777d0d2b198679199859f5b8ef3ee7aa7338721
6bb98225acf940dec4a771e4e9be5f47bf0ba1c8
refs/heads/master
2020-09-01T19:14:17.344623
2020-01-23T04:28:49
2020-01-23T04:28:49
219,034,541
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
14,012
cpp
Window.cpp
#include "Window.h" #include "App.h" int Window::Init() { //default resolution winH = 600; winW = 800; if (SDL_GetNumVideoDisplays() < 1) return -1; //getting display resolution SDL_DisplayMode current; if (SDL_GetCurrentDisplayMode(0, &current) < 0) { SDL_Log("Could not get display mode for video display #0: %s", SDL_GetError()); } else { winW = current.w*0.8; winH = current.h*0.8; } std::string title = "My VGE " + App::version; //create main window window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, winW, winH, SDL_WINDOW_SHOWN ); if (window == 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"Ошибка", u8"Невозможно создать окно. Посмотрите лог для подробной информации.", NULL); SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8"Невозможно создать окно, ошибка: %s", SDL_GetError()); return -2; } //create renderer for window render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (render == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"Ошибка", u8"Невозможно создать рендерер. Посмотрите лог для подробной информации.", NULL); SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8"Невозможно создать рендерер, ошибка: %s", SDL_GetError()); return -3; } font = TTF_OpenFont("a_AvanteBs_ExtraBold.ttf", 22); DRAW::render = render; SDL_SetRenderDrawBlendMode(DRAW::render, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(render, 0xFF, 0xFF, 0xFF, 0x00); for (int i = 0; i < 4; i++) { Button* tmp = new Button; string str = "./img/button-*.jpg"; str[str.find("*")] = i + 49; tmp->Init(render, str.c_str(), winW - 138 + (i % 2) * 69, 5 + i / 2 * 69); file_control.push_back(tmp); } m_ShapeBar.Init(render, "./img/shapebar-*.jpg", 0, 0, 6, VERTICAL, 5); canvas.Init(render); Palette::border.Init(5, 419, false); Palette::fill.Init(39, 419, true); workspace = { 94, 0, winW - 94 - 139, winH}; Canvas::canvas = { winW, winH, 0, 0 }; mb_down = false; return 0; } int Window::Handle(SDL_Event* event) { int mx = 0, my = 0; SDL_GetMouseState(&mx, &my); switch (event->type) { case SDL_KEYDOWN: if (event->key.keysym.sym == SDLK_q && event->key.keysym.mod == KMOD_LCTRL) { //SDL_Event exitEvent = { SDL_QUIT }; //SDL_PushEvent(&exitEvent); return 1; } if (event->key.keysym.sym == SDLK_DOWN) { m_ShapeBar.Activate0(); SDL_Log("cur: %d size: %d", Canvas::_current, Canvas::v_elements.size() - 1); if (Canvas::_current < (int)(Canvas::v_elements.size() - 1)) { //SDL_Log("%d", Canvas::_current); if (Canvas::_current >= 0) Canvas::v_elements[Canvas::_current]->UnSelect(); Canvas::_current++; Canvas::v_elements[Canvas::_current]->Select(); //SDL_Log("%d", Canvas::_current); } } if (event->key.keysym.sym == SDLK_UP) { m_ShapeBar.Activate0(); if (Canvas::_current > 0) { Canvas::v_elements[Canvas::_current]->UnSelect(); Canvas::_current--; Canvas::v_elements[Canvas::_current]->Select(); } //SDL_Log("%d", Canvas::_current); } if (event->key.keysym.sym == SDLK_DELETE && Canvas::_current >= 0) { Canvas::v_elements[Canvas::_current]->Clear(); Canvas::v_elements.erase(Canvas::v_elements.begin() + Canvas::_current); Canvas::_current = -1; } //SDL_Log(u8"нажата клавиша %d", event->key.keysym.sym); break; case SDL_KEYUP: //SDL_Log(u8"отпущена клавиша %d", event->key.keysym.sym); break; case SDL_TEXTEDITING: //SDL_Log(u8"Выделение текста. Выделенный текст '%s', начало в %d и длина выделения %d", event->edit.text, event->edit.start, event->edit.length); break; case SDL_TEXTINPUT: //SDL_Log(u8"Ввод текста с клавиатуры. Текст '%s'", event->text.text); break; case SDL_MOUSEMOTION: if (Canvas::_current >= 0 && mb_down) { Canvas::v_elements[Canvas::_current]->Handle(event); } break; case SDL_MOUSEBUTTONDOWN: mb_down = true; if (InWorkspace(event->button.x, event->button.y)) { if (Bar::_active) { Dot* tmp = 0; switch (Bar::_active) { case 1: tmp = new Dot; break; case 2: tmp = new Line; break; case 3: tmp = new Rect; break; case 4: tmp = new Ellipse; break; case 5: tmp = new Dot; //for text break; default: break; } tmp->Init(event->button.x - Canvas::canvas.x, event->button.y - Canvas::canvas.y); Canvas::v_elements.push_back(tmp); Canvas::_current = Canvas::v_elements.size() - 1; } else if (Canvas::_current >= 0 && Canvas::v_elements[Canvas::_current]->MouseOver(mx - Canvas::canvas.x, my - Canvas::canvas.y)) { Canvas::v_elements[Canvas::_current]->Handle(event); } } break; case SDL_MOUSEBUTTONUP: mb_down = false; if (Canvas::_current >= 0) { if (Bar::_active) { Canvas::v_elements[Canvas::_current]->StopCreate(); Canvas::v_elements[Canvas::_current]->UnSelect(); Canvas::_current = -1; } else Canvas::v_elements[Canvas::_current]->Handle(event); } break; case SDL_MOUSEWHEEL: //SDL_Log(u8"Колесо мыши X=%d, Y=%d", event->wheel.x, event->wheel.y); break; case SDL_QUIT: //SDL_Log(u8"Пользователь запросил выход"); return 1; case SDL_WINDOWEVENT: switch (event->window.event) { case SDL_WINDOWEVENT_RESIZED: //SDL_Log(u8"Окно %d изменило размер %dx%d", event->window.windowID, event->window.data1, event->window.data2); if (event->window.data1 < 640) winW = 640; else winW = event->window.data1; if (event->window.data2 < 480) winH = 480; else winH = event->window.data2; SDL_SetWindowSize(window, winW, winH); break; case SDL_WINDOWEVENT_SIZE_CHANGED: //SDL_Log(u8"Размер окна %d изменился на %dx%d", event->window.windowID, event->window.data1, event->window.data2); break; case SDL_WINDOWEVENT_CLOSE: { //SDL_Log(u8"Окно %d закрыто", event->window.windowID); return 1; } default: //SDL_Log(u8"В окне %d произошло неизвестное событие %d", event->window.windowID, event->window.event); break; } break; default: //SDL_Log(u8"Неизвестное событие %d", event->type); break; } if (m_ShapeBar.MouseOver(event->button.x, event->button.y)) { m_ShapeBar.Handle(event); if (Bar::_active && Canvas::_current >= 0) { Canvas::v_elements[Canvas::_current]->UnSelect(); Canvas::_current = -1; } } else m_ShapeBar.Unfocus(); Palette::border.Handle(event); if (Palette::border.IsOpened()) Palette::fill.Close(); Palette::fill.Handle(event); if (Palette::fill.IsOpened()) Palette::border.Close(); HandleFileControl(event); return 0; } void Window::Render() { SDL_SetRenderDrawColor(render, 0xa0, 0xa0, 0xa0, 0xff); SDL_RenderClear(render); canvas.Render(render); SDL_RenderSetViewport(render, &Canvas::canvas); for (int i = 0; i < Canvas::v_elements.size(); i++) { //SDL_Log("print %d", i); if(i != Canvas::_current) Canvas::v_elements[i]->Render(render); } if(Canvas::_current >= 0) Canvas::v_elements[Canvas::_current]->Render(render); SDL_RenderSetViewport(render, 0); SDL_Rect dst = { 0, 0, 74, winH }; SDL_SetRenderDrawColor(DRAW::render, 0x30, 0x30, 0x30, 255); SDL_RenderFillRect(DRAW::render, &dst); SDL_Rect dst2 = { winW - 144, 0, 143, winH }; SDL_RenderFillRect(DRAW::render, &dst2); m_ShapeBar.Render(render); Palette::border.Render(); Palette::fill.Render(); for (int i = 0; i < 4; i++) { file_control[i]->Render(render); } SDL_RenderPresent(render); } void Window::HandleFileControl(SDL_Event* event) { for (int i = 0; i < 4; i++) { if (file_control[i]->MouseOver(event->button.x, event->button.y)) { file_control[i]->Focus(); switch (event->type) { case SDL_MOUSEBUTTONDOWN: file_control[i]->Press(); SDL_Log("pressed %d", i); break; case SDL_MOUSEBUTTONUP: SDL_Log("released %d", i); file_control[i]->Release(); switch (i) { case 0: //create new canvas and clear old Create(); break; case 1: //open bin file LoadMVG(); break; case 2: //save bin file SaveMVG(); break; case 3: //save svg file SaveSVG(); break; } break; } } else file_control[i]->UnFocus(); } } void Window::CleanUp() { for (int i = 0; i < Canvas::v_elements.size(); i++) Canvas::v_elements[i]->Clear(); canvas.Clear(); SDL_DestroyRenderer(render); SDL_DestroyWindow(window); } void Window::InputText(const char* hint) { bool done = false; bool first = true; SDL_Rect rect = { (winW - 217) / 2 + 74 - 100, 300, 200, 40 }; SDL_Event event; SDL_StartTextInput(); buf.clear(); buf = hint; SDL_SetRenderDrawColor(render, 0xff, 0xff, 0xff, 0xff); SDL_RenderFillRect(render, &rect); SDL_Color color = { 0x0, 0x0, 0x0, 0xff }; SDL_Color bgcolor = { 0xff, 0xff, 0xff, 0xff }; DRAW::DrawText(render, font, buf.c_str(), rect.x, rect.y, rect.w, rect.h, &color, &bgcolor); SDL_RenderPresent(render); while (!done) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_RETURN) { done = true; } else if (event.key.keysym.sym == SDLK_BACKSPACE && buf.length() > 0) { buf.pop_back(); } break; case SDL_TEXTINPUT: if (first) { buf.clear(); first = false; } buf += event.text.text; break; } } SDL_SetRenderDrawColor(render, 0xff, 0xff, 0xff, 0xff); SDL_RenderFillRect(render, &rect); SDL_Color color = { 0x0, 0x0, 0x0, 0xff }; SDL_Color bgcolor = { 0xff, 0xff, 0xff, 0xff }; DRAW::DrawText(render, font, buf.c_str(), rect.x, rect.y, rect.w, rect.h, &color, &bgcolor); SDL_RenderPresent(render); } SDL_StopTextInput(); //return buf.c_str(); } void Window::Create() { canvas.Clear(); InputText(u8"Введите ширину"); Canvas::canvas.w = stoi(buf); InputText(u8"Введите высоту"); Canvas::canvas.h = stoi(buf); Canvas::canvas.x = (winW - 217) / 2 + 74 - Canvas::canvas.w / 2; Canvas::canvas.y = winH / 2 - Canvas::canvas.h / 2; } void Window::SaveMVG() { nfdchar_t* savePath = NULL; nfdresult_t result = NFD_SaveDialog("mvg", NULL, &savePath); if (result == NFD_OKAY) { SDL_Log("Success!"); string path = savePath; free(savePath); path += ".mvg"; SDL_Log(path.c_str()); ofstream out(path.c_str(), ios_base::binary); //offsets out.write((char*)& Canvas::canvas.x, sizeof(Canvas::canvas.x)); out.write((char*)& Canvas::canvas.y, sizeof(Canvas::canvas.y)); out.write((char*)& Canvas::canvas.w, sizeof(Canvas::canvas.w)); out.write((char*)& Canvas::canvas.h, sizeof(Canvas::canvas.h)); SDL_Log("cax = %d cay = %d caw = %d cah = %d", Canvas::canvas.x, Canvas::canvas.y, Canvas::canvas.w, Canvas::canvas.h); //count of obj int n = Canvas::v_elements.size(); out.write((char*)&n, sizeof(n)); SDL_Log("count = %d", n); //objects for (int i = 0; i < n; i++) { Canvas::v_elements[i]->Write(out); } out.close(); } else if (result == NFD_CANCEL) { SDL_Log("User pressed cancel."); return; } else { SDL_Log("Error: %s\n", NFD_GetError()); } } void Window::LoadMVG() { nfdchar_t* outPath = NULL; nfdresult_t result = NFD_OpenDialog("mvg", NULL, &outPath); if (result == NFD_OKAY) { canvas.Clear(); SDL_Log("Success!"); string path = outPath; free(outPath); SDL_Log(path.c_str()); ifstream in(path.c_str(), ios_base::binary); //offsets in.read((char*)& Canvas::canvas.x, sizeof(Canvas::canvas.x)); in.read((char*)& Canvas::canvas.y, sizeof(Canvas::canvas.y)); in.read((char*)& Canvas::canvas.w, sizeof(Canvas::canvas.w)); in.read((char*)& Canvas::canvas.h, sizeof(Canvas::canvas.h)); SDL_Log("cax = %d cay = %d caw = %d cah = %d", Canvas::canvas.x, Canvas::canvas.y, Canvas::canvas.w, Canvas::canvas.h); //count of obj int n; in.read((char*)& n, sizeof(n)); SDL_Log("count = %d", n); //objects for (int i = 0; i < n; i++) { int m; in.read((char*)& m, sizeof(m)); SDL_Log("i = %d ID = %d", i, m); switch (m) { case 0: { Dot* tmp = new Dot; tmp->Read(in); Canvas::v_elements.push_back(tmp); break; } case 1: { Dot* tmp = new Line; tmp->Read(in); Canvas::v_elements.push_back(tmp); break; } case 2: { Dot* tmp = new Rect; tmp->Read(in); Canvas::v_elements.push_back(tmp); break; } case 3: { Dot* tmp = new Ellipse; tmp->Read(in); Canvas::v_elements.push_back(tmp); break; } } } in.close(); } else if (result == NFD_CANCEL) { SDL_Log("User pressed cancel."); return; } else { SDL_Log("Error: %s\n", NFD_GetError()); } } void Window::SaveSVG() { nfdchar_t* savePath = NULL; nfdresult_t result = NFD_SaveDialog("svg", NULL, &savePath); if (result == NFD_OKAY) { SDL_Log("Success!"); string path = savePath; free(savePath); path += ".svg"; SDL_Log(path.c_str()); ofstream out(path.c_str()); //offsets out << "<?xml version=\"1.0\"?>\n"; out << "<svg width=\"" << Canvas::canvas.w << "\" height=\"" << Canvas::canvas.h << "\" viewBox=\"0 0 " << Canvas::canvas.w << " " << Canvas::canvas.h << "\" xmlns=\"http://www.w3.org/2000/svg\">\n"; //objects for (int i = 0; i < Canvas::v_elements.size(); i++) { Canvas::v_elements[i]->WriteSVG(out); } out << "</svg>"; out.close(); } else if (result == NFD_CANCEL) { SDL_Log("User pressed cancel."); return; } else { SDL_Log("Error: %s\n", NFD_GetError()); } }
5be7a2e1ec1c052e521fe5a6a2b62c3998132011
10ff3baf83ed55a3783c720033d0f672ae152dd5
/CurrencyRates.hpp
189a00d64e743e79c342fec9d3d4d429c1e0bd42
[]
no_license
sczembor/projekt_wymiana_walut
53f5be7d712b556e85f38939c2bec08247ff7578
90dfbd25914a3850a59c6ae038d587787342aaab
refs/heads/master
2020-12-24T00:55:42.229762
2020-01-31T00:11:32
2020-01-31T00:11:32
237,329,188
0
0
null
null
null
null
UTF-8
C++
false
false
755
hpp
CurrencyRates.hpp
// // CurrencyRates.hpp // wymiana_walut // // Created by Stanislaw Czembor on 23/11/2019. // Copyright © 2019 Stanislaw Czembor. All rights reserved. // #ifndef CurrencyRates_hpp #define CurrencyRates_hpp #include <string> #include <iostream> class currencyRates { private: std::string name; double ask; double bid; public: currencyRates(); currencyRates(std::string &p_name, double &p_ask, double & p_bid) : name(p_name), ask(p_ask), bid(p_bid){;} //operator strumieniowy friend std::ostream& operator<<(std::ostream& os, const currencyRates& waluta); std::string getName() const {return name;} double getAsk() const {return ask;} double getBid() const {return bid;} }; #endif /* CurrencyRates_hpp */
b0b94c79fad1ea3c934c687fc5daadb4b997a5ff
19e2cfde15c989fac6b91737ddfc22cfd5435c55
/TP5-E20/Hopital.cpp
c8df60fd9f9e1ddc002bbb538ccd78c03aab2ffa
[]
no_license
SamiBourai/inf1010
4466d32ba9ab913cbeb2372932ceefb3518ed7a9
87a3e395074aadc7797c87c8940a40000dc6e17e
refs/heads/main
2023-02-02T03:20:13.315032
2020-12-25T06:52:50
2020-12-25T06:52:50
324,303,961
1
0
null
null
null
null
UTF-8
C++
false
false
2,162
cpp
Hopital.cpp
//! Class Hopital //! \authors Ahmed Hammami & Youssef Ben Taleb //! \date 05 juin 2020 #include "Hopital.h" #include "assert.h" #include <numeric> #include "Foncteurs.h" #include <fstream> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <iterator> //! Constructeur par paramètres de la classe Hopital //! \param nom Nom de l'hopital //! \param adresse Adresse de l'hopital Hopital::Hopital(const std::string& nom, const std::string& adresse):nom_(nom), adresse_(adresse) { } void Hopital::ajouterPersonnel(Personnel& personnel) { /* TODO 1: * émettre le signal correspondant si l'ajout est réussi */ if (gestionnairePersonnels_.ajouterPersonnel(personnel)) { emit personnelAjoute(&personnel); } } void Hopital::supprimnerPersonnel(const std::string& personnelId) { /* TODO 2: * émettre le signal correspondant si la suppression est réussie */ if (gestionnairePersonnels_.supprimerPersonnel(personnelId)) { emit personnelSupprime(gestionnairePersonnels_.chercherPersonnel(personnelId)); //emit personnelSupprime(gestionnairePersonnels_.chercherPersonnel(personnelId)); } } //! Méthode qui retourne le nom de l'hopital //! \return nom_ le nom de l'hopital const std::string& Hopital::getNom() const { return nom_; } //! Méthode qui retourne l'adresse de l'hopital //! \return adresse_ l'adresse de l'hopital const std::string& Hopital::getAdresse() const { return adresse_; } //! Méthode qui retourne le gestionnaire du personnels //! \return gestionnairePersonnels_ gestionnaire du personnels GestionnairePersonnels& Hopital::getGestionnairePersonnels() { return gestionnairePersonnels_; } //! Méthode qui permet de mettre à jour le nom de l'hopital //! \Param nom Le nom de l'hopital void Hopital::setNom(const std::string& nom) { nom_ = nom; } //! Méthode qui permet de mettre à jour l'adresse de l'hopital //! \Param adresse l'adresse de l'hopital void Hopital::setAdresse(const std::string& adresse) { adresse_ = adresse; }
af4f50190d8e1b685c3e7dea4c1b00dab57089da
952af00d549bda4474dd25d65b8c18c3a2291863
/projeto_carga-descarga_capacitor/carga_descarga_controlada.ino
808b89f2c4d5707ed0482f3efeb990ec9f810ef5
[]
no_license
geans/GDEEF-Suporte
06a9a8893b99faf351f6df3085998ab4f633664a
67999b05a30aadcb576dac64772eb02a0ca101f4
refs/heads/master
2020-03-22T17:56:23.600590
2019-11-28T20:31:26
2019-11-28T20:31:26
140,425,279
1
1
null
2019-11-28T20:31:27
2018-07-10T11:58:54
Python
UTF-8
C++
false
false
1,715
ino
carga_descarga_controlada.ino
int chave_carga=6; int chave_descarga=7; int pino_rele1=10; int pino_rele2=11; bool ligar_rele = LOW; bool desligar_rele = ~ligar_rele; void setup() { Serial.begin(9600); pinMode ( chave_carga, OUTPUT); pinMode ( chave_descarga, OUTPUT); digitalWrite ( chave_carga, HIGH); digitalWrite ( chave_descarga, HIGH); } void tratador(String cmd){ /* Vai receber 2 ou mais caraceters. O primeiro indica se é carga ou descarga. * Do segundo em diante é o tempo em segundos que o sistema fica ligado. * Exemplo: c120 * c - carga * 120 - 120 segundos carregando * Exemplo: d3 * d - descarga * 3 - 3 segundos carregado */ char carga = cmd[0]; char rele1 = cmd[1]; char rele2 = cmd[2]; String duracao_tempo_str = cmd.substring(3); int duracao_tempo = duracao_tempo_str.toInt(); int rele_escolhido = (carga == 'c') ? chave_carga : chave_descarga; if(rele1 == '1'){ digitalWrite (pino_rele1, ligar_rele); Serial.println("Rele 1 ligado"); }else{ digitalWrite (pino_rele1, desligar_rele); Serial.println("Rele 1 desligado"); } Serial.print("Rele 1: "); Serial.println(rele1); if(rele2 == '1'){ digitalWrite (pino_rele2, ligar_rele); Serial.println("Rele 2 ligado"); }else{ digitalWrite (pino_rele2, desligar_rele); Serial.println("Rele 2 desligado"); } Serial.print("Rele 2: "); Serial.println(rele2); Serial.print("Rele escolhido: "); Serial.println(rele_escolhido); digitalWrite ( rele_escolhido, ligar_rele); delay(duracao_tempo*1000); digitalWrite ( rele_escolhido, desligar_rele); } void loop() { if (Serial.available() > 0) { String cmd = Serial.readString(); tratador(cmd); } }
3ef0f0d1509cd072bacbc6c850a1887abf2f1483
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/chrome_cleaner/engines/controllers/scanner_impl.h
59c0277eeab321aefea05e3992d032595f1d2af0
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,799
h
scanner_impl.h
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_IMPL_H_ #define CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_IMPL_H_ #include <set> #include "base/sequence_checker.h" #include "base/task/sequenced_task_runner.h" #include "chrome/chrome_cleaner/engines/broker/engine_client.h" #include "chrome/chrome_cleaner/pup_data/pup_data.h" #include "chrome/chrome_cleaner/scanner/scanner.h" namespace chrome_cleaner { class ScannerImpl : public Scanner { public: // Passed |engine_client| should stay alive the entire lifetime of the object. explicit ScannerImpl(EngineClient* engine_client); ~ScannerImpl() override; // Scanner implementation. // Start scanning. bool Start(const FoundUwSCallback& found_uws_callback, DoneCallback done_callback) override; void Stop() override; // When calling |Stop|, the engine may still be running, so make sure to call // |IsCompletelyDone| and allow the main UI to pump messages to let the engine // finish gracefully. bool IsCompletelyDone() const override; private: // Sandboxed client callbacks. void OnFoundUwS(UwSId pup_id, const PUPData::PUP& pup); void OnScanDone(uint32_t result); void HandleFoundUwS(UwSId pup_id, const PUPData::PUP& pup); void HandleScanDone(uint32_t result); EngineClient* engine_client_; std::set<UwSId> found_uws_; FoundUwSCallback found_uws_callback_; DoneCallback done_callback_; SEQUENCE_CHECKER(sequence_checker_); scoped_refptr<base::SequencedTaskRunner> task_runner_; bool is_scanning_ = false; }; } // namespace chrome_cleaner #endif // CHROME_CHROME_CLEANER_ENGINES_CONTROLLERS_SCANNER_IMPL_H_
a3ecc4e7a3ab45f334c2a90d41510e4f4861fcfe
d7b9a2c289449390f0cb77c056885936030a54fb
/source/include/mczMath.h
9a47f48ee31f2eaa6b2ef85c092550e062fbbfc8
[]
no_license
mczombie/CSharpServer
6693260413d6166794af342c4513632509c85897
addd2f5bbc39264773a3fd0fca5a22900fa5b9a1
refs/heads/master
2016-09-06T04:58:13.344717
2015-02-23T14:26:29
2015-02-23T14:26:29
29,083,302
0
0
null
null
null
null
UTF-8
C++
false
false
188
h
mczMath.h
#pragma once namespace mcz { struct vector3 { vector3() {} vector3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} float x, y, z; }; struct vector4 { float x, y, z, w; }; }
33504fb40997ffba747df864748dc37e5e66e91d
bb96dc76f4e70b3e52b010b69dfe75049f6b9da2
/kvread/cq_test.cpp
9b31da053cf81f1e3218f232a5feba3f0a8ab44d
[]
no_license
wamos/sorting-comet
faa5c0fec3095f215d3584ef384bd6b0db932b20
bc91f920a229843be963b194ec365c49799a4feb
refs/heads/master
2020-03-19T22:14:01.986329
2018-08-22T20:59:12
2018-08-22T20:59:12
136,963,809
0
0
null
null
null
null
UTF-8
C++
false
false
3,837
cpp
cq_test.cpp
#include <thread> #include <chrono> #include <iostream> #include <utility> //#include "json.hpp" #include "utility.h" /*---------------*/ //#include "ConcurrentQueue.h" #include "CircularQueue.h" #include "MemoryPool.h" #include "StageTracker.h" #include "KVTuple.h" #include "KVSink.h" #include "KVSource.h" //#include "KVGuide.h" #include "spdlog/spdlog.h" #define SPDLOG_TRACE_ON #define SPDLOG_DEBUG_ON inline uint64_t getNanoSecond(struct timespec tp){ clock_gettime(CLOCK_MONOTONIC, &tp); return (1000000000) * (uint64_t)tp.tv_sec + tp.tv_nsec; } int main(int argc, char* argv[]) { size_t record_size= 100; uint32_t key_size=10; uint32_t val_size=99980; //uint32_t val_size=90; uint32_t header_size=10; size_t bulk_size=100; int num_src_thread=1; //default as 1 int num_sink_thread=1; //default as 1 int num_file_guider=0; //default as 0 int duration = 60; //std::string filepath= "/oasis/scratch/comet/stingw/temp_project/"; std::string filepath= "/tmp/"; std::string datapath; std::string slurm_topology_addr; utility::parse_cli_arguments(argc, argv, utility::cli_argument_pack() .arg(duration, "-t", "how long should the code run") .arg(num_src_thread, "-src", "the number of source") .arg(num_sink_thread, "-sink", "the number of sink") .arg(num_file_guider, "-fg", "the number of file guider") .arg(bulk_size, "-bs", "the size of a bulk") .arg(datapath, "-d", "SSD or Data Oasis") //.arg(slurm_topology_addr, "-host", "hostname from env var") //.positional_arg(inputFileName, "input_filename", "input file name") ); /*size_t queue_size = 100; KVTuple kvr2; CircularQueue cq(queue_size); MemoryPool mpool(queue_size*2, size); for(int i=0;i<queue_size;i++){ KVTuple kvr(header_size, key_size, val_size, mpool.acquireMemBlock()); cq.spin_push(std::move(kvr)); } for(int i=0;i<queue_size;i++){ cq.spin_pop(kvr2); mpool.releaseMemBlock(); }*/ time_t rawtime; struct tm * timeinfo; char buffer[80]; time (&rawtime); timeinfo = localtime(&rawtime); strftime(buffer,sizeof(buffer),"%Y:%m:%d:%H:%M",timeinfo); std::string time_str(buffer); std::cout << "The Time is:"+time_str <<"\n"; auto console = spdlog::stdout_color_mt("console"); spdlog::set_pattern("%v"); console->info("spdlog console logger starts"); auto queue_logger = spdlog::basic_logger_mt("queue_logger", filepath+"queue_"+time_str+"_th_"+std::to_string(num_sink_thread)+"."+datapath); if(num_file_guider>0){ auto g_logger = spdlog::basic_logger_mt("guide_logger", filepath+"guide_"+time_str+"_th_"+std::to_string(num_sink_thread)+"."+datapath); } else{ std::cout << "No Guider!!!!!!!"<<"\n"; } if(num_sink_thread>0) auto sink_logger = spdlog::basic_logger_mt("sink_logger", filepath+"sink_"+time_str+"_th_"+std::to_string(num_sink_thread)+"."+datapath); if(num_src_thread>0) auto src_logger = spdlog::basic_logger_mt("source_logger", filepath+"src_"+time_str+"_th_"+std::to_string(num_sink_thread)+"."+datapath); size_t queue_size = 1000; size_t size = header_size+key_size+val_size; std::shared_ptr<CircularQueue> GuideQueue( new CircularQueue(queue_size) ); std::shared_ptr<StageTracker> tracker( new StageTracker(num_src_thread, 1)); //std::shared_ptr<MemoryPool> mpool( new MemoryPool(queue_size*2, size)); //auto ptr =mpool.get(); //MemoryPool* ptr = new MemoryPool(queue_size*2, size); //KVTuple kvr(header_size, key_size, val_size, ptr->acquireMemBlock()); //ptr->releaseMemBlock(); KVSource source_gen(0, key_size, val_size, GuideQueue, tracker, nullptr); source_gen.setHeaderSize(10); KVSink sink(0, GuideQueue, tracker, nullptr, 1); source_gen.startSource(); sink.startMultiSink(); std::this_thread::sleep_for(std::chrono::seconds(duration)); source_gen.stopSource(); return 0; }
9bd1b27b8d2c072ebddd14dbee0c82c79eb17e88
459103d6cff07d697a25239ad4a98635f602aaf9
/include/BytecodeIO.h
7cd3c2711a07d4376856ea80abe69063bc7e2c30
[ "MIT" ]
permissive
Cloaked9000/Fryte
1959bdb6c65967c0439cb20158252f45265c4b70
e8c94f88fdc4ca49f9008fd10093cb48e5a8251b
refs/heads/master
2018-01-07T22:27:22.894218
2016-11-03T16:39:48
2016-11-03T16:39:48
46,950,784
4
1
null
null
null
null
UTF-8
C++
false
false
439
h
BytecodeIO.h
#ifndef BYTECODEIO_H #define BYTECODEIO_H #include <fstream> #include <string> #include <vector> #include <iostream> class BytecodeIO { public: BytecodeIO(); virtual ~BytecodeIO(); static bool writeBytecode(const std::string &filepath, const std::vector<unsigned int> &byteCode); static bool readBytecode(const std::string &filepath, std::vector<unsigned int> &byteCode); protected: private: }; #endif // BYTECODEIO_H
24ffd46e1227b5d544167d06cb2a0773b0c7f55e
58e2c2e6b632fadd78906e38a4e75d088e0af983
/mtPt3.h
57555df8d020c2a11f5dbf35ab04f2d1fc6b0a68
[]
no_license
funcman/mtMath
6b0b1c338bd3f98739ca1046c22f5915f3958d90
254beb2ca173d8817aa9389a6f6214d1c75e048b
refs/heads/master
2021-01-25T05:15:37.279470
2015-12-24T05:52:54
2015-12-24T09:31:48
39,837,806
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
h
mtPt3.h
#ifndef MTPT3_H #define MTPT3_H #include <string> class mtVec3; class mtBox; class mtPt3 { public: float x; float y; float z; public: mtPt3(); explicit mtPt3(float x, float y, float z); mtPt3(mtPt3 const& pt); mtPt3& operator=(mtPt3 const& pt); mtPt3 operator+(mtPt3 const& pt) const; mtPt3 operator-(mtPt3 const& pt) const; mtPt3 operator-() const; bool operator==(mtPt3 const& pt) const; bool operator!=(mtPt3 const& pt) const; mtPt3 operator+(mtVec3 const& vec) const; mtPt3 operator-(mtVec3 const& vec) const; mtVec3 from(mtPt3 const& pt) const; mtVec3 to(mtPt3 const& pt) const; float distanceFrom(mtPt3 const& pt) const; float distanceTo(mtPt3 const& pt) const; mtBox operator*(mtPt3 const& pt) const; std::string toString() const; }; #include "mtPt3.inl" #endif//MTPT3_H
4441b657f5c2e2952cd9b66db6648ea6f7fbc725
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1485488_0/C++/PlutoShe/B.cpp
291f431a842fc86308e8817c0a50043fde613896
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
685
cpp
B.cpp
#include <iostream> #include <cstdio> using namespace std; int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int t, n, s, l, l1, l2, j; cin >> t; for (int tt = 0; tt < t; tt++) { int ans = 0; cin >> n >> s >> l; l1 = l * 3 - 2; l2 = l * 3 - 4; if (l2 <= 0) { if (l > 0) l2 = l; else if (l == 0) l2 = 0; } for (int i = 0; i < n; i++) { scanf("%d", &j); if (j >= l1) ans++; else if (s > 0 && j >= l2) {ans++; s--;} } cout << "Case #" << tt + 1 << ": " << ans << endl; } }
fd763d0204afdb5157562bea51ea761382005cae
723202e673511cf9f243177d964dfeba51cb06a3
/09/oot/eav_labs/lab1/src/eav_oot_lab_1/TextInOval.h
ee566fc0d9ecd09cbfb4e163170be9a0f0c56683
[]
no_license
aeremenok/a-team-777
c2ffe04b408a266f62c523fb8d68c87689f2a2e9
0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b
refs/heads/master
2020-12-24T16:50:12.178873
2009-06-16T14:55:41
2009-06-16T14:55:41
32,388,114
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,744
h
TextInOval.h
// Copyright (C) 1991 - 1999 Rational Software Corporation #if defined (_MSC_VER) && (_MSC_VER >= 1000) #pragma once #endif #ifndef _INC_TEXTINOVAL_46F50C7B01D4_INCLUDED #define _INC_TEXTINOVAL_46F50C7B01D4_INCLUDED ////////////////////////////////////////////////////////////////////////// #include "Oval.h" #include "Text.h" #include <list> ////////////////////////////////////////////////////////////////////////// class ostream; using std::list; ////////////////////////////////////////////////////////////////////////// //текст в овале //##ModelId=46F50C7B01D4 class TextInOval : public Oval , public Text { private: //##ModelId=472DF1EC00DA TextInOval(float rad1, float rad2, std::string content, float x, float y); //указатели на созданные тексты в овалах //##ModelId=4736C5F102FD static list<TextInOval*> _textsInOvals; public: //выдает указатель на уже существующий текст в овале, если он имеет заданные //параметры //если такого не существует - создает новый //##ModelId=4736C62903A9 static TextInOval* create(float rad1, float rad2, std::string content, float x, float y); //##ModelId=46F677F2002E virtual ~TextInOval(); //вычисляет площадь фигуры //##ModelId=472DF2A20119 virtual float Area() const; protected: //вывести состояние текста в овале в поток //##ModelId=471219010148 virtual ostream& speak(ostream& os) const; }; ////////////////////////////////////////////////////////////////////////// #endif /* _INC_TEXTINOVAL_46F50C7B01D4_INCLUDED */
1b976a27a482d97bfa50aa2bb66f800a8526500c
1aa8668f1d861728eecb4a15ac282685be6fa3d8
/printEffect.cpp
796163f68b83d216f25c40ce6b915346c2bb90bf
[]
no_license
BraveKoen/wumpus
8a265d680c9c495fa5fcd25061015914bae7f524
688853aa4bd9bd7aa6b1e392afde9007ce7890a8
refs/heads/master
2022-04-17T23:51:53.146505
2020-04-09T10:20:58
2020-04-09T10:20:58
250,246,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,969
cpp
printEffect.cpp
using namespace std; #include "printEffect.hpp" //Prints 'text', character by character at 'speed', also prints an end line character if 'line' is true. void printEffect(string text, bool line, int speed){ //if line is set to true printEffect will add a enter. for (unsigned int i = 0; i < text.size(); i++){ cout << text[i]; Sleep(speed); } if(line == true){ cout << endl; } } //Opens 'rulesWumpus.txt' and prints the text within. void rules(){ string line; ifstream myfile("rulesWumpus.txt"); if (myfile.is_open()) { while (getline(myfile, line)) { printEffect(line,true,15); } myfile.close(); } else cout << "Unable to open file"; } //Checks if game.player.score is higher than current highscore, prints information accordingly. Also writes to file if score is indeed higher. void statistics(game_data& game ,string name) { vector<string> highscore; string line; ifstream myfile("userData.txt"); // opens the file in read mode if (myfile.is_open()) { while (getline(myfile, line)) { highscore.push_back(line); // All lines will be pushed in the vector } myfile.close(); } int score = stoi(highscore[1]); //To compare the score they both have to be inters printEffect("The highscore is ",false); cout << score << endl; if(game.player.score > score){ // if the current player has a higer score then the record, the changeHighscore function will be called printEffect("You have beaten the highscore! ", true); changeHighscore(name, game.player.score); }else{ printEffect("The highscore has not been bested!", true); } } //Writes highscore to 'userData.txt'. void changeHighscore(string name, int score) { ofstream newFile("userData.txt"); //opens the file in write mode so it will override the current score newFile << name << endl; newFile << score; newFile.close(); }
66830102078695f1ec6b4f5ac77ea0c0f3cf08c0
efd7adff589e37ca98d2e3eb245aaeb23f64496e
/src/plugins/cpptools/modelmanagertesthelper.cpp
46f2a91723968338d2db34026e6cac72fc31250e
[]
no_license
Andersbakken/CPlusPlus
3cf03c28968243587fa1d4661e7e5a388e62eb43
400f0b8f19de1c3fc9b794228c7aeec2259fce81
refs/heads/master
2021-01-10T20:24:54.067140
2013-05-28T03:46:50
2013-05-28T03:46:50
9,491,173
2
0
null
null
null
null
UTF-8
C++
false
false
3,678
cpp
modelmanagertesthelper.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "modelmanagertesthelper.h" #include <QtTest> #include <cassert> using namespace CppTools::Internal; TestProject::TestProject(const QString &name, QObject *parent) : m_name (name) { setParent(parent); } TestProject::~TestProject() { } ModelManagerTestHelper::ModelManagerTestHelper(QObject *parent) : QObject(parent) { CppModelManager *mm = CppModelManager::instance(); assert(mm); connect(this, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)), mm, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*))); connect(this, SIGNAL(projectAdded(ProjectExplorer::Project*)), mm, SLOT(onProjectAdded(ProjectExplorer::Project*))); connect(mm, SIGNAL(sourceFilesRefreshed(QStringList)), this, SLOT(sourceFilesRefreshed(QStringList))); cleanup(); verifyClean(); } ModelManagerTestHelper::~ModelManagerTestHelper() { cleanup(); verifyClean(); } void ModelManagerTestHelper::cleanup() { CppModelManager *mm = CppModelManager::instance(); assert(mm); QList<ProjectInfo> pies = mm->projectInfos(); foreach (const ProjectInfo &pie, pies) emit aboutToRemoveProject(pie.project().data()); } void ModelManagerTestHelper::verifyClean() { CppModelManager *mm = CppModelManager::instance(); assert(mm); QVERIFY(mm->projectInfos().isEmpty()); QVERIFY(mm->includePaths().isEmpty()); QVERIFY(mm->frameworkPaths().isEmpty()); QVERIFY(mm->definedMacros().isEmpty()); QVERIFY(mm->projectFiles().isEmpty()); QVERIFY(mm->snapshot().isEmpty()); QCOMPARE(mm->workingCopy().size(), 1); QVERIFY(mm->workingCopy().contains(mm->configurationFileName())); } ModelManagerTestHelper::Project *ModelManagerTestHelper::createProject(const QString &name) { TestProject *tp = new TestProject(name, this); emit projectAdded(tp); return tp; } QStringList ModelManagerTestHelper::waitForRefreshedSourceFiles() { m_refreshHappened = false; while (!m_refreshHappened) QCoreApplication::processEvents(); return m_lastRefreshedSourceFiles; } void ModelManagerTestHelper::sourceFilesRefreshed(const QStringList &files) { m_lastRefreshedSourceFiles = files; m_refreshHappened = true; }
b098de027cb2826995b5e76a3740c2a1288259e8
4473811d5ffa2a60adbad8f848b47e12d9d3b6e1
/cpp/Config.cpp
10b892410c83cfb7d56c849e4c10f917e9053fb1
[]
no_license
EvansDaniel/Coding-Problems
538aa95dcb78de79a231637810badc14b7644a2c
bab7dd53e693a10457e4e62be0989363060dc007
refs/heads/master
2020-05-21T23:10:31.274904
2016-10-03T13:51:28
2016-10-03T13:51:28
58,461,833
0
0
null
null
null
null
UTF-8
C++
false
false
198
cpp
Config.cpp
// // Created by daniel on 9/7/16. // #include "Config.h" std::string Config::getDataDir() { std::string home(getenv("HOME")); return home + "/ClionProjects/Coding-Problems/dataFiles/"; }
23ca274f1dee6501ccabdd6d67081a9ccddb20e6
4cc3badb472249678271f9ae24e47c0eea711925
/scene_manager.h
2df97ba9eb3e188bbe58b7dee8648c72625db8ae
[]
no_license
m1n1027/azuma2019
ea6dab9736e1414d92b43bbeccc8a97a082ca36b
f553660c911dcea592809ffbe017d3ddf835ceb5
refs/heads/master
2020-05-07T12:05:27.779773
2019-04-10T03:10:30
2019-04-10T03:10:30
180,487,680
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
scene_manager.h
#pragma once #include"scene.h" class SCENE_MANAGER { private: SCENE *scene = NULL; public: void SceneChange(SCENE* s) { if (scene != NULL) delete scene; scene = s; scene->Initialize(); } void Initialize() { scene->Initialize(); } void Update() { scene->Update(); } void Draw() { scene->Draw(); } SCENE* GetScene() { return scene; } };
103449404693c4ce23d66d12bcec5564c7893ab7
f5d9dda0732bc9bcd4196e9ae6552da1ce7e8c84
/Q18.CPP
0752fbe54e039c522df0b3e53dcfd44b5f073dc5
[]
no_license
dibakardhar/C-CPP-Notes
170f306fdcfd7eab8100548d9b3d9161bf482f63
cabef9e885664460c2b810ec5ee786d88457f949
refs/heads/main
2023-08-10T21:19:35.970627
2021-09-17T11:43:55
2021-09-17T11:43:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
151
cpp
Q18.CPP
#include<stdio.h> #include<conio.h> void main() { clrscr(); float x = 18.23; printf("%1.1f\n" ,x); printf("%-8.3f" ,x); getch(); }
ac06673366d192040a5c607e7fbadef2c2b1fe2d
c4f84aecbccd66748a5cb1d916ee179bbfe3f72d
/bindings/python/src/SummarizedMap.cpp
687c9a87736a13fae81057a109ca5a00a87c7fbb
[ "BSD-3-Clause" ]
permissive
MeasureTransport/MParT
c43ee812704b117ff147b26ab83b10d411678b69
aa08ee2e2ff765282b14351f07a81ea0c963783a
refs/heads/main
2023-08-18T13:33:37.072562
2023-07-26T18:57:44
2023-07-26T18:57:44
444,467,673
9
1
BSD-3-Clause
2023-08-13T03:02:26
2022-01-04T15:22:23
C++
UTF-8
C++
false
false
1,067
cpp
SummarizedMap.cpp
#include "CommonPybindUtilities.h" #include "MParT/SummarizedMap.h" #include "MParT/ConditionalMapBase.h" #include "MParT/ParameterizedFunctionBase.h" #include <pybind11/stl.h> #include <pybind11/eigen.h> #include <Kokkos_Core.hpp> #include <pybind11/pybind11.h> namespace py = pybind11; using namespace mpart::binding; template<typename MemorySpace> void mpart::binding::SummarizedMapWrapper(py::module &m) { std::string tName = "SummarizedMap"; if(!std::is_same<MemorySpace,Kokkos::HostSpace>::value) tName = "d" + tName; // SummarizedMap py::class_<SummarizedMap<MemorySpace>, ConditionalMapBase<MemorySpace>, std::shared_ptr<SummarizedMap<MemorySpace>>>(m, tName.c_str()) .def(py::init<std::shared_ptr<ParameterizedFunctionBase<MemorySpace>>, std::shared_ptr<ConditionalMapBase<MemorySpace>>>()) ; } template void mpart::binding::SummarizedMapWrapper<Kokkos::HostSpace>(py::module&); #if defined(MPART_ENABLE_GPU) template void mpart::binding::SummarizedMapWrapper<mpart::DeviceSpace>(py::module&); #endif // MPART_ENABLE_GPU
47ffeb4328f3d14a3bd64e4d6da1e3097514174a
4a3da8a0c70a1fcb9a6d8ba2b0f3777000ffe5e0
/ fighting7mongoose7senior7project/Game/CSSDefineState.h
00af7c34d70d7693352facc54e11f2cec263ad1c
[]
no_license
tectronics/fighting7mongoose7senior7project
21401db4c8ad4164dc99fcc3fe873b55fe3f28b6
c13ff5f6d8279732342efd80feeb3491d8452492
refs/heads/master
2018-01-11T15:00:54.474111
2010-02-16T22:33:01
2010-02-16T22:33:01
47,051,823
0
0
null
null
null
null
UTF-8
C++
false
false
4,458
h
CSSDefineState.h
////** All 'State' classes will have an instance passed **//// ////** into the singleton instance of 'Game' in order to switch state **//// ////** The methods changeState(), pushState(), and popState() (inherited) will be used **//// ////** Within each state class is where specific scene setup **//// ////** and functionality will be created/handled **//// //******** I want to implement this class as a sub-state of CreateSquadState ********// //******** (if thats possible) by pushing this state into our GameStates vector ********// //******** while retaining CreateSquadState and its rendering capabilities ********// //******** Right now this class is implemented as a seperate state ********// //******** (which could be ok) but results in extra overhead and copied code ********// #pragma once #pragma comment( lib, "Common.lib" ) #include "GameState.h" #include "GUIManager.h" #include "../Common/enumerations.h" #include "../Common/Character.h" struct maPointers { AnimationState *maDoll; AnimationState *maDress; AnimationState *maShirt; AnimationState *maShirt02; AnimationState *maPant; AnimationState *maPant02; AnimationState *maHat01; AnimationState *maHat02; AnimationState *maHelmet01; AnimationState *maBoot; }; class CSSDefineState : public GameState { private: Root *mRoot; SceneManager *mSceneManager; Viewport *mViewport; Camera *mCamera; OISInput *mInput; GUIManager *mGUI; CEGUI::WindowManager *mWindowManager; CEGUI::Window *mLayoutSheet; Character *mCharacter; maPointers maP; unsigned char activeButton; // character defines string characterName; unsigned char classType, subclassType, specialityType, alignmentType, genderType; static CSSDefineState mCSSDefineState; //** private functions **// void defineScene(); void defineGUI(); // registered button events (main) bool nameFieldEntered(const CEGUI::EventArgs &guiEvent); bool classButtonPressed(const CEGUI::EventArgs &guiEvent); bool subclassButtonPressed(const CEGUI::EventArgs &guiEvent); bool specialityButtonPressed(const CEGUI::EventArgs &guiEvent); bool alignmentButtonPressed(const CEGUI::EventArgs &guiEvent); bool genderButtonPressed(const CEGUI::EventArgs &guiEvent); bool backButtonPressed(const CEGUI::EventArgs &guiEvent); bool continueButtonPressed(const CEGUI::EventArgs &guiEvent); // class select event bool classCheckboxPressed(const CEGUI::EventArgs &guiEvent); bool classCheckboxReleased(const CEGUI::EventArgs &guiEvent); // subclass select events bool subclassCheckboxPressed(const CEGUI::EventArgs &guiEvent); bool subclassCheckboxReleased(const CEGUI::EventArgs &guiEvent); bool specialityCheckboxPressed(const CEGUI::EventArgs &guiEvent); //bool specialityCheckboxReleased(const CEGUI::EventArgs &guiEvent); //bool alignmentCheckboxPressed(const CEGUI::EventArgs &guiEvent); //bool alignmentCheckboxReleased(const CEGUI::EventArgs &guiEvent); //// supplementary event functions //// void loadWarriorSubclasses(); void loadMageSubclasses(); void loadRogueSubclasses(); void loadHealerSubclasses(); void loadRangedSubclasses(); // test availability of continue button void testEnableContinue(); string maName; void LoadCharacterMesh(); // used after mesh has been loaded to display // correct class mesh void warriorMesh(); void warriorMatChange(int w); void mageMesh(); void mageMatChange(int w); void healMesh(); void healMatChange(int w); void rogueMesh(); void rogueMatChange(int w); void rangeMesh(); void rangeMatChange(int w); protected: CSSDefineState() {} public: void enter(); void exit(); Character* getCharacter() { return mCharacter; } bool mouseMoved(const OIS::MouseEvent &mouseEvent); bool mousePressed(const OIS::MouseEvent &mouseEvent, OIS::MouseButtonID buttonID); bool mouseReleased(const OIS::MouseEvent &mouseEvent, OIS::MouseButtonID buttonID); bool keyPressed(const OIS::KeyEvent &keyEvent); bool keyReleased(const OIS::KeyEvent &keyEvent); bool frameStarted(const FrameEvent &frameEvent); bool frameEnded(const FrameEvent &frameEvent); static CSSDefineState* getInstance() { return &mCSSDefineState; } };
140e11c9502f7e420f427a0e97973225fb849c2a
209c4d5759e1fae9112fc8a4f1b9ef53777c4e1a
/MissileMadness/ResourceManager.h
c8709c3238e08fad561fd67f236391f81f036e9a
[]
no_license
Kassuz/missile-madness
da1213e864230ee93ef2a8066be613105d0b6c89
963f06eee614425fecee88791ed86ff444147e6a
refs/heads/master
2020-06-01T03:55:09.097100
2019-11-12T10:49:24
2019-11-12T10:51:10
190,623,270
0
0
null
null
null
null
UTF-8
C++
false
false
666
h
ResourceManager.h
#pragma once #include <map> #include <string> class Shader; class Texture2D; class ResourceManager { public: static ResourceManager& Instance(); Shader* LoadShader(const std::string& name); Texture2D* LoadTexture2D(const std::string& path); private: ResourceManager(); ~ResourceManager(); ResourceManager(const ResourceManager& other) = delete; ResourceManager& operator=(const ResourceManager& other) = delete; std::map<std::string, Shader*> m_Shaders; std::map<std::string, Texture2D*> m_Textures; Shader* LoadShaderFromFile(const std::string& vertex, const std::string& fragment); Texture2D* LoadTexture2DFromFile(const std::string& path); };
87d4c13ad607f26b405901052ba8dcb463aa256a
5d5fac95f996b78d1b90554de04182b13c7c70ca
/GreedyActivitySelector.cpp
b293b7a1d973ea1c8e6dc51031da4298c412fecb
[]
no_license
Rahul-154/DAA-Lab
ece881882430dfb74b86717922dbc36f3f4e34cf
9e6b3a8813b2ef45249be868dd0066cf0ec5ce19
refs/heads/main
2023-02-13T10:07:54.702212
2021-01-06T06:54:48
2021-01-06T06:54:48
327,214,157
3
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
GreedyActivitySelector.cpp
#include <iostream> using namespace std; int main() { int s[11] = {1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12}; int f[11] = {4, 5, 6, 7, 9, 9, 10, 11, 12, 14, 16}; int n = sizeof(s) / sizeof(int); int A[n] = {1}; int k = 0; int count = 0; for (int m = 1; m < n; m++) { if (s[m] >= f[k]) { count++; A[count] = m + 1; k = m; } } for (int i = 0; i <= count; i++) { cout << "a" << A[i] << " "; } return 0; }
f267057d7cb1b445701106f788b837ed801c3096
63c97099562efeba79a27bc005cef6b3c08fbe96
/shared/lane/f32/lane_f32_common.cpp
a7b803a2fa31aee04d3a1348bdc8e749d4a697b7
[]
no_license
CaptainSeagull/Screenshotter---public
e5e8a68919616c9e73d477b2683dd7790957340b
ad16bd1cdb6926572c933c78d5db45100c413b6c
refs/heads/master
2023-07-17T23:26:44.365967
2021-08-28T13:19:14
2021-08-28T13:19:14
400,792,353
0
0
null
null
null
null
UTF-8
C++
false
false
3,613
cpp
lane_f32_common.cpp
// Methods LANE_PUBLIC_DEC float extract(Lane_F32 a, uint32_t lane) { float r = ((float *)&a)[lane]; return(r); } LANE_PUBLIC_DEC Lane_F32 clamp(Lane_F32 a, Lane_F32 l, Lane_F32 u) { Lane_F32 r = minf32(maxf32(a, l), u); return(r); } LANE_PUBLIC_DEC Lane_F32 clamp(Lane_F32 a, float l, float u) { Lane_F32 r = clamp(a, lane_f32(l), lane_f32(u)); return(r); } LANE_PUBLIC_DEC Lane_F32 lane_clamp01(Lane_F32 a) { Lane_F32 r = clamp(a, lane_f32(0.0f), lane_f32(1.0f)); return(r); } Lane_F32 Lane_F32::operator=(float a) { *this = lane_f32(a); return(*this); } // Mul LANE_PUBLIC_DEC Lane_F32 operator*(Lane_F32 a, float b) { Lane_F32 r = a * lane_f32(b); return(r); } LANE_PUBLIC_DEC Lane_F32 operator*(float a, Lane_F32 b) { Lane_F32 r = lane_f32(a) * b; return(r); } LANE_PUBLIC_DEC Lane_F32 operator*=(Lane_F32 &a, Lane_F32 b) { a = a * b; return(a); } // Div LANE_PUBLIC_DEC Lane_F32 operator/(Lane_F32 a, float b) { Lane_F32 r = a / lane_f32(b); return(r); } LANE_PUBLIC_DEC Lane_F32 operator/(float a, Lane_F32 b) { Lane_F32 r = lane_f32(a) / b; return(r); } LANE_PUBLIC_DEC Lane_F32 operator/=(Lane_F32 &a, Lane_F32 b) { a = a / b; return(a); } // Add LANE_PUBLIC_DEC Lane_F32 operator+(Lane_F32 a, float b) { Lane_F32 r = a + lane_f32(b); return(r); } LANE_PUBLIC_DEC Lane_F32 operator+(float a, Lane_F32 b) { Lane_F32 r = lane_f32(a) + b; return(r); } LANE_PUBLIC_DEC Lane_F32 operator+=(Lane_F32 &a, Lane_F32 b) { a = a + b; return(a); } // Subtract LANE_PUBLIC_DEC Lane_F32 operator-(Lane_F32 a) { Lane_F32 r = lane_f32_zero() - a; return(r); } LANE_PUBLIC_DEC Lane_F32 operator-(Lane_F32 a, float b) { Lane_F32 r = a - lane_f32(b); return(r); } LANE_PUBLIC_DEC Lane_F32 operator-(float a, Lane_F32 b) { Lane_F32 r = lane_f32(a) - b; return(r); } LANE_PUBLIC_DEC Lane_F32 operator-=(Lane_F32 &a, Lane_F32 b) { a = a - b; return(a); } LANE_PUBLIC_DEC float horizontal_add(Lane_F32 a) { float r = 0; float *v = (float *)&a.v; for(uint32_t i = 0; (i < LANE_WIDTH); ++i) { r += v[i]; } return(r); } LANE_PUBLIC_DEC Lane_U32 operator>(Lane_F32 a, float b) { Lane_U32 r = (a > lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_U32 operator>=(Lane_F32 a, float b) { Lane_U32 r = (a >= lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_U32 operator<(Lane_F32 a, float b) { Lane_U32 r = (a < lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_U32 operator<=(Lane_F32 a, float b) { Lane_U32 r = (a <= lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_U32 operator==(Lane_F32 a, float b) { Lane_U32 r = (a == lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_U32 operator!=(Lane_F32 a, float b) { Lane_U32 r = (a != lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_F32 maxf32(Lane_F32 a, float b) { Lane_F32 r = maxf32(a, lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_F32 maxf32(float a, Lane_F32 b) { Lane_F32 r = maxf32(lane_f32(a), b); return(r); } LANE_PUBLIC_DEC Lane_F32 minf32(Lane_F32 a, float b) { Lane_F32 r = minf32(a, lane_f32(b)); return(r); } LANE_PUBLIC_DEC Lane_F32 minf32(float a, Lane_F32 b) { Lane_F32 r = minf32(lane_f32(a), b); return(r); } LANE_PUBLIC_DEC Lane_F32 lerp(Lane_F32 t, Lane_F32 a, Lane_F32 b) { Lane_F32 r = (lane_f32(1.0f) - t) * a + t * b; return(r); } LANE_PUBLIC_DEC Lane_F32 lerp(float t, Lane_F32 a, Lane_F32 b) { Lane_F32 r = (lane_f32(1.0f) - lane_f32(t)) * a + t * b; return(r); }
e9dff146044ddd15179c3b6dc9bcae46d06a893e
f458a8869bf59b5610b7bde490fa4d971f4d2e7c
/NumericalVariableEquation.h
1790cd83ea0aa83be234dbf8c4b4bcb85a9f927f
[]
no_license
gr331-mipt/vichmatyLab4var3
782e6b39d15d91a5a9da1f7e8fd2d7e26c75c3b6
29411e1e36e0fdc7cb0c5a2739ca0da2b963b584
refs/heads/master
2021-01-12T15:33:55.559595
2016-10-24T20:15:24
2016-10-24T20:15:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
NumericalVariableEquation.h
// // Created by altair on 20.02.16. // #ifndef LAB4VAR3_NUMERICALVARIABLEEQUATION_H #define LAB4VAR3_NUMERICALVARIABLEEQUATION_H #include "NumericalConstEquation.h" class NumericalVariableEquation: public NumericalConstEquation { mydouble getA(mydouble l); mydouble getB(mydouble l); mydouble getC(mydouble l); mydouble getD(mydouble l); bool isRound(size_t l) { return NumericalConstEquation::isRound(l * h * 10); } public: virtual ListPoints getSolution() override; }; #endif //LAB4VAR3_NUMERICALVARIABLEEQUATION_H
b0b28734700aa91adb35012c879c69de87fd9016
0d085b4ee7537095ff0d0b1f12cb486329800dce
/Lang/iostream.cpp
504879ede5acbfd0c5eb251469e4a257b50dcafe
[]
no_license
YongHoonJJo/CPP
f3043e5bca1314fa9954e82fb3b481ef25a56c6f
1cfdda3fddb86d7f010401bbc9bfc4330e9cd324
refs/heads/master
2021-01-02T23:04:51.188049
2017-09-03T11:09:31
2017-09-03T11:09:31
99,462,878
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
iostream.cpp
#include <iostream> #include <string> using namespace std; int main() { cout << "input a number: "; int n; cin >> n; cout << "Your input : " << n << endl; // cin, cout, endl are Object and exist in std. cout << "input two number: "; int a, b; cin >> a >> b; cout << "Your first number: " << a << endl; cout << "Your second number: " << b << endl; double f; cout << "input a decimal: "; cin >> f; cout << "Your input: " << f << endl; // in : 3.14 // out : 3.14 cout << "input a decimal: "; cin >> f; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << "Your input: " << f << endl; // in : 3.14 // out : 3.140 /*** <string> ***/ string str1, str2, str3; cout << "input two words: "; cin >> str1 >> str2; str3 = str1 + str2; cout << "mixed word is " << str3 << endl; cout << "str3[1] : " << str3[1] << endl; str1 = "Power"; str2 = "Kim"; str3 = str1 + str2; cout << "mixed word is " << str3 << endl; cout << "str3[1] : " << str3[1] << endl; // string is a Object and exists in std too. }
3b3dc36d573399986b1438d2d46fc67aab41b4ec
3293f82fdf0cb7dd90ad34f24e628d2c40705a29
/stock_analyzer/stock.h
8e9c4a5144a6846b10558b42e607576b72f86785
[]
no_license
gregorthebigmac/analyzer
fef72c1de736ec80510ba0fc36440182eae934ac
0ace0d1f046518c03d50eb4ca5d6904de69a9d88
refs/heads/master
2021-01-16T21:29:18.562225
2016-08-13T13:42:03
2016-08-13T13:42:03
64,594,954
0
0
null
null
null
null
UTF-8
C++
false
false
3,971
h
stock.h
#pragma once #ifndef STOCK_H #define STOCK_H #include <iostream> #include <fstream> #include <vector> #include <boost/lexical_cast.hpp> using namespace std; class stock { public: stock(); ~stock(); // getters string get_name() { return m_name; } int get_days() { return m_number_of_continuous_running_days; } string get_symbol() { return m_symbol; } float get_size_of_change() { return m_change.size(); } float get_change(); int get_num_errors() { return m_err_report.size(); } float get_current_price(); float get_percent_change(); float get_52_wk_low(); float get_percent_change_from_52_week_low(); // setters void set_name(string symbol) { m_symbol = symbol; } // todo void load_data(); void parse_data(); void bad_data(string data); float calculate_daily_avg_percentage_diff(); void make_a_date(); // debug void dump_data(); void print_error_report(); void write_error_log(ofstream &fout); void write_element_sizes_to_file(ofstream& fout); private: // easiest way to create an integer date from the string m_str_date struct date_stamp { int year; int month; int day; }; int m_number_of_continuous_running_days; vector<string> m_err_report; // this is used for internal errors and exception handling vector<string> m_data; // this will be used for getting raw data from files as strings. temp storage ONLY!! // m_data will be used in method void parse_data() // member variables are listed in the order in which they are received in the yahoo csv file. // refer to reference.txt for explanations of data string m_str_date; vector<date_stamp> m_date; string m_error; // error report from yahoo, in case the stock moved or no longer exists vector<float> m_ask; vector<int> m_average_daily_volume; vector<int> m_ask_size; vector<float> m_bid; vector<float> m_book_value; vector<int> m_bid_size; //vector<float> m_percent_change; // test: Phasing this out vector<float> m_change; vector<float> m_dividend_share; vector<string> m_last_trade_date; vector<float> m_earnings_share; vector<float> m_eps_estimate_current_year; vector<float> m_eps_estimate_next_year; vector<float> m_eps_estimate_next_quarter; vector<string> m_float_shares; // float--as in the economic definition--not the data type vector<float> m_day_low; vector<float> m_day_high; vector<float> m_52_week_low; vector<string> m_market_capitalization; vector<string> m_shares_outstanding; vector<string> m_EBITDA; vector<float> m_change_from_52_week_low; vector<float> m_percent_change_from_52_week_low; vector<float> m_52_week_high; vector<int> m_last_trade_size; vector<float> m_change_from_52_week_high; vector<float> m_percent_change_from_52_week_high; vector<float> m_last_trade_price; vector<string> m_day_range; vector<float> m_50_day_moving_average; vector<float> m_200_day_moving_average; vector<float> m_change_from_200_day_moving_average; vector<float> m_percent_change_from_200_day_moving_average; vector<float> m_change_from_50_day_moving_average; vector<float> m_percent_change_from_50_day_moving_average; vector<float> m_open; vector<float> m_previous_close; vector<float> m_change_in_percent; // fix m_data[7] vector<float> m_price_sales; vector<float> m_price_book; vector<string> m_ex_dividend_date; vector<float> m_pe_ratio; vector<string> m_dividend_pay_date; vector<float> m_peg_ratio; vector<float> m_price_of_eps_estimate_current_year; vector<float> m_price_of_eps_estimate_next_year; string m_symbol; // this data will never change, so it doesn't need to be a vector vector<string> m_revenue; vector<float> m_short_ratio; vector<string> m_last_trade_time; vector<float> m_1_yr_target_price; vector<int> m_volume; vector<string> m_52_week_range; string m_stock_exchange; // this data will never change, so it doesn't need to be a vector vector<float> m_dividend_yield; string m_name; // this data will never change, so it doesn't need to be a vector }; #endif // !STOCK_H
2627ea2289978930a894df7d610959677d605199
37b1e69f2e180d495b54e920511a7d973e22d85c
/areaAndPerimeterOfRectangle.cpp
42e5f5a79ec6b579995fc696df47bbcb39039c15
[]
no_license
crestel-ong/Unit2-02-CPP-area_of_rectangle
f52c65c2b909567d44b55bde4b6d5a8ddbbd50e6
c6ec6ab9c0e74f17a1e8d655e9b0b265e362fbbe
refs/heads/main
2023-08-17T22:06:55.771076
2021-09-14T22:25:15
2021-09-14T22:25:15
406,526,259
0
0
null
null
null
null
UTF-8
C++
false
false
882
cpp
areaAndPerimeterOfRectangle.cpp
// Copyright (c) 2021 Crestel Ong All rights reserved // Created by: Crestel Ong // Created on: September 2021 // This program calculates the area and perimeter of a rectangle // with length and width inputted from the user #include <iostream> int main() { // this function calculates area and perimeter int length; int width; int area; int perimeter; // input std::cout << "Enter length of the rectangle (mm): "; std::cin >> length; std::cout << "Enter width of the rectangle (mm): "; std::cin >> width; // process area = length*width; perimeter = 2 *(length+width); // output std::cout << "" << std::endl; std::cout << "Area is " << area << " mm²." << std::endl; std::cout << "Perimeter is " << perimeter << " mm." <<std::endl; std::cout << "" << std:: endl; std::cout << "Done." << std::endl; }
18fd5673a8ada80465e5818f435e55195b1bf92e
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/orttraining/orttraining/training_ops/rocm/math/div_grad.cc
03669e33e7d2e35a11d649eac1b6fbe2f7d3b568
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
9,957
cc
div_grad.cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "orttraining/training_ops/rocm/math/div_grad.h" #include "orttraining/training_ops/rocm/math/div_grad_impl.h" #include "core/providers/rocm/math/binary_elementwise_ops.h" using namespace onnxruntime::common; namespace onnxruntime { namespace rocm { #define DIVGRAD_REGISTER_KERNEL_TYPED(T) \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ DivGrad, \ kMSDomain, \ 1, \ T, \ kRocmExecutionProvider, \ (*KernelDefBuilder::Create()).TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \ DivGrad<T>); DIVGRAD_REGISTER_KERNEL_TYPED(MLFloat16) DIVGRAD_REGISTER_KERNEL_TYPED(float) // DIVGRAD_REGISTER_KERNEL_TYPED(double) TensorShapeVector prepended_dimension_1(const TensorShape& shape, size_t total_rank) { size_t input_rank = shape.NumDimensions(); if (input_rank == total_rank) return shape.AsShapeVector(); TensorShapeVector dims(total_rank, 1); // https://github.com/onnx/onnx/blob/main/docs/Broadcasting.md // for property 3 of Multidirectional Broadcasting, we need to prepended with a dimension of length 1. if (input_rank > 0) std::copy(shape.GetDims().begin(), shape.GetDims().end(), &dims[total_rank - input_rank]); return dims; } template <typename T> Status DivGrad<T>::ComputeInternal(OpKernelContext* context) const { typedef typename ToHipType<T>::MappedType HipT; const Tensor* dy_tensor = context->Input<Tensor>(0); const Tensor* a_tensor = context->Input<Tensor>(1); const Tensor* b_tensor = context->Input<Tensor>(2); const TensorShape& a_shape = a_tensor->Shape(); const TensorShape& b_shape = b_tensor->Shape(); const TensorShape& dy_shape = dy_tensor->Shape(); // output shapes shall match its corresponding inputs Tensor* da_output_tensor = context->Output(0, a_shape); Tensor* db_output_tensor = context->Output(1, b_shape); if (!da_output_tensor && !db_output_tensor) return Status::OK(); BinaryElementwisePreparation prepare; ORT_RETURN_IF_ERROR(BinaryElementwiseBroadcastPrepare(a_tensor, b_tensor, // TODO: BinaryElementwiseBroadcastPrepare shall take dy_tensor as const Tensor*. const_cast<Tensor*>(dy_tensor), &prepare)); const HipT* prepare_a_data = reinterpret_cast<const HipT*>(prepare.lhs_tensor->template Data<T>()); const HipT* prepare_b_data = reinterpret_cast<const HipT*>(prepare.rhs_tensor->template Data<T>()); const HipT* prepare_dy_data = reinterpret_cast<const HipT*>(prepare.output_tensor->template Data<T>()); T* da_data = da_output_tensor ? da_output_tensor->template MutableData<T>() : nullptr; T* db_data = db_output_tensor ? db_output_tensor->template MutableData<T>() : nullptr; switch (prepare.output_rank_or_simple_broadcast) { case static_cast<int32_t>(SimpleBroadcast::NoBroadcast): ImplDivGradSimple<HipT>( Stream(context), SimpleBroadcast::NoBroadcast, prepare_a_data, prepare_b_data, prepare_dy_data, dy_shape.Size(), reinterpret_cast<HipT*>(da_data), reinterpret_cast<HipT*>(db_data)); break; case static_cast<int32_t>(SimpleBroadcast::LeftScalar): { T* temp_da_data = nullptr; IAllocatorUniquePtr<T> temp_da_allocator; if (da_output_tensor) { temp_da_allocator = GetScratchBuffer<T>(dy_shape.Size(), context->GetComputeStream()); temp_da_data = temp_da_allocator.get(); } ImplDivGradSimple<HipT>( Stream(context), SimpleBroadcast::LeftScalar, prepare_a_data, prepare_b_data, prepare_dy_data, dy_shape.Size(), reinterpret_cast<HipT*>(temp_da_data), reinterpret_cast<HipT*>(db_data)); if (da_output_tensor) { auto a_output_dims = prepended_dimension_1(a_shape, dy_shape.NumDimensions()); ORT_RETURN_IF_ERROR((ReduceKernelShared<T, T, MIOPEN_REDUCE_TENSOR_NO_INDICES>( temp_da_data, dy_shape, da_data, TensorShape({}), MIOPEN_REDUCE_TENSOR_ADD, GetMiopenHandle(context), context->GetComputeStream(), a_output_dims))); } break; } case static_cast<int32_t>(SimpleBroadcast::RightScalar): { T* temp_db_data = nullptr; IAllocatorUniquePtr<T> temp_db_allocator; if (db_output_tensor) { temp_db_allocator = GetScratchBuffer<T>(dy_shape.Size(), context->GetComputeStream()); temp_db_data = temp_db_allocator.get(); } ImplDivGradSimple<HipT>( Stream(context), SimpleBroadcast::RightScalar, prepare_a_data, prepare_b_data, prepare_dy_data, dy_shape.Size(), reinterpret_cast<HipT*>(da_data), reinterpret_cast<HipT*>(temp_db_data)); if (db_output_tensor) { auto b_output_dims = prepended_dimension_1(b_shape, dy_shape.NumDimensions()); ORT_RETURN_IF_ERROR((ReduceKernelShared<T, T, MIOPEN_REDUCE_TENSOR_NO_INDICES>( temp_db_data, dy_shape, db_data, TensorShape({}), MIOPEN_REDUCE_TENSOR_ADD, GetMiopenHandle(context), context->GetComputeStream(), b_output_dims))); } break; } case static_cast<int32_t>(SimpleBroadcast::RightPerChannelBatch1): case static_cast<int32_t>(SimpleBroadcast::RightPerChannelBatchN): { T* temp_db_data = nullptr; IAllocatorUniquePtr<T> temp_db_allocator; if (db_output_tensor) { temp_db_allocator = GetScratchBuffer<T>(dy_shape.Size(), context->GetComputeStream()); temp_db_data = temp_db_allocator.get(); } if (prepare.output_rank_or_simple_broadcast == static_cast<int32_t>(SimpleBroadcast::RightPerChannelBatch1)) { // lhs(1,C,H) and rhs (C,1) ImplDivGradRhsPerChannelBatch1<HipT>( Stream(context), prepare_a_data, prepare_b_data, prepare_dy_data, dy_shape.Size(), prepare.fdm_H, reinterpret_cast<HipT*>(da_data), reinterpret_cast<HipT*>(temp_db_data)); } else { // lhs(N,C,H) and rhs (C,1) ImplDivGradRhsPerChannelBatchN<HipT>( Stream(context), prepare_a_data, prepare_b_data, prepare_dy_data, dy_shape.Size(), prepare.fdm_H, prepare.fdm_C, reinterpret_cast<HipT*>(da_data), reinterpret_cast<HipT*>(temp_db_data)); } if (db_output_tensor) { auto b_output_dims = prepended_dimension_1(b_shape, dy_shape.NumDimensions()); ORT_RETURN_IF_ERROR((ReduceKernelShared<T, T, MIOPEN_REDUCE_TENSOR_NO_INDICES>( temp_db_data, dy_shape, db_data, b_shape, MIOPEN_REDUCE_TENSOR_ADD, GetMiopenHandle(context), context->GetComputeStream(), b_output_dims))); } break; } default: { bool need_reduce_da = da_output_tensor && a_shape.Size() != dy_shape.Size(); bool need_reduce_db = db_output_tensor && b_shape.Size() != dy_shape.Size(); IAllocatorUniquePtr<T> temp_da_allocator, temp_db_allocator; T* da_data_ref = nullptr; if (da_output_tensor) { if (need_reduce_da) { temp_da_allocator = GetScratchBuffer<T>(dy_shape.Size(), context->GetComputeStream()); da_data_ref = temp_da_allocator.get(); } else { da_data_ref = da_data; } } T* db_data_ref = nullptr; if (db_output_tensor) { if (need_reduce_db) { temp_db_allocator = GetScratchBuffer<T>(dy_shape.Size(), context->GetComputeStream()); db_data_ref = temp_db_allocator.get(); } else { db_data_ref = db_data; } } ImplDivGrad<HipT>( Stream(context), prepare.output_rank_or_simple_broadcast, prepare.lhs_padded_strides, prepare_a_data, prepare.rhs_padded_strides, prepare_b_data, prepare_dy_data, dy_shape.Size(), prepare.fdm_output_strides, reinterpret_cast<HipT*>(da_data_ref), reinterpret_cast<HipT*>(db_data_ref)); if (need_reduce_da) { auto a_output_dims = prepended_dimension_1(a_shape, dy_shape.NumDimensions()); ORT_RETURN_IF_ERROR((ReduceKernelShared<T, T, MIOPEN_REDUCE_TENSOR_NO_INDICES>( da_data_ref, dy_shape, da_data, a_shape, MIOPEN_REDUCE_TENSOR_ADD, GetMiopenHandle(context), context->GetComputeStream(), a_output_dims))); } if (need_reduce_db) { auto b_output_dims = prepended_dimension_1(b_shape, dy_shape.NumDimensions()); ORT_RETURN_IF_ERROR((ReduceKernelShared<T, T, MIOPEN_REDUCE_TENSOR_NO_INDICES>( db_data_ref, dy_shape, db_data, b_shape, MIOPEN_REDUCE_TENSOR_ADD, GetMiopenHandle(context), context->GetComputeStream(), b_output_dims))); } } } return Status::OK(); } } // namespace rocm } // namespace onnxruntime
4e07cd374df1e48884bf6f5d6efcf4f772493619
5f06033c7d151227919907288a1458d97c6e6d27
/Studio Project 3/Base/Source/WalkCamera.cpp
b48f25d9d2a257c096194eca7eb5c5d8d060dd22
[]
no_license
kwanliang/SP3-Team-9
bb43df5bbe8dee3366c775adfec3172329be70d0
e26db09351e1663e73f45499ef8f5f30c9b9f12d
refs/heads/master
2020-12-01T15:38:07.896753
2016-09-01T08:22:59
2016-09-01T11:55:52
66,514,254
0
0
null
null
null
null
UTF-8
C++
false
false
1,795
cpp
WalkCamera.cpp
#include "WalkCamera.h" const float maxPitch = 80; const float minPitch = -80; WalkCamera::WalkCamera() : yOffset(0) { } WalkCamera::~WalkCamera() { } void WalkCamera::Init( const Vector3 &pos, const Vector3 &dir, const Vector3 &up, const float &distance, const Vector3 &vertical) { ThirdPersonCamera::Init(pos, dir, up, distance); this->vertical = vertical; this->vertical.Normalize(); } void WalkCamera::Move(const Vector3 &v) { pos += v; } void WalkCamera::Move(const float &frontDist, const float &sideDist, const float &upDist, const bool &followUp) { Vector3 right = dir.Cross(up); Vector3 front = vertical.Cross(right); Vector3 view = pos - dir; view.Normalize(); right.Normalize(); front.Normalize(); pos += front * frontDist + right * sideDist ; if (followUp) pos += up * upDist; else pos += vertical * upDist; } void WalkCamera::Turn(const float &degrees) { Mtx44 rot; rot.SetToRotation(degrees, vertical.x, vertical.y, vertical.z); dir = rot * dir; up = rot * up; } void WalkCamera::Pitch(float degrees) { float angle = acos(dir.Dot(vertical)); angle = 90.f - Math::RadianToDegree(angle); if (degrees > 0) { if (angle + degrees > maxPitch) degrees = maxPitch - angle; } if (degrees < 0) { if (angle + degrees < minPitch) degrees = minPitch - angle; } Vector3 right = dir.Cross(up); Mtx44 rot; rot.SetToRotation(degrees, right.x, right.y, right.z); dir = rot * dir; up = rot * up; } Mtx44 WalkCamera::GetView() { Vector3 eye = pos - dir * distance + Vector3(0, yOffset, 0); Vector3 center = pos + Vector3(0, yOffset, 0); Mtx44 view; view.SetToLookAt( (double)eye.x, (double)eye.y, (double)eye.z, (double)center.x, (double)center.y, (double)center.z, (double)up.x, (double)up.y, (double)up.z ); return view; }
35403592a1aa088ad2e7f0473f99c8715453d30e
7d0be48c377429d297c8743be155f8eec408100a
/21.01 - Busca/1198-feito.cpp
ad98515da4aa24a261e12e528d15c211d3ae59b2
[]
no_license
MatheusBlanco/EDA
94b0520fd0297d572bf8d181dce3a4912dfe79e5
5970f1c28be41cf3dc6e2448ff3fe6635dbaf0eb
refs/heads/master
2020-04-17T22:07:28.497334
2019-02-05T23:19:30
2019-02-05T23:19:30
166,981,333
0
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
1198-feito.cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; int main(){ int heroes, villains, sub; while(cin >> heroes >> villains){ if(heroes > villains){ cout << (heroes - villains) << endl; } else{ cout << (villains - heroes) << endl; } } return 0; }
82a8820bd814a8938249b985ac562bc7abddc1be
5dba24249f360186963a1f5c56b4543d5b612cef
/GameEngine_GameLoop/Assignment1/Main.cpp
10f481a1641beea0178571b2146bc28b8a1c661c
[]
no_license
dbrandt2/DanPortfolio
0d83fd0bf8a6a97c3c74a9b077e8ecfc2d909b59
8dadac90c90ace5bbb6398da9273acfae3f3cf0a
refs/heads/master
2020-05-14T22:46:34.118549
2020-02-24T01:52:19
2020-02-24T01:52:19
181,983,028
0
0
null
null
null
null
UTF-8
C++
false
false
1,706
cpp
Main.cpp
#include <iostream> #include <string> #include <chrono> #include <thread> #include <conio.h> #include <thread> #include "PhysicsManager.h" #include "RenderManager.h" #include "SoundManager.h" #include "FileSystemManager.h" #include "MemoryManager.h" #include "TextureManager.h" #include "AnimationManager.h" #include "Monobehaviour.h" #include "Vector3.h" #include "GameWorld.h" #include "GameManager.h" using namespace std; int main() { //initialize game world GameWorld(); //array of pointers to managers Monobehaviour** managers = new Monobehaviour*[8]; float milliSecondsFrameSpeed = 66.6; //66.6 = 15 fps //add managers to array managers[0] = &MemoryManager::getInstance(); managers[1] = &FileSystemManager::getInstance(); managers[2] = &AnimationManager::getInstance(); managers[3] = &PhysicsManager::getInstance(); managers[4] = &RenderManager::getInstance(); managers[5] = &SoundManager::getInstance(); managers[6] = &TextureManager::getInstance(); managers[7] = &GameManager::getInstance(); //Start each manager for (int i = 0; i <= 7; i++) { managers[i]->Start(); } //update each manager for (int i = 0; i <= 7; i++) { managers[i]->Update(); } //Game Loop while (true) { //frames per seconds auto currTime = chrono::high_resolution_clock::now(); managers[7]->Update(); auto endTime = chrono::high_resolution_clock::now(); auto realTime = int((milliSecondsFrameSpeed - chrono::duration_cast<chrono::milliseconds>(endTime - currTime).count())); this_thread::sleep_for(chrono::milliseconds(realTime)); } //shutdown each manager in reverse order for (int i = 7; i >= 0; i--) { managers[i]->Shutdown(); } char c; cin.get(); return 0; }
54200112bbc31b9a25dc903c3edef4892abdd6f1
625af6c0df835b0d2e10392361ea5976413f2018
/src/include/InputOutput.h
57e727eb3be93356ff1cabe7481ad4944baaffd0
[]
no_license
SharonHxr/tw2017
7fca96e818513d2f0bc9a6a589062f680f656ef8
90e4d0ec588febc8b9f32f33d84dff066a766df2
refs/heads/master
2021-06-24T14:15:38.453484
2017-09-11T14:27:40
2017-09-11T14:27:40
103,077,267
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
InputOutput.h
#ifndef _H_INPUTOUTPUT_ #define _H_INPUTOUTPUT_ #include <string> #include <stdio.h> #include "Schedule.h" #include "PlayGround.h" class InputOutput{ public: static bool parse(const std::string &str, Date &date,ScheduleItem &item,char &ground,bool &cancel); static void showInputInvalid(); static void showBookingSuccessed(); static void showBookingConflict(); static void showCancelNotExist(); static void showPlayGround( const std::string &name, PlayGround &pg ); }; #endif
2156f96911ed306c93bd880d553f03898fb880ac
e696368075df887e7bb4b0aa032b4c9fc9348532
/PermutationCyclesOptimization/main.cpp
3a1e500235b35144f4d158fb44023714e009dcbd
[]
no_license
kkoltunski/algorithms
c07c8f3bafe84dfecec716176144a59560db8590
3666157e5512467f0dc8c3c3b89b3905f75bf0db
refs/heads/master
2021-05-26T10:25:04.172609
2021-01-26T16:47:46
2021-01-26T16:47:46
254,095,461
0
0
null
null
null
null
UTF-8
C++
false
false
552
cpp
main.cpp
#include "ElephantsData.h" #include "FileParser.h" #include "CoreAlgorithm.h" #include <iostream> int main(int argc, char* argv[]) { if (argc > 1 && argc < 3) { try { ElephantsData elephants; FileParser documentReader(argv[1], &elephants); documentReader.openFile(); documentReader.parseFile(); CoreAlgorithm algorithm(&elephants); algorithm.computeOptimalWork(); std::cout << "Result = " << algorithm.getOptimalWork() << std::endl; } catch (std::exception _e) { std::cout << _e.what() << std::endl; } } return 0; }