blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
858cd91a128229a3ad05d3725093833dc8be7d80
a4e927d4100400c22ce8e8288d2bb5ad271155b9
/vectorops.hpp
a072d45483188231abd541f0668ee5f7b4787511
[ "MIT" ]
permissive
heyrichardshi/random-walk
c7c7a82f91cea5b0dbc8b8089cf8a9c7146c3efe
d37ee577a628e9acbdb441381b9403c2ce96a4b2
refs/heads/master
2020-05-02T06:53:10.605794
2019-04-01T01:13:24
2019-04-01T01:13:24
177,805,507
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
hpp
#ifndef RANDOMWALKS_VECTOROPS_HPP #define RANDOMWALKS_VECTOROPS_HPP #include <cmath> #include <vector> using namespace std; double magnitude(vector<int> v) { return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } double magnitude(vector<double> v) { return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } vector<int> difference(vector<int> a, vector<int> b) { int c[3] = {0}; c[0] = a[0] - b[0]; c[1] = a[1] - b[1]; c[2] = a[2] - b[2]; vector<int> v(c, c + sizeof(c) / sizeof(double)); return v; } vector<double> difference(vector<int> a, vector<double> b) { double c[3] = {0}; c[0] = a[0] - b[0]; c[1] = a[1] - b[1]; c[2] = a[2] - b[2]; vector<double> v(c, c + sizeof(c) / sizeof(double)); return v; } vector<double> difference(vector<double> a, vector<double> b) { double c[3] = {0}; c[0] = a[0] - b[0]; c[1] = a[1] - b[1]; c[2] = a[2] - b[2]; vector<double> v(c, c + sizeof(c) / sizeof(double)); return v; } double rms(vector<double> v) { double total = 0; for (auto i : v) { total += i * i; } total = sqrt(total / v.size()); return total; } #endif //RANDOMWALKS_VECTOROPS_HPP
[ "noreply@github.com" ]
noreply@github.com
18dde4aae2aac44e3a3d1c86b8131a8458cd6111
84b9dd141734d46fe643efdb02bbd19dd58bf49c
/Fundamental Algorithms/Lab 2/articulation Points (puncte critice).cpp
91adc6b7a805e4f7a7d12902ec8299e8725bec8b
[]
no_license
cosminbvb/Uni
a8748fc77b2d34a2f419fe6dd507f9b73cbc8f78
6acbae2a4fca728435d6a6740b3d33758efb215a
refs/heads/master
2023-03-13T20:22:53.423358
2021-09-11T11:30:59
2021-09-11T11:30:59
240,605,555
25
1
null
2023-03-03T08:24:22
2020-02-14T21:58:29
Python
UTF-8
C++
false
false
2,969
cpp
//Puncte critice / Articulation Points #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <set> using namespace std; int n, m; vector<int>* adj = NULL; int* nivel; // nivel[i] = nivelul nodului i in arborele DF int* niv_min; // niv_min[i] = nivelul minim la care se inchide un ciclu elementar // care contine varful i (printr-o muchie de intoarcere) int* viz; int* tata; int start; set<int> puncte; // am folosit set pt ca daca un varf v e sters // si sparge graful in mai mult de 2 componente conexe // va aparea de (nr de comp conexe - 1 ori) cred // si noi pt problema asta vrem doar sa afisam punct // un varf v e critic <=> exista doua varfuri x,y != v a.i. // v apartine oricarui x,y-lant // in arborele DF, radacina s e punct critic <=> are cel putin 2 fii // in arborele DF, un alt varf i din arbore e critic <=> // are cel putin un fiu j cu niv_min[j] >= nivel[i] void read() { ifstream f("graf.in"); f >> n >> m; adj = new vector<int>[n + 1]; for (int i = 0; i < m; i++) { int x, y; f >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } f.close(); } void df(int i) { viz[i] = 1; niv_min[i] = nivel[i]; for (int j : adj[i]) { if (viz[j] == 0) { //ij muchie de avansare nivel[j] = nivel[i] + 1; tata[j] = i; df(j); //actualizare niv_min[i] niv_min[i] = min(niv_min[i], niv_min[j]); //test i punct critic if (niv_min[j] >= nivel[i]) { if (i == start) { //cazul cu radacina int nr = 0; for (int i = 1; i <= n; i++) { if (tata[i] == start) nr++; } if (nr >= 2) { puncte.insert(i); } } else puncte.insert(i); } } else { if (nivel[j] < nivel[i] - 1) { //ij muchie de intoarcere //actualizare niv_min[i] niv_min[i] = min(niv_min[i], nivel[j]); } } } } int main() { read(); nivel = new int[n + 1]; niv_min = new int[n + 1]; viz = new int[n + 1]; tata = new int[n + 1]; for (int i = 1; i <= n; i++) { nivel[i] = -1; niv_min[i] = -1; viz[i] = 0; tata[i] = -1; } //luam nodul de start ca fiind 1 //daca avem mai multe componente conexe putem aplica //df pe nodurile nevizitate cu un for dar in cazul asta //pp ca graful e conex start = 1; nivel[start] = 1; df(start); for (int i : puncte) cout << i << " "; } /* 10 13 1 5 1 10 3 5 5 6 5 9 5 10 3 6 3 7 6 7 2 4 2 6 2 8 4 8 => 2 5 6 */
[ "cosmin.petrescu@my.fmi.unibuc.ro" ]
cosmin.petrescu@my.fmi.unibuc.ro
bfc9a4cd251e6d9b6d3bf2b672cc8d8f4d9a053d
bb75c662324baa739ab1edba84ca62c443f56cb5
/pr_sacn.cpp
25cce6eed6a7bec2a466a9782e6e85c031fe1901
[]
no_license
AparnaSGhenge/Hello_World
b2b79ac898df5f6c09ca8febfb128c724d08f013
6103c06309e13c1c78ecb5d2ed644f289196284a
refs/heads/master
2021-10-14T11:30:42.987211
2021-10-12T13:35:21
2021-10-12T13:35:21
149,583,064
0
8
null
2021-06-28T06:53:23
2018-09-20T09:14:49
C
UTF-8
C++
false
false
386
cpp
#include <iostream> using namespace std; int main() { cout << "Enter two integers: "; cin >> firstNumber >> secondNumber; // sum of two numbers in stored in variable sumOfTwoNumbers sumOfTwoNumbers = firstNumber + secondNumber; // Prints sum cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers; return 0; }
[ "aparna.ghenge@embold.io" ]
aparna.ghenge@embold.io
ac6c22ea9a8c64705a13dcb7127bc1dc31f5c4c6
00231bd4b5b3c42cbfc281eabbea8a6d77d30fef
/operators.cpp
68e2bb9daed0b530f1f7f13fc7f4a037513f6e51
[]
no_license
Allarepossible/algorithms
36950d04d8130081f4ab38169d0a9524cb7b9c81
5243ff09463442cb270d3485a5c315ee84f06126
refs/heads/master
2020-06-12T01:48:07.003148
2019-12-05T17:43:53
2019-12-05T17:43:53
194,156,843
0
0
null
2019-10-28T08:01:51
2019-06-27T20:09:56
JavaScript
UTF-8
C++
false
false
3,293
cpp
#include <iostream> using namespace std; int NOD(int a, int b) { int r; if (b > a) std::swap(a,b); while (b != 0) { r = a % b; a = b; b = r; } return a; } int NOK(int a, int b) { return a * b / NOD(a, b); } class RationalNumber { private: int m_numerator; int m_denominator; void Red() { int n = NOD(this->m_numerator, this->m_denominator); this->m_numerator = this->m_numerator / n; this->m_denominator = this->m_denominator / n; } public: friend RationalNumber RationalY(const RationalNumber& element); friend double Y(const RationalNumber& element); friend ostream& operator<< (ostream& out, const RationalNumber& element); friend istream& operator>> (istream& in, RationalNumber& element); RationalNumber() { m_numerator = 1; m_denominator = 2; } RationalNumber(int numerator, int denominator) { m_numerator = numerator; m_denominator = denominator; Red(); } RationalNumber(double numerator) { m_numerator = numerator*10; m_denominator = 10; Red(); } RationalNumber operator+ (const RationalNumber& element) { double k1, k2; RationalNumber S; S.m_denominator = this->m_denominator * element.m_denominator; k1 = S.m_denominator / element.m_denominator; k2 = S.m_denominator / this->m_denominator; S.m_numerator = k2*this->m_numerator + k1*element.m_numerator; S.Red(); return S; } RationalNumber operator* (const RationalNumber& element) { RationalNumber C; C.m_denominator = this->m_denominator * element.m_denominator; C.m_numerator = this->m_numerator * element.m_numerator; C.Red(); return C; } RationalNumber operator/ (const RationalNumber& element) { RationalNumber D; D.m_denominator = this->m_denominator * element.m_numerator; D.m_numerator = this->m_numerator * element.m_denominator; D.Red(); return D; } }; RationalNumber RationalY(const RationalNumber& element) { RationalNumber a = 2; RationalNumber b = 1.3; RationalNumber res = a * element + b / element; res.Red(); return res; } double Y(const RationalNumber& element) { double deistv = (double)element.m_numerator / element.m_denominator; return 2 * deistv + 1.3 / deistv; } void CreateTable() { for (int i = -10; i <= 10; i++) { if (i != 0) { RationalNumber r = (double)i/10; cout << "x= " << (double)i/10 << " \t y = " << RationalY(r) << " \t y1 = " << Y(r) << endl; } } } ostream& operator<< (ostream& out, const RationalNumber& element) { out << element.m_numerator << "/" << element.m_denominator; return out; } istream& operator>> (istream& in, RationalNumber& element) { cout << "Введите числитель: "; in >> element.m_numerator; cout << "Введите знаменатель: "; in >> element.m_denominator; element.Red(); return in; } int main() { setlocale(LC_ALL, "Russian"); CreateTable(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
97cb0b8567e462b12cdd9ef3ed74ec885df2166c
928beefa16471c6b640651914e909ca2c7dd1e70
/CFG.cpp
111596fcbe7d3c36ba7ef5ea08d727b9c42d867b
[]
no_license
YichaoLee/BRICK-test
b859762d7b60744395d020ab71e4be4dd2e1a76f
83c6b10ce27122099e0e494420ff3a838edbe7c0
refs/heads/master
2021-01-13T04:39:14.200200
2017-06-30T13:59:12
2017-06-30T13:59:12
79,446,611
0
0
null
null
null
null
UTF-8
C++
false
false
23,397
cpp
#include "CFG.h" using namespace std; int Transition::tran_id = 0; void printPath(CFG *cfg, vector<int> path){ cerr<<"Path route: "; for(unsigned i=0;i<path.size();i++){ int id = path[i]; State *s = cfg->searchState(id); if(s==NULL) cerr<<"printPath state error "<<id<<"\n"; if(i<path.size()-1){ cerr<<s->name<<"->"; Transition *t = cfg->searchTransition(path[++i]); if(t==NULL) cerr<<"\nprintPath transition error "<<path[i]<<"\n"; assert(t!=NULL); cerr<<t->name<<"->"; } else cerr<<s->name<<"("<<s->ID<<")"<<endl; } } void CFG::InsertCFGState(int id,string name,string funcName) { State* tmp = new State(id,name,funcName); this->stateMap.insert(pair<int,State*>(tmp->ID,tmp)); } CFG global_CFG; void CFG::InsertCFGTransition(Transition* tr) { this->transitionMap.insert(pair<int,Transition*>(tr->ID,tr)); } void CFG::InsertCFGLabel(string Label, State *s){ LabelMap.insert( pair<string,State*> (Label,s)); for(unsigned int i=0;i<transitionList.size();i++){ if(transitionList[i].toLabel == Label&&transitionList[i].toState==NULL) { transitionList[i].toName = s->name; transitionList[i].toState = s; //errs()<<"SLOT%"<<Label<<"\tsName:\t"<<s->name<<"\n\n\n"; }; } for(unsigned int i=0;i<stateList.size();i++) { State s1= stateList[i]; for(unsigned int j=0;j<s1.transList.size();j++) { if(s1.transList[j]->toLabel == Label && s1.transList[j]->toState == NULL) { s1.transList[j]->toName = s->name; s1.transList[j]->toState = s; } } } errs()<<"func\t"<<Label <<"\t"<< s->name<<"\n"; } //stateList&transitionList----->Map bool CFG::initial(){ stateMap.clear(); stateStrMap.clear(); nameMap.clear(); transitionMap.clear(); transitionStrMap.clear(); this->counter_transition = 0; /* for(int i=0;i<stateList.size();i++) errs()<<stateList[i]<<"\n"; for(int i=0;i<transitionList.size();i++) errs()<<transitionList[i]<<"\n"; */ int count=1; for(unsigned int i=0;i<stateList.size();i++){ State* st=&stateList[i]; // errs()<<st->ID<<"\t"<<st->nextS<<"\n"; st->transList.clear(); if(i==0){ // initialState=st; st->ID=0; // st->isInitial=true; } else st->ID=count++; if(st->isInitial) initialState=st; stateMap.insert(pair<int, State*>(st->ID, st)); stateStrMap.insert(pair<string, State*>(st->name, st)); nameMap.insert(pair<int, string>(st->ID, st->name)); for(unsigned int j=0;j<transitionList.size();j++){ Transition* tran=&transitionList[j]; if(st->name==tran->fromName){ st->transList.push_back(tran); tran->fromState=st; } else if(st->name==tran->toName){ tran->toState=st; } } } for(unsigned int i=0;i<transitionList.size();i++){ Transition* tran=&transitionList[i]; tran->ID=count++; transitionMap.insert(pair<int, Transition*>(tran->ID,tran)); transitionStrMap.insert(pair<string, Transition*>(tran->name, tran)); nameMap.insert(pair<int, string>(tran->ID, tran->name)); if(tran->toState==NULL){ errs()<<"warning: can not find the tostate of the transition: "<<tran->name<<"\n"; errs()<<tran->name<<" toLabel "<<tran->toLabel<<"\n"; // return false; } } if(initialState==NULL){ errs()<<"Warning: there is no initial state.\n"; State* st=&stateList[0]; st->isInitial=true; initialState=st; // return false; } // errs()<<"cfg initialed~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return true; } bool CFG::isLinear(){ return linear; } void CFG::setModeLock(){ modeLock = true; } void CFG::setUnlinear(){ if(!modeLock) linear = false; } void CFG::setLinear(){ if(!modeLock) linear = true; } bool CFG::is_state(const int ID){ if((unsigned)ID < stateList.size()) return true; return false; } bool CFG::hasVariable(string name){ for(unsigned int i = 0; i < variableList.size(); i ++){ if(variableList[i].name == name) return true; } return false; } Variable* CFG::getVariable(string name){ Variable* var = NULL; for(unsigned int i = 0; i < variableList.size(); i ++){ if(variableList[i].name == name) var = &(variableList[i]); } return var; } string CFG::getNodeName(int i){ if(nameMap.find(i)==nameMap.end()) return string(); return nameMap[i]; } State* CFG::searchState(int stateID) { if(stateMap.find(stateID)==stateMap.end()) return NULL; return stateMap[stateID]; } Transition* CFG::searchTransition(int transID) { if(transitionMap.find(transID)==transitionMap.end()) return NULL; return transitionMap[transID]; } raw_ostream& operator << (raw_ostream& os,Op_m& object){ switch(object){ case TRUNC:errs()<<" trunc ";break; case ZEXT:errs()<<" zext ";break; case SEXT:errs()<<" sext ";break; case FPTRUNC:errs()<<" fptrunc ";break; case FPEXT:errs()<<" fpext ";break; case FPTOUI:errs()<<" fptoui ";break; case FPTOSI:errs()<<" fptosi ";break; case UITOFP:errs()<<" uitofp ";break; case SITOFP:errs()<<" sitofp ";break; case BITCAST:errs()<<" bitcast ";break; case ADD:case FADD:errs()<<" + ";break; case SUB:case FSUB:errs()<<" - ";break; case AND:errs()<<" and ";break; case NAND:errs()<<" nand ";break; case OR:errs()<<" or ";break; case XOR:errs()<<" xor ";break; case TAN:errs()<<" tan ";break; case ATAN:errs()<<" atan ";break; case ATAN2:errs()<<" atan2 ";break; case SIN:errs()<<" sin ";break; case ASIN:errs()<<" asin ";break; case COS:errs()<<" cos ";break; case ACOS:errs()<<" acos ";break; case SQRT:errs()<<" sqrt ";break; case POW:errs()<<" pow ";break; case LOG:errs()<<" log ";break; case LOG10:errs()<<" log10 ";break; case ABS:errs()<<" abs ";break; case FABS:errs()<<" fabs ";break; case EXP:errs()<<" exp ";break; case SINH:errs()<<" sinh ";break; case COSH:errs()<<" cosh ";break; case TANH:errs()<<" tanh ";break; case MUL:case FMUL:errs()<<" * ";break; case SDIV:case UDIV:case FDIV:errs()<<" / ";break; case GETPTR:errs()<<" getptr ";break; case ADDR:errs()<<" addr ";break; case STORE:errs()<<" store ";break; case LOAD:errs()<<" load ";break; case ALLOCA:errs()<<" alloca ";break; case SREM:case UREM:case FREM:errs()<<" % ";break; case ASHR:case LSHR:errs()<<" >> ";break; case SHL:errs()<<" << ";break; case slt:case ult:case flt:errs()<<" < ";break; case sle:case ule:case fle:errs()<<" <= ";break; case sgt:case ugt:case fgt:errs()<<" > ";break; case sge:case uge:case fge:errs()<<" >= ";break; case eq:case feq:errs()<<" == ";break; case ne:case fne:errs()<<" != ";break; case MKNAN:errs()<<" nan ";break; case ISNAN:errs()<<" isnan ";break; case ISINF:errs()<<" isinf ";break; case ISNORMAL:errs()<<" isnormal ";break; case ISFINITE:errs()<<" isfinite ";break; case SIGNBIT:errs()<<" signbit ";break; case CLASSIFY:errs()<<" fpclassify ";break; case COPYSIGN:errs()<<" copysign ";break; case FESETROUND:errs()<<" fesetround ";break; case FEGETROUND:errs()<<" fegetround ";break; case CEIL:errs()<<" ceil ";break; case FLOOR:errs()<<" floor ";break; case ROUND:errs()<<" round ";break; case NEARBYINT:errs()<<" nearbyint ";break; case RINT:errs()<<" rint ";break; case FMAX:errs()<<" fmax ";break; case FMIN:errs()<<" fmin ";break; case FMOD:errs()<<" fmod ";break; case FDIM:errs()<<" fdim ";break; case REMAINDER:errs()<<" remainder ";break; case MODF:errs()<<" modf ";break; case FUNCTRUNC:errs()<<" functrunc ";break; case NONE:errs()<<" ";break; } return os; } raw_ostream& operator << (raw_ostream& os,Err& object){ switch(object){ case Assert:errs()<<" Assert Error ";break; case Spec:errs()<<" Spec Error ";break; case Div0:errs()<<" Div0 Error ";break; case DomainLog:errs()<<" DomainLog Error ";break; case DomainSqrt:errs()<<" DomainSqrt Error ";break; case DomainTri:errs()<<" DomainTri Error ";break; case Noerr:errs()<<" No Error ";break; } return os; } extern string get_m_Operator_str(Op_m op){ switch(op){ case TRUNC:return " trunc ";break; case ZEXT:return " zext ";break; case SEXT:return " sext ";break; case FPTRUNC:return " fptrunc ";break; case FPEXT:return " fpext ";break; case FPTOUI:return " fptoui ";break; case FPTOSI:return " fptosi ";break; case UITOFP:return " uitofp ";break; case SITOFP:return " sitofp ";break; case BITCAST:return " bitcast ";break; case GETPTR:return " getptr ";break; case ADD:case FADD:return " + ";break; case SUB:case FSUB:return " - ";break; case AND:return " and ";break; case NAND:return " nand ";break; case OR:return " or ";break; case XOR:return " xor ";break; case TAN:return " tan ";break; case ATAN:return " atan ";break; case ATAN2:return " atan2 ";break; case SIN:return " sin ";break; case ASIN:return " asin ";break; case COS:return " cos ";break; case ACOS:return " acos ";break; case SQRT:return " sqrt ";break; case POW:return " pow ";break; case LOG:return " log ";break; case LOG10:return " log10 ";break; case ABS:return " abs ";break; case FABS:return " fabs ";break; case EXP:return " exp ";break; case SINH:return " sinh ";break; case COSH:return " cosh ";break; case TANH:return " tanh ";break; case MUL:case FMUL:return " * ";break; case UDIV:case SDIV:case FDIV:return " / ";break; case ADDR:return " addr ";break; case STORE:return " store ";break; case LOAD:return " load ";break; case ALLOCA:return " alloca ";break; case SREM:case UREM:case FREM:return " % ";break; case ASHR:case LSHR:return " >> ";break; case SHL:return " << ";break; case NONE:return " ";break; case slt:case ult:case flt:return " < ";break; case sle:case ule:case fle:return " <= ";break; case sgt:case ugt:case fgt:return " > ";break; case sge:case uge:case fge:return " >= ";break; case eq:case feq:return " == ";break; case ne:case fne:return " != ";break; case MKNAN:return " nan ";break; case ISNAN:return " isnan ";break; case ISINF:return " isinf ";break; case ISNORMAL:return " isnormal ";break; case ISFINITE:return " isfinite ";break; case SIGNBIT:return " signbit ";break; case CLASSIFY:return " fpclassify ";break; case COPYSIGN:return " copysign ";break; case FESETROUND:return " fesetround ";break; case FEGETROUND:return " fegetround ";break; case CEIL:return " ceil ";break; case FLOOR:return " floor ";break; case ROUND:return " round ";break; case NEARBYINT:return " nearbyint ";break; case RINT:return " rint ";break; case FMAX:return " fmax ";break; case FMIN:return " fmin ";break; case FMOD:return " fmod ";break; case FDIM:return " fdim ";break; case REMAINDER:return " remainder ";break; case MODF:return " modf ";break; case FUNCTRUNC:return " functrunc ";break; default: assert(false);break; } } extern string get_var_type(VarType type){ switch(type){ case INT: return " INT ";break; case FP: return " FP ";break; case PTR: return " PTR ";break; case BOOL: return " BOOl ";break; case INTNUM: return " INTNUM ";break; case FPNUM: return " FPNUM ";break; default: assert(false);break; } } /******************************dReal_nonlinear_constraint************************************/ void Variable::printName(){ if(type == FPNUM){ if(numbits == 32){ int32_t temp = atoi(name.c_str()); float *fp = (float *)&temp; errs()<<*fp; } else if(numbits == 64){ int64_t temp = atoll(name.c_str()); double *fp = (double *)&temp; errs()<<*fp; } } else errs()<<name; } double Variable::getVal(){ assert(type==INTNUM||type==FPNUM); if(type == FPNUM){ if(numbits == 32){ int32_t temp = atoi(name.c_str()); float *fp = (float *)&temp; return (double)*fp; } else if(numbits == 64){ int64_t temp = atoll(name.c_str()); double *fp = (double *)&temp; return *fp; } } return ConvertToDouble(name); } raw_ostream& operator << (raw_ostream& os, Variable& object){ errs()<<"name:"<<object.name<<" id:"<<object.ID<<" type:"<<get_var_type(object.type)<<" bits:"<<object.numbits; return os; } raw_ostream& operator << (raw_ostream& os,ParaVariable& object){ if(object.lvar!=NULL){ object.lvar->printName(); } errs()<<object.op; if(object.rvar!=NULL){ object.rvar->printName(); } for(unsigned i=0;i<object.varList.size();i++) errs()<<object.varList[i]->name<<" "; return os; } raw_ostream& operator << (raw_ostream& os,Operator& object){ switch(object){ case SLT:case ULT:case FLT:errs()<<" < ";break; case SLE:case ULE:case FLE:errs()<<" <= ";break; case SGT:case UGT:case FGT:errs()<<" > ";break; case SGE:case UGE:case FGE:errs()<<" >= ";break; case EQ:case FEQ:errs()<<" == ";break; case NE:case FNE:errs()<<" != ";break; case ASSIGN:errs()<<" = ";break; } return os; } raw_ostream& operator << (raw_ostream& os,Constraint& object){ errs()<<"constraint:"; errs()<<object.lpvList; errs()<<object.op; errs()<<object.rpvList; return os; } raw_ostream& operator << (raw_ostream& os, Transition object){ errs()<<"Transition Name:"<<object.name<<" ID:"<<object.ID<<"\n"; errs()<<"Level:"<<object.level<<"\n"; errs()<<"ToLabel:"<<object.toLabel<<"\n"; errs()<<"from:"<<object.fromName<<" to:"<<object.toName<<"\nGuard:\n"; if(object.guardList.empty()) errs()<<"null\n"; else{ for(unsigned int i=0;i<object.guardList.size();i++) errs()<<"\t"<<object.guardList[i]<<"\n"; errs()<<"\n"; } return os; } raw_ostream& operator << (raw_ostream& os, State object){ errs()<<"Location Name:"<<object.funcName<<" "<<object.name<<" ID:"<<object.ID<<" nextS:"<<object.nextS<<"\n"; errs()<<"Level:"<<object.level<<"\n"; errs()<<"ErrorType:"<<object.error<<"\n"; if(object.isInitial) errs()<<"\tInitial location\n"; if(object.consList.empty()) errs()<<"null\n"; else{ for(unsigned int i=0;i<object.consList.size();i++) errs()<<"\t"<<object.consList[i]<<"\n"; errs()<<"\n"; } errs()<<"Content:"<<object.ContentRec<<"\n"; return os; } void CFG::print(){ errs()<<"*******************CFG Information*********************\n"; errs()<<"CFG:"<<name<<"\n"; printLinearMode(); unsigned mainInputID=0; unsigned mainSize = mainInput.size(); for(unsigned i=0;i<exprList.size();i++){ if(exprList[i].type==PTR) continue; errs()<<"(declare-fun "; errs()<<exprList[i].name; errs()<<" () "; if(exprList[i].type==INT) errs()<<"Int"; else errs()<<"Real"; errs()<<")\n"; } for(unsigned i=0;i<variableList.size();i++){ errs()<<variableList[i]; // errs()<<"variable:"<<variableList[i].name; // errs()<< ", " << variableList[i].ID; // errs()<<", "<<get_var_type(variableList[i].type)<<variableList[i].numbits; if(mainInputID<mainSize){ if(mainInput[mainInputID]==i){ errs()<<", mainInput"; mainInputID++; } } errs()<<"\n"; } errs()<<"\n"; for(unsigned int i=0;i<stateList.size();i++) errs()<<stateList[i]<<"\n"; for(unsigned int i=0;i<transitionList.size();i++) errs()<<transitionList[i]<<"\n"; } void CFG::printLinearMode(){ errs()<<"VerifierMode:\t"; if(linear) errs()<<"Linear\n"; else errs()<<"Unlinear\n"; } Operator getEnumOperator(string str) { if(str=="EQ") return EQ; else if(str=="NE") return NE; else if(str=="SLT") return SLT; else if(str=="SLE") return SLE; else if(str=="SGE") return SGE; else if(str=="SGT") return SGT; else if(str=="ULT") return ULT; else if(str=="ULE") return ULE; else if(str=="UGE") return UGE; else if(str=="UGT") return UGT; else if(str=="FEQ") return FEQ; else if(str=="FNE") return FNE; else if(str=="FLT") return FLT; else if(str=="FLE") return FLE; else if(str=="FGE") return FGE; else if(str=="FGT") return FGT; else if(str=="ASSIGN") return ASSIGN; else assert(false); } Op_m get_m_Operator(string str, bool isFunc){ if(str=="tan") return TAN; else if(str=="atan") return ATAN; else if(str=="atan2") return ATAN2; else if(str=="sin") return SIN; else if(str=="asin") return ASIN; else if(str=="cos") return COS; else if(str=="acos") return ACOS; else if(str=="sqrt") return SQRT; else if(str=="pow") return POW; else if(str=="log") return LOG; else if(str=="abs") return ABS; else if(str=="fabs") return FABS; else if(str=="exp") return EXP; else if(str=="sinh") return SINH; else if(str=="cosh") return COSH; else if(str=="tanh") return TANH; else if(str=="mul") return MUL; else if(str=="fmul") return FMUL; else if(str=="sdiv") return SDIV; else if(str=="fdiv") return FDIV; else if(str=="udiv") return UDIV; else if(str=="add") return ADD; else if(str=="fadd") return FADD; else if(str=="sub") return SUB; else if(str=="fsub") return FSUB; else if(str=="and") return AND; else if(str=="nand") return NAND; else if(str=="or") return OR; else if(str=="xor") return XOR; else if(str=="log10") return LOG10; else if(str=="srem") return SREM; else if(str=="urem") return UREM; else if(str=="frem") return FREM; else if(str=="ashr") return ASHR; else if(str=="lshr") return LSHR; else if(str=="shl") return SHL; else if(str=="trunc" && !isFunc) return TRUNC; else if(str=="trunc") return FUNCTRUNC; else if(str=="zext") return ZEXT; else if(str=="sext") return SEXT; else if(str=="fptrunc") return FPTRUNC; else if(str=="fpext") return FPEXT; else if(str=="fptoui") return FPTOUI; else if(str=="fptosi") return FPTOSI; else if(str=="uitofp") return UITOFP; else if(str=="sitofp") return SITOFP; else if(str=="bitcast") return BITCAST; else if(str=="EQ") return eq; else if(str=="NE") return ne; else if(str=="SLT") return slt; else if(str=="SLE") return sle; else if(str=="SGE") return sge; else if(str=="SGT") return sgt; else if(str=="ULT") return ult; else if(str=="ULE") return ule; else if(str=="UGE") return uge; else if(str=="UGT") return ugt; else if(str=="FEQ") return feq; else if(str=="FNE") return fne; else if(str=="FLT") return flt; else if(str=="FLE") return fle; else if(str=="FGE") return fge; else if(str=="FGT") return fgt; else if(str=="nan"||str=="nanf"||str=="nanl") return MKNAN; else if(str.find("isnan") != string::npos) return ISNAN; else if(str.find("isinf") != string::npos) return ISINF; else if(str.find("isnormal") != string::npos) return ISNORMAL; else if(str.find("finite") != string::npos) return ISFINITE; else if(str.find("signbit") != string::npos) return SIGNBIT; else if(str.find("fpclassify") != string::npos) return CLASSIFY; else if(str=="copysign") return COPYSIGN; else if(str=="fesetround") return FESETROUND; else if(str=="fegetround") return FEGETROUND; else if(str=="ceil") return CEIL; else if(str=="floor") return FLOOR; else if(str=="round"||str=="lround"||str=="llround") return ROUND; else if(str=="nearbyint") return NEARBYINT; else if(str=="rint"||str=="lrint"||str=="llrint") return RINT; else if(str=="fmax") return FMAX; else if(str=="fmin") return FMIN; else if(str=="fmod") return FMOD; else if(str=="fdim") return FDIM; else if(str=="remainder") return REMAINDER; else if(str=="modf") return MODF; else return NONE; } string intToString(int value) { char tmpString[15]; memset(tmpString, 0x00, 15); sprintf(tmpString, "%d", value); return tmpString; }
[ "YichaoLee@github.com" ]
YichaoLee@github.com
3fb3f5a60d33f6c65adbe1257cbea22231866fea
78102217d24a3f92e15f8201ee4d8c7628f3871e
/Electric-Revolution/Main.cpp
8af2db497ff2b5f84d5eb699e7f6fc779c414581
[ "MIT" ]
permissive
sknjpn/Electric-Revolution
bdf55c380e34ec1a7cc208cd0e26ec84417fad3e
1dc19d265fb7002cc2e826c26fbe8641c03f8547
refs/heads/master
2021-10-23T16:05:45.911907
2019-03-18T16:16:26
2019-03-18T16:16:26
107,275,857
8
1
null
null
null
null
UTF-8
C++
false
false
66
cpp
// OpenSiv3D v0.1.7 #include"Game.h" void Main() { Game(); }
[ "sknjpn@gmail.com" ]
sknjpn@gmail.com
792f4b391ecdbebcbc1693ec100006f823dc7a8a
0d3e91928ab114fd08b4f1e046220ee3de1628e9
/src/wtf/fshooks.h
2f3cf642e9bae1028f4e6212e106de501f18a993
[ "MIT" ]
permissive
modulexcite/wtf
539d895262ea882155ea3bad6df0de33dc4923ad
fed45a61f0d9d7b8844cceef658a34b21fb63976
refs/heads/main
2023-08-24T03:35:44.078685
2021-11-01T02:00:31
2021-11-01T02:00:31
423,667,419
1
0
MIT
2021-11-02T01:18:18
2021-11-02T01:18:18
null
UTF-8
C++
false
false
384
h
// Axel '0vercl0k' Souchet - March 19 2020 #pragma once #include "globals.h" #include <cstdio> #include <fmt/format.h> constexpr bool FsHooksLoggingOn = false; template <typename... Args_t> void FsDebugPrint(const char *Format, const Args_t &... args) { if constexpr (FsHooksLoggingOn) { fmt::print("fs:"); fmt::print(Format, args...); } } bool SetupFilesystemHooks();
[ "noreply@github.com" ]
noreply@github.com
d38d1c729f6de43250e42afc443e2c3fa08ad6c9
e8e6d0c9358052fa97b83c899bef3869a6abb805
/src/Common/PathTools.cpp
54250df7a8218dd532bbd04337a1c67335b1832d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cryptonoteclub/4xbitcoin-V-1.1
a59dc865e39b9f340c2c16e7a09c69f5a69d374e
8c70d63b052d5a440f1a92a50c4bc6b81070532b
refs/heads/master
2020-07-14T04:08:50.901770
2019-09-28T20:22:11
2019-09-28T20:22:11
205,234,452
0
0
null
2019-08-29T19:16:47
2019-08-29T19:16:47
null
UTF-8
C++
false
false
2,489
cpp
// Copyright (c) 2011-2017, The ManateeCoin Developers, The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "PathTools.h" #include <algorithm> namespace { const char GENERIC_PATH_SEPARATOR = '/'; #ifdef _WIN32 const char NATIVE_PATH_SEPARATOR = '\\'; #else const char NATIVE_PATH_SEPARATOR = '/'; #endif std::string::size_type findExtensionPosition(const std::string& filename) { auto pos = filename.rfind('.'); if (pos != std::string::npos) { auto slashPos = filename.rfind(GENERIC_PATH_SEPARATOR); if (slashPos != std::string::npos && slashPos > pos) { return std::string::npos; } } return pos; } } // anonymous namespace namespace Common { std::string NativePathToGeneric(const std::string& nativePath) { if (GENERIC_PATH_SEPARATOR == NATIVE_PATH_SEPARATOR) { return nativePath; } std::string genericPath(nativePath); std::replace(genericPath.begin(), genericPath.end(), NATIVE_PATH_SEPARATOR, GENERIC_PATH_SEPARATOR); return genericPath; } std::string GetPathDirectory(const std::string& path) { auto slashPos = path.rfind(GENERIC_PATH_SEPARATOR); if (slashPos == std::string::npos) { return std::string(); } return path.substr(0, slashPos); } std::string GetPathFilename(const std::string& path) { auto slashPos = path.rfind(GENERIC_PATH_SEPARATOR); if (slashPos == std::string::npos) { return path; } return path.substr(slashPos + 1); } void SplitPath(const std::string& path, std::string& directory, std::string& filename) { directory = GetPathDirectory(path); filename = GetPathFilename(path); } std::string CombinePath(const std::string& path1, const std::string& path2) { return path1 + GENERIC_PATH_SEPARATOR + path2; } std::string ReplaceExtenstion(const std::string& path, const std::string& extension) { return RemoveExtension(path) + extension; } std::string GetExtension(const std::string& path) { auto pos = findExtensionPosition(path); if (pos != std::string::npos) { return path.substr(pos); } return std::string(); } std::string RemoveExtension(const std::string& filename) { auto pos = findExtensionPosition(filename); if (pos == std::string::npos) { return filename; } return filename.substr(0, pos); } bool HasParentPath(const std::string& path) { return path.find(GENERIC_PATH_SEPARATOR) != std::string::npos; } }
[ "mybtcfx@gmail.com" ]
mybtcfx@gmail.com
2491e0c0687c5edd7e5a35e49c2303d6c6797281
f1f95e4ad6a45f1aeacc64d657b172d284b99a55
/renderer/renderer.hpp
a6cac7334cd7c00d8b5661353a8264678d570aa1
[]
no_license
saitec/Foveated-Encoder-for-VR
0fb3a7e6a7ace5a423960bdaf059b4f45b062a3e
9350440c3121817d61aee04d34fb06d557bd906a
refs/heads/master
2020-12-03T03:51:03.586149
2016-09-18T05:47:08
2016-09-18T05:47:08
68,499,097
3
0
null
null
null
null
UTF-8
C++
false
false
1,272
hpp
#ifndef RENDERER_RENDERER_H_ #define RENDERER_RENDERER_H_ #include <iostream> //#include <unistd.h> #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <GLUT/glut.h> #else #include <GL/gl.h> #include <GL/glut.h> #endif #include <glm/glm.hpp> #include <OVR_CAPI_0_5_0.h> #include <OVR_CAPI_GL.h> #ifdef WIN32 #include <SDL.h> #else #include <SDL2/SDL.h> #endif #include <opencv2/highgui/highgui.hpp> #include "../util/imageutil.hpp" #ifdef WIN32 #define OVR_OS_WIN32 #elif defined(__APPLE__) #define OVR_OS_MAC #else #define OVR_OS_LINUX #include <GL/glx.h> #include <X11/Xlib.h> #endif class Renderer { public: Renderer(int w, int h); void displayStereoImage(const cv::Mat& image); private: SDL_Window* win; SDL_GLContext ctx; ovrHmd hmd; ovrSizei eyeRes[2]; ovrEyeRenderDesc eyeDesc[2]; ovrSizei fovSize; ovrGLTexture ovrTex[2]; ovrGLTexture* prTargetTex; GLuint texture[2]; int windowWidth, windowHeight; int fbTexWidth, fbTexHeight; unsigned int fbo, fbTex, fbDepth; ovrGLConfig glCfg; unsigned int distortCaps, hmdCaps; void updateRenderTarget(); static GLuint loadTexture(const cv::Mat& image); static unsigned int nextPow2(unsigned int x); }; #endif
[ "noreply@github.com" ]
noreply@github.com
f264c4fc1c9474dd87e0380f2dbc082be11cc09e
c61f243a96edecba68576eb43c51196472a3f41d
/tests/PMFloatTest.cpp
0f0d853c2b840d8abacd74e2a6da6edc1b4adf4b
[ "BSD-3-Clause" ]
permissive
Abioy/skia
7d8070fd3350d140d69e2a1a68e59d52d6a51509
9665eee8d5ddc2ef644b062069f29a73d5dde077
refs/heads/master
2021-01-18T07:40:40.175455
2015-03-26T17:13:05
2015-03-26T17:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,038
cpp
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPMFloat.h" #include "Test.h" DEF_TEST(SkPMFloat, r) { // Test SkPMColor <-> SkPMFloat SkPMColor c = SkPreMultiplyColor(0xFFCC9933); SkPMFloat pmf(c); REPORTER_ASSERT(r, SkScalarNearlyEqual(255.0f, pmf.a())); REPORTER_ASSERT(r, SkScalarNearlyEqual(204.0f, pmf.r())); REPORTER_ASSERT(r, SkScalarNearlyEqual(153.0f, pmf.g())); REPORTER_ASSERT(r, SkScalarNearlyEqual( 51.0f, pmf.b())); REPORTER_ASSERT(r, c == pmf.get()); // Test rounding. pmf = SkPMFloat(254.5f, 203.5f, 153.1f, 50.8f); REPORTER_ASSERT(r, c == pmf.get()); // Test clamping. SkPMFloat clamped(SkPMFloat(510.0f, 153.0f, 1.0f, -0.2f).clamped()); REPORTER_ASSERT(r, SkScalarNearlyEqual(255.0f, clamped.a())); REPORTER_ASSERT(r, SkScalarNearlyEqual(153.0f, clamped.r())); REPORTER_ASSERT(r, SkScalarNearlyEqual( 1.0f, clamped.g())); REPORTER_ASSERT(r, SkScalarNearlyEqual( 0.0f, clamped.b())); // Test SkPMFloat <-> Sk4f conversion. Sk4f fs = clamped; SkPMFloat scaled = fs * Sk4f(0.25f); REPORTER_ASSERT(r, SkScalarNearlyEqual(63.75f, scaled.a())); REPORTER_ASSERT(r, SkScalarNearlyEqual(38.25f, scaled.r())); REPORTER_ASSERT(r, SkScalarNearlyEqual( 0.25f, scaled.g())); REPORTER_ASSERT(r, SkScalarNearlyEqual( 0.00f, scaled.b())); // Test 4-at-a-time conversions. SkPMColor colors[4] = { 0xFF000000, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF }; SkPMFloat floats[4]; SkPMFloat::From4PMColors(colors, floats+0, floats+1, floats+2, floats+3); SkPMColor back[4]; SkPMFloat::To4PMColors(floats[0], floats[1], floats[2], floats[3], back); for (int i = 0; i < 4; i++) { REPORTER_ASSERT(r, back[i] == colors[i]); } SkPMFloat::ClampTo4PMColors(floats[0], floats[1], floats[2], floats[3], back); for (int i = 0; i < 4; i++) { REPORTER_ASSERT(r, back[i] == colors[i]); } }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
57c663f5f0cbb4fd2fe6467f77478cf66974c939
230b77c1f7dead20a64a92cd1579ab7da1682a79
/zlibrary/ezx/dialogs/QWaitMessage.h
b4fd96d0e43e13f94a2e073d9b51973a299cf27a
[]
no_license
xufooo/fbreader-e2-test
b2a0f3a0ec1474a9e1773297e48fa31d056187ee
6043dda7a8531f5e842f2ebab77504f70d49944c
refs/heads/master
2021-01-22T07:22:46.337032
2012-10-30T11:27:53
2012-10-30T11:27:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
h
/* * Copyright (C) 2004-2006 Nikolay Pultsin <geometer@mawhrin.net> * Copyright (C) 2005 Mikhail Sobolev <mss@mawhrin.net> * * Port for the Motorola A780/E680i is * Copyright (C) 2006 Ketut P. Kumajaya <kumajaya@bluebottle.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef __QWAITMESSAGE_H__ #define __QWAITMESSAGE_H__ #include <string> #include <qobject.h> class QWaitMessage : public QObject { public: QWaitMessage(const std::string &message); ~QWaitMessage(); }; #endif /* __QWAITMESSAGE_H__ */
[ "ooo@ooo-isn.(none)" ]
ooo@ooo-isn.(none)
0ebcc23ceb618ca02b21487202d31ee6d7db05ae
1018c805f7d3eb9e534e23a68b006e3510bba569
/Mastering_SFML_Engine/Game.cpp
aecc9c14277f854e886865947454ec3416689cc8
[]
no_license
rafaelrzacharias/Mastering-SFML-Engine-OpenGL-CPlusPlus
ed89c6aceab8979f0de14a672c3a0526ac6e7bd3
2fd8a523621dde25b07afe160b5feac308d28f8b
refs/heads/master
2021-09-05T12:08:55.939523
2018-01-27T10:17:40
2018-01-27T10:17:40
117,825,619
0
0
null
null
null
null
UTF-8
C++
false
false
4,361
cpp
#include "Game.h" #include "State_Intro.h" #include "State_MainMenu.h" #include "State_MapEditor.h" #include "State_Game.h" #include "C_Position.h" #include "C_SpriteSheet.h" #include "C_State.h" #include "C_Movable.h" #include "C_Controller.h" #include "C_Collidable.h" #include "C_SoundEmitter.h" #include "C_SoundListener.h" #include "S_Renderer.h" #include "S_Movement.h" #include "S_Collision.h" #include "S_Control.h" #include "S_State.h" #include "S_SheetAnimation.h" #include "S_Sound.h" Game::Game() : m_window("Chapter 6", sf::Vector2u(800, 600)), m_entityManager(&m_systemManager, &m_textureManager), m_guiManager(m_window.GetEventManager(), &m_context), m_soundManager(&m_audioManager), m_gameMap(&m_window, &m_entityManager, &m_textureManager) { SetUpClasses(); SetUpECS(); SetUpStates(); m_fontManager.RequireResource("Main"); m_stateManager->SwitchTo(StateType::Intro); } Game::~Game() { m_fontManager.ReleaseResource("Main"); } sf::Time Game::GetElapsed() { return m_clock.getElapsedTime(); } void Game::RestartClock() { m_elapsed = m_clock.restart(); } Window* Game::GetWindow() { return &m_window; } void Game::Update() { m_window.Update(); m_stateManager->Update(m_elapsed); m_guiManager.Update(m_elapsed.asSeconds()); m_soundManager.Update(m_elapsed.asSeconds()); GUI_Event guiEvent; while (m_context.m_guiManager->PollEvent(guiEvent)) { m_window.GetEventManager()->HandleEvent(guiEvent); } } void Game::Render() { m_window.BeginDraw(); // Render here. m_stateManager->Draw(); m_guiManager.Render(m_window.GetRenderWindow()); m_window.EndDraw(); } void Game::LateUpdate() { m_stateManager->ProcessRequests(); RestartClock(); } void Game::SetUpClasses() { m_clock.restart(); m_context.m_rand = &m_rand; srand(static_cast<unsigned int>(time(nullptr))); m_systemManager.SetEntityManager(&m_entityManager); m_context.m_wind = &m_window; m_context.m_eventManager = m_window.GetEventManager(); m_context.m_textureManager = &m_textureManager; m_context.m_fontManager = &m_fontManager; m_context.m_audioManager = &m_audioManager; m_context.m_soundManager = &m_soundManager; m_context.m_gameMap = &m_gameMap; m_context.m_systemManager = &m_systemManager; m_context.m_entityManager = &m_entityManager; m_context.m_guiManager = &m_guiManager; m_stateManager = std::make_unique<StateManager>(&m_context); m_gameMap.SetStateManager(m_stateManager.get()); m_particles = std::make_unique<ParticleSystem>(m_stateManager.get(), &m_textureManager, &m_rand, &m_gameMap); m_context.m_particles = m_particles.get(); m_gameMap.AddLoadee(m_particles.get()); } void Game::SetUpECS() { m_entityManager.AddComponentType<C_Position>(Component::Position); m_entityManager.AddComponentType<C_SpriteSheet>(Component::SpriteSheet); m_entityManager.AddComponentType<C_State>(Component::State); m_entityManager.AddComponentType<C_Movable>(Component::Movable); m_entityManager.AddComponentType<C_Controller>(Component::Controller); m_entityManager.AddComponentType<C_Collidable>(Component::Collidable); m_entityManager.AddComponentType<C_SoundEmitter>(Component::SoundEmitter); m_entityManager.AddComponentType<C_SoundListener>(Component::SoundListener); m_systemManager.AddSystem<S_State>(System::State); m_systemManager.AddSystem<S_Control>(System::Control); m_systemManager.AddSystem<S_Movement>(System::Movement); m_systemManager.AddSystem<S_Collision>(System::Collision); m_systemManager.AddSystem<S_SheetAnimation>(System::SheetAnimation); m_systemManager.AddSystem<S_Sound>(System::Sound); m_systemManager.AddSystem<S_Renderer>(System::Renderer); m_systemManager.GetSystem<S_Collision>(System::Collision)->SetMap(&m_gameMap); m_systemManager.GetSystem<S_Movement>(System::Movement)->SetMap(&m_gameMap); m_systemManager.GetSystem<S_Sound>(System::Sound)->SetUp(&m_audioManager, &m_soundManager); } void Game::SetUpStates() { m_stateManager->AddDependent(m_context.m_eventManager); m_stateManager->AddDependent(&m_guiManager); m_stateManager->AddDependent(&m_soundManager); m_stateManager->AddDependent(m_particles.get()); m_stateManager->RegisterState<State_Intro>(StateType::Intro); m_stateManager->RegisterState<State_MainMenu>(StateType::MainMenu); m_stateManager->RegisterState<State_MapEditor>(StateType::MapEditor); m_stateManager->RegisterState<State_Game>(StateType::Game); }
[ "rafaelrzacharias@gmail.com" ]
rafaelrzacharias@gmail.com
e58aa0d5ebc96344f5d1e7823203d6be45b75859
d617f6f2e3fe291c982649f1a0dddc93105d8056
/src/gtest/generated/key_417.cpp
77cf10f34c74048ee695040389f1f5ce53801c94
[ "BSD-2-Clause" ]
permissive
Cryptolens/cryptolens-cpp-tests
052d65c94f8008c90d9e62140907480cf18afe57
c8971dbbece8505c04114f7e47a0cf374353f097
refs/heads/master
2020-08-27T22:20:25.835533
2019-10-25T12:19:20
2019-10-25T12:19:20
217,503,236
0
0
null
null
null
null
UTF-8
C++
false
false
24,544
cpp
#include <cryptolens/tests/gtest_shared.hpp> #include <gtest/gtest.h> namespace tests_v20180502 { class v20180502_online_Key417 : public ::testing::Test { protected: static void SetUpTestCase() { Cryptolens cryptolens_handle; cryptolens::Error e; cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); license_key_ = cryptolens_handle.activate(e, "WyI3NzkxIiwiSkV6QmE3TVFDSU5jSmdSQXNwZXdCdnZSODNGeitQYnNDVDltckVvUSJd", "4848", "FDHCM-WRJOP-JVWFU-HODFG", "a"); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20180502_online_Key417() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20180502_online_Key417::license_key_; TEST_F(v20180502_online_Key417, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565801546); EXPECT_EQ(license_key->get_expires(), 3269274159); EXPECT_EQ(license_key->get_period(), 19716); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), true); EXPECT_EQ(license_key->get_f1(), false); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), false); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), false); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), false); } TEST_F(v20180502_online_Key417, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 468); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FDHCM-WRJOP-JVWFU-HODFG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "YIRy0LTh104b6dUMVGYfFSVc"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 1); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), ""); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } } TEST_F(v20180502_online_Key417, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565811759)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20180502_online_Key417, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6586); EXPECT_EQ(customer.get_name(), "Pm2R3RrsECiW4fFP6d57ZaR"); EXPECT_EQ(customer.get_email(), ""); EXPECT_EQ(customer.get_company_name(), "tL"); EXPECT_EQ(customer.get_created(), 1565801546); } } TEST_F(v20180502_online_Key417, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(4527, "fluzFgE3MdWAdnxbq3GDgNAd", "bzQIh7 MC9VWk7icJ", 351942)); expected.push_back(cryptolens::DataObject(4528, "Ii0RfFy9b", "MX4Z8FcU", 643251)); expected.push_back(cryptolens::DataObject(4529, "QoJtBmuITRmp2Xs MB", "", 831369)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } } // namespace tests_v20180502 namespace tests_v20190401 { class v20190401_online_Key417 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); license_key_ = cryptolens_handle.activate(e, "WyI3NzkxIiwiSkV6QmE3TVFDSU5jSmdSQXNwZXdCdnZSODNGeitQYnNDVDltckVvUSJd", 4848, "FDHCM-WRJOP-JVWFU-HODFG"); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_online_Key417() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_online_Key417::license_key_; TEST_F(v20190401_online_Key417, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565801546); EXPECT_EQ(license_key->get_expires(), 3269274159); EXPECT_EQ(license_key->get_period(), 19716); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), true); EXPECT_EQ(license_key->get_f1(), false); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), false); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), false); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), false); } TEST_F(v20190401_online_Key417, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 468); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FDHCM-WRJOP-JVWFU-HODFG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "YIRy0LTh104b6dUMVGYfFSVc"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 1); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), ""); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } } TEST_F(v20190401_online_Key417, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565811759)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_online_Key417, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6586); EXPECT_EQ(customer.get_name(), "Pm2R3RrsECiW4fFP6d57ZaR"); EXPECT_EQ(customer.get_email(), ""); EXPECT_EQ(customer.get_company_name(), "tL"); EXPECT_EQ(customer.get_created(), 1565801546); } } TEST_F(v20190401_online_Key417, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(4527, "fluzFgE3MdWAdnxbq3GDgNAd", "bzQIh7 MC9VWk7icJ", 351942)); expected.push_back(cryptolens::DataObject(4528, "Ii0RfFy9b", "MX4Z8FcU", 643251)); expected.push_back(cryptolens::DataObject(4529, "QoJtBmuITRmp2Xs MB", "", 831369)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } class v20190401_offline_json_Key417 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); std::string saved_response("{\"licenseKey\":\"eyJQcm9kdWN0SWQiOjQ4NDgsIklEIjo0NjgsIktleSI6IkZESENNLVdSSk9QLUpWV0ZVLUhPREZHIiwiQ3JlYXRlZCI6MTU2NTgwMTU0NiwiRXhwaXJlcyI6MzI2OTI3NDE1OSwiUGVyaW9kIjoxOTcxNiwiRjEiOmZhbHNlLCJGMiI6ZmFsc2UsIkYzIjpmYWxzZSwiRjQiOnRydWUsIkY1IjpmYWxzZSwiRjYiOnRydWUsIkY3Ijp0cnVlLCJGOCI6ZmFsc2UsIk5vdGVzIjoiWUlSeTBMVGgxMDRiNmRVTVZHWWZGU1ZjIiwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6NTQ3NDksIkN1c3RvbWVyIjp7IklkIjo2NTg2LCJOYW1lIjoiUG0yUjNScnNFQ2lXNGZGUDZkNTdaYVIiLCJFbWFpbCI6bnVsbCwiQ29tcGFueU5hbWUiOiJ0TCIsIkNyZWF0ZWQiOjE1NjU4MDE1NDZ9LCJBY3RpdmF0ZWRNYWNoaW5lcyI6W3siTWlkIjoiYSIsIklQIjoiMTU4LjE3NC4xMC4yMTgiLCJUaW1lIjoxNTY1ODExNzU5fV0sIlRyaWFsQWN0aXZhdGlvbiI6dHJ1ZSwiTWF4Tm9PZk1hY2hpbmVzIjoxLCJBbGxvd2VkTWFjaGluZXMiOiIiLCJEYXRhT2JqZWN0cyI6W3siSWQiOjQ1MjcsIk5hbWUiOiJmbHV6RmdFM01kV0FkbnhicTNHRGdOQWQiLCJTdHJpbmdWYWx1ZSI6ImJ6UUloNyBNQzlWV2s3aWNKIiwiSW50VmFsdWUiOjM1MTk0Mn0seyJJZCI6NDUyOCwiTmFtZSI6IklpMFJmRnk5YiIsIlN0cmluZ1ZhbHVlIjoiTVg0WjhGY1UiLCJJbnRWYWx1ZSI6NjQzMjUxfSx7IklkIjo0NTI5LCJOYW1lIjoiUW9KdEJtdUlUUm1wMlhzIE1CIiwiU3RyaW5nVmFsdWUiOiIiLCJJbnRWYWx1ZSI6ODMxMzY5fV0sIlNpZ25EYXRlIjoxNTcwNDYxMDMzfQ==\",\"signature\":\"gZYiojKpS5TZ2TJmIEGe1r+vdRIWbnjWDUIUVasqR3iMRB+95e6VLTbPt6OBXtkVG3uJVPRQSDC91VsQOgx/RJSyJfvDRd9s7FMa2YFc6+Vq094C3RyefkOXOWqoHM9fEoPqDRa3nlZsjQfPLuzNfkL0auiagkSfoL7bSItJrfqTtwLAKdybzo91/rWZW0KJ42DWj79Bd/W1V9OYEzUnLaKuY2A7ukxipM3ZLpWBTiIigcfRcq8v7Hx14G6NkGldqUBnQjdwEJpRfY3VLdzIRggRVOOxmciWeP4jOxgMsQCS4T7eNfdSns8MnfeEETATSnmWOobLh1+kWykYreKtow==\",\"result\":0,\"message\":\"\"}"); license_key_ = cryptolens_handle.make_license_key(e, saved_response); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_offline_json_Key417() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_offline_json_Key417::license_key_; TEST_F(v20190401_offline_json_Key417, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565801546); EXPECT_EQ(license_key->get_expires(), 3269274159); EXPECT_EQ(license_key->get_period(), 19716); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), true); EXPECT_EQ(license_key->get_f1(), false); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), false); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), false); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), false); } TEST_F(v20190401_offline_json_Key417, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 468); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FDHCM-WRJOP-JVWFU-HODFG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "YIRy0LTh104b6dUMVGYfFSVc"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 1); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), ""); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } } TEST_F(v20190401_offline_json_Key417, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565811759)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_offline_json_Key417, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6586); EXPECT_EQ(customer.get_name(), "Pm2R3RrsECiW4fFP6d57ZaR"); EXPECT_EQ(customer.get_email(), ""); EXPECT_EQ(customer.get_company_name(), "tL"); EXPECT_EQ(customer.get_created(), 1565801546); } } TEST_F(v20190401_offline_json_Key417, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(4527, "fluzFgE3MdWAdnxbq3GDgNAd", "bzQIh7 MC9VWk7icJ", 351942)); expected.push_back(cryptolens::DataObject(4528, "Ii0RfFy9b", "MX4Z8FcU", 643251)); expected.push_back(cryptolens::DataObject(4529, "QoJtBmuITRmp2Xs MB", "", 831369)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } class v20190401_offline_compact_Key417 : public ::testing::Test { protected: static void SetUpTestCase() { cryptolens::Error e; Cryptolens cryptolens_handle(e); cryptolens_handle.signature_verifier.set_modulus_base64(e, "khbyu3/vAEBHi339fTuo2nUaQgSTBj0jvpt5xnLTTF35FLkGI+5Z3wiKfnvQiCLf+5s4r8JB/Uic/i6/iNjPMILlFeE0N6XZ+2pkgwRkfMOcx6eoewypTPUoPpzuAINJxJRpHym3V6ZJZ1UfYvzRcQBD/lBeAYrvhpCwukQMkGushKsOS6U+d+2C9ZNeP+U+uwuv/xu8YBCBAgGb8YdNojcGzM4SbCtwvJ0fuOfmCWZvUoiumfE4x7rAhp1pa9OEbUe0a5HL+1v7+JLBgkNZ7Z2biiHaM6za7GjHCXU8rojatEQER+MpgDuQV3ZPx8RKRdiJgPnz9ApBHFYDHLDzDw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "a"); std::string saved_response("v20180502-"); saved_response += "eyJQcm9kdWN0SWQiOjQ4NDgsIklEIjo0NjgsIktleSI6IkZESENNLVdSSk9QLUpWV0ZVLUhPREZHIiwiQ3JlYXRlZCI6MTU2NTgwMTU0NiwiRXhwaXJlcyI6MzI2OTI3NDE1OSwiUGVyaW9kIjoxOTcxNiwiRjEiOmZhbHNlLCJGMiI6ZmFsc2UsIkYzIjpmYWxzZSwiRjQiOnRydWUsIkY1IjpmYWxzZSwiRjYiOnRydWUsIkY3Ijp0cnVlLCJGOCI6ZmFsc2UsIk5vdGVzIjoiWUlSeTBMVGgxMDRiNmRVTVZHWWZGU1ZjIiwiQmxvY2siOmZhbHNlLCJHbG9iYWxJZCI6NTQ3NDksIkN1c3RvbWVyIjp7IklkIjo2NTg2LCJOYW1lIjoiUG0yUjNScnNFQ2lXNGZGUDZkNTdaYVIiLCJFbWFpbCI6bnVsbCwiQ29tcGFueU5hbWUiOiJ0TCIsIkNyZWF0ZWQiOjE1NjU4MDE1NDZ9LCJBY3RpdmF0ZWRNYWNoaW5lcyI6W3siTWlkIjoiYSIsIklQIjoiMTU4LjE3NC4xMC4yMTgiLCJUaW1lIjoxNTY1ODExNzU5fV0sIlRyaWFsQWN0aXZhdGlvbiI6dHJ1ZSwiTWF4Tm9PZk1hY2hpbmVzIjoxLCJBbGxvd2VkTWFjaGluZXMiOiIiLCJEYXRhT2JqZWN0cyI6W3siSWQiOjQ1MjcsIk5hbWUiOiJmbHV6RmdFM01kV0FkbnhicTNHRGdOQWQiLCJTdHJpbmdWYWx1ZSI6ImJ6UUloNyBNQzlWV2s3aWNKIiwiSW50VmFsdWUiOjM1MTk0Mn0seyJJZCI6NDUyOCwiTmFtZSI6IklpMFJmRnk5YiIsIlN0cmluZ1ZhbHVlIjoiTVg0WjhGY1UiLCJJbnRWYWx1ZSI6NjQzMjUxfSx7IklkIjo0NTI5LCJOYW1lIjoiUW9KdEJtdUlUUm1wMlhzIE1CIiwiU3RyaW5nVmFsdWUiOiIiLCJJbnRWYWx1ZSI6ODMxMzY5fV0sIlNpZ25EYXRlIjoxNTcwNDYxMDMzfQ=="; saved_response += "-"; saved_response += "gZYiojKpS5TZ2TJmIEGe1r+vdRIWbnjWDUIUVasqR3iMRB+95e6VLTbPt6OBXtkVG3uJVPRQSDC91VsQOgx/RJSyJfvDRd9s7FMa2YFc6+Vq094C3RyefkOXOWqoHM9fEoPqDRa3nlZsjQfPLuzNfkL0auiagkSfoL7bSItJrfqTtwLAKdybzo91/rWZW0KJ42DWj79Bd/W1V9OYEzUnLaKuY2A7ukxipM3ZLpWBTiIigcfRcq8v7Hx14G6NkGldqUBnQjdwEJpRfY3VLdzIRggRVOOxmciWeP4jOxgMsQCS4T7eNfdSns8MnfeEETATSnmWOobLh1+kWykYreKtow=="; license_key_ = cryptolens_handle.make_license_key(e, saved_response); ASSERT_TRUE(license_key_); ASSERT_FALSE(e); } static void TearDownTestCase() { license_key_ = cryptolens::nullopt; } v20190401_offline_compact_Key417() : ::testing::Test(), license_key(license_key_) {} static cryptolens::optional<cryptolens::LicenseKey> license_key_; cryptolens::optional<cryptolens::LicenseKey> const& license_key; }; cryptolens::optional<cryptolens::LicenseKey> v20190401_offline_compact_Key417::license_key_; TEST_F(v20190401_offline_compact_Key417, MandatoryProperties) { EXPECT_EQ(license_key->get_product_id(), 4848); EXPECT_EQ(license_key->get_created(), 1565801546); EXPECT_EQ(license_key->get_expires(), 3269274159); EXPECT_EQ(license_key->get_period(), 19716); EXPECT_EQ(license_key->get_block(), false); EXPECT_EQ(license_key->get_trial_activation(), true); EXPECT_EQ(license_key->get_f1(), false); EXPECT_EQ(license_key->get_f2(), false); EXPECT_EQ(license_key->get_f3(), false); EXPECT_EQ(license_key->get_f4(), true); EXPECT_EQ(license_key->get_f5(), false); EXPECT_EQ(license_key->get_f6(), true); EXPECT_EQ(license_key->get_f7(), true); EXPECT_EQ(license_key->get_f8(), false); } TEST_F(v20190401_offline_compact_Key417, SimpleOptionalProperties) { EXPECT_TRUE(license_key->get_id()); if (license_key->get_id()) { EXPECT_EQ(*(license_key->get_id()), 468); } EXPECT_TRUE(license_key->get_key()); if (license_key->get_key()) { EXPECT_EQ(*(license_key->get_key()), "FDHCM-WRJOP-JVWFU-HODFG"); } EXPECT_TRUE(license_key->get_notes()); if (license_key->get_notes()) { EXPECT_EQ(*(license_key->get_notes()), "YIRy0LTh104b6dUMVGYfFSVc"); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } EXPECT_TRUE(license_key->get_maxnoofmachines()); if (license_key->get_maxnoofmachines()) { EXPECT_EQ(*(license_key->get_maxnoofmachines()), 1); } EXPECT_TRUE(license_key->get_allowed_machines()); if (license_key->get_allowed_machines()) { EXPECT_EQ(*(license_key->get_allowed_machines()), ""); } EXPECT_TRUE(license_key->get_global_id()); if (license_key->get_global_id()) { EXPECT_EQ(*(license_key->get_global_id()), 54749); } } TEST_F(v20190401_offline_compact_Key417, ActivatedMachines) { ASSERT_TRUE(license_key->get_activated_machines()); std::vector<cryptolens::ActivationData> expected; expected.push_back(cryptolens::ActivationData("a", "158.174.10.218", 1565811759)); // XXX: We have quadratic performance here. Could be some concern here given that set of activated machines can be large auto const& activated_machines = *(license_key->get_activated_machines()); for (auto i = activated_machines.cbegin(); i != activated_machines.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_mid() == j->get_mid() && i->get_ip() == j->get_ip() && i->get_time() == j->get_time()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } TEST_F(v20190401_offline_compact_Key417, Customer) { EXPECT_TRUE(license_key->get_customer()); if (license_key->get_customer()) { auto const& customer = *(license_key->get_customer()); EXPECT_EQ(customer.get_id(), 6586); EXPECT_EQ(customer.get_name(), "Pm2R3RrsECiW4fFP6d57ZaR"); EXPECT_EQ(customer.get_email(), ""); EXPECT_EQ(customer.get_company_name(), "tL"); EXPECT_EQ(customer.get_created(), 1565801546); } } TEST_F(v20190401_offline_compact_Key417, DataObjects) { ASSERT_TRUE(license_key->get_data_objects()); std::vector<cryptolens::DataObject> expected; expected.push_back(cryptolens::DataObject(4527, "fluzFgE3MdWAdnxbq3GDgNAd", "bzQIh7 MC9VWk7icJ", 351942)); expected.push_back(cryptolens::DataObject(4528, "Ii0RfFy9b", "MX4Z8FcU", 643251)); expected.push_back(cryptolens::DataObject(4529, "QoJtBmuITRmp2Xs MB", "", 831369)); // XXX: We have quadratic performance here. It's fine given current restrictions on data objects auto const& data_objects = *(license_key->get_data_objects()); for (auto i = data_objects.cbegin(); i != data_objects.cend(); ++i) { ASSERT_NE(expected.size(), 0); for (auto j = expected.begin(); j != expected.end(); ++j) { if (i->get_id() == j->get_id() && i->get_name() == j->get_name() && i->get_string_value() == j->get_string_value() && i->get_int_value() == j->get_int_value()) { expected.erase(j); break; } } } ASSERT_EQ(expected.size(), 0); } } // namespace tests_v20190401
[ "martin@cryptolens.io" ]
martin@cryptolens.io
cd24d2adb17390a54ff09930e27de8b415a88584
bfd2a57a7d6980a4a67bfa8d4405c9b33838bae7
/Src/D3D12MiniLibrary/Engine/AsyncComponent/Fence.h
fa6330ba4c18c978c3fdb1cbe3e289b35580911c
[]
no_license
Mag357num/TBDR
ec936d5925e696affdf790d2f268931069a164fe
792926bbe51bd01b0a2db72171827521fdb3af14
refs/heads/master
2021-10-23T21:04:27.786138
2019-03-20T01:30:49
2019-03-20T01:30:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
588
h
#pragma once #include "../Util/D3D12Common.h" #include <list> //Forward declaration // namespace K3D12 { class CommandQueue; class Fence { private: Microsoft::WRL::ComPtr<ID3D12Fence> _fence; UINT64 _fenceValue; void* _fenceEvent; public: private: public: HRESULT Create(UINT64 initialFenceValue, D3D12_FENCE_FLAGS flags); void Discard(); Microsoft::WRL::ComPtr<ID3D12Fence> GetFence(); UINT64 GetFenceValue(); void* GetFenceEvent(); HRESULT Wait(CommandQueue* commandQueue); Fence(); ~Fence(); }; }
[ "necrophantasia_koba@icloud.com" ]
necrophantasia_koba@icloud.com
94575791b0cb5a649e18a4c8ebc0513a8c50cdb0
fd57ede0ba18642a730cc862c9e9059ec463320b
/wilhelm/src/sllog.cpp
d9c916cea52e300ceb7ef58b75a48e7be89dba49
[]
no_license
kailaisi/android-29-framwork
a0c706fc104d62ea5951ca113f868021c6029cd2
b7090eebdd77595e43b61294725b41310496ff04
refs/heads/master
2023-04-27T14:18:52.579620
2021-03-08T13:05:27
2021-03-08T13:05:27
254,380,637
1
1
null
2023-04-15T12:22:31
2020-04-09T13:35:49
C++
UTF-8
C++
false
false
1,366
cpp
/* * Copyright (C) 2010 The Android 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. */ #include "sles_allinclusive.h" #ifdef ANDROID /** \brief Log messages are prefixed by this tag */ const char slLogTag[] = "libOpenSLES"; #endif #if 0 // There is no support for configuring the logging level at runtime. // If that was needed, it could be done like this: // #define SL_LOGx(...) do { if (slLogLevel <= ...) ... } while (0) /** \brief Default runtime log level */ SLAndroidLogLevel slLogLevel = USE_LOG_RUNTIME; /** \brief Set the runtime log level */ SL_API void SLAPIENTRY slAndroidSetLogLevel(SLAndroidLogLevel logLevel) { // Errors can't be disabled if (logLevel > SLAndroidLogLevel_Error) logLevel = SLAndroidLogLevel_Error; slLogLevel = logLevel; } #endif
[ "541018378@qq.com" ]
541018378@qq.com
7e248e893ac64fbe8ec96f1c068d4044116c06ff
aeb11458d1a6ae1e4f7c8e2f2d9ffa3aa5b0cff2
/cyclic_list/Source.cpp
65f58e96c8f8787b80a98aa4dcd188cdcf669724
[]
no_license
CodeR-na-r1/List
756e97e7b68ddecb95d58e2fde59b762180531f4
12b22af751b4a1eff915e996baa50de5ae5e12e9
refs/heads/main
2023-09-04T16:03:46.200168
2021-11-11T09:35:55
2021-11-11T09:35:55
420,057,075
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
cpp
#include <iostream> #include "cyclic_list.h" using namespace std; int main() { // Joseph flavius // step - what kind of person are we killing. # If the step is 2, then we kill every second. (but we skip 1 person) cyclic_list<int> cl; int size, step; cout << "Enter number of people: " << endl; enter_size: cin >> size; if (cin.fail() || size < 1) { cin.clear(); cin.ignore(999, '\n'); cout << "error input! Try again: " << endl; goto enter_size; } cout << "Enter step (how many people are skip) : " << endl; enter_step: cin >> step; if (cin.fail() || step < 0) { cin.clear(); cin.ignore(999, '\n'); cout << "error input! Try again: " << endl; goto enter_step; } if (step == 1|| step == 0) { cout << endl << "Answer: " << size; return 0; } int count = size; while (cl.get_size() != size) { cl.push_front(count); --count; } --step; cyclic_list<int>::iterator it = cl.begin(); count = 1; while (cl.get_size() != 1) { if (count == step) { cl.pop_after(it); ; count = 0; } it = it.shift(cl, 1); ++count; } cout << "Answer: " << cl << endl; cl.clear(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
1b5c4ab1d97124bd31ac84efe959e11c0f72bc63
358a40dea4ec1bcc53d431cea4eb81005ad10536
/plugins/RenderOGL/OGL_Texture.cpp
7752e247bc0c1c511094cdbf4db2dc534364ad77
[]
no_license
jeckbjy/engine
cc0a0b82b7d7891f4fbf3d851ecea38e2b1cd3f5
1e15d88dfb21f9cd7140d61c79764a932b24ef4d
refs/heads/master
2020-04-07T02:00:37.381732
2017-06-22T06:09:10
2017-06-22T06:09:10
47,948,967
3
1
null
null
null
null
GB18030
C++
false
false
9,807
cpp
#include "OGL_Texture.h" #include "OGL_Mapping.h" CUTE_NS_BEGIN // 压缩,非压缩,数组,非数组共4种情况 static const char TEX_NORMAL = 0; static const char TEX_ARRAYS = 1; static const char TEX_COMPRESS = 2; static const char TEX_COMPRESS_ARRAY = 3; GLenum OGL_Texture::getGLTarget(TexType type, uint32_t arrays) { switch (type) { case TEX_1D:return arrays > 1 ? GL_TEXTURE_1D_ARRAY : GL_TEXTURE_1D; case TEX_2D:return arrays > 1 ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D; case TEX_3D:return GL_TEXTURE_3D; case TEX_CUBE:return arrays > 1 ? GL_TEXTURE_CUBE_MAP_ARRAY : GL_TEXTURE_CUBE_MAP; } return GL_TEXTURE_2D; } // todo:数据初始化 OGL_Texture::OGL_Texture(const TextureDesc& desc) :Texture(desc) { m_target = getGLTarget(desc.type, desc.depthOrArraySize); // 创建 glGenTextures(1, &m_handle); glBindTexture(m_target, m_handle); // This needs to be set otherwise the texture doesn't get rendered glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, desc.mipLevels - 1); // Set some misc default parameters so NVidia won't complain, these can of course be changed later glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(m_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(m_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLint glinternal; GLenum glformat; GLenum gltype; OGL_Mapping::getPixelFormat(desc.format, glinternal, glformat, gltype); // 分配空间 bool compressed = PixelUtil::isCompressed(m_format); char fill_mode; if (compressed) fill_mode = m_depth > 1 ? TEX_COMPRESS_ARRAY : TEX_COMPRESS; else fill_mode = m_depth > 1 ? TEX_ARRAYS : TEX_NORMAL; if ((m_usage & RES_RENDER_TARGET) || (m_usage & RES_DEPTH_STENCIL)) { if (desc.samples > 0) glTexImage2DMultisample(GL_TEXTURE_2D, desc.samples, glinternal, m_width, m_height, GL_FALSE); else glTexImage2D(GL_TEXTURE_2D, 0, glinternal, m_width, m_height, 0, glformat, gltype, NULL); } const char* data = (const char*)desc.data; // 2d switch (m_type) { case TEX_1D: create1D(glinternal, glformat, gltype, compressed, fill_mode, data); break; case TEX_2D: create2D(glinternal, glformat, gltype, compressed, fill_mode, data); break; case TEX_3D: create3D(glinternal, glformat, gltype, compressed, fill_mode, data); break; case TEX_CUBE: createCube(glinternal, glformat, gltype, compressed, fill_mode, data); break; default: break; } } OGL_Texture::~OGL_Texture() { glDeleteTextures(1, &m_handle); } void OGL_Texture::active(GLint index) { glActiveTexture(GL_TEXTURE0 + index); glBindTexture(m_target, m_handle); } void OGL_Texture::bindToFrameBuffer(GLenum attachment) { switch (m_target) { case GL_TEXTURE_1D: glFramebufferTexture1D(GL_FRAMEBUFFER, attachment, 0, m_handle, 0); break; case GL_TEXTURE_2D: glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, 0, m_handle, 0); break; case GL_TEXTURE_2D_MULTISAMPLE: glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, 0, m_handle, 0); break; case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_3D: default: glFramebufferTexture(GL_FRAMEBUFFER, attachment, m_handle, 0); break; } } void* OGL_Texture::map(PixelData& data, MAP_FLAG flag, uint level, uint face) { return 0; } void OGL_Texture::unmap() { } void OGL_Texture::read(PixelData& data, uint level, uint face) { // 传入参数不用这么复杂?? glBindTexture(m_target, m_handle); GLenum target = (m_type == TEX_CUBE) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + face : m_target; if (PixelUtil::isCompressed(m_format)) {// 创建空间?? glGetCompressedTexImage(target, level, data.data); } else { glGetTexImage(target, level, OGL_Mapping::getGLFormat(m_format), OGL_Mapping::getGLType(m_format), data.data); } } void OGL_Texture::write(const PixelData& data, uint level, uint face, bool discard) { // 还能再简化么? glBindTexture(m_target, m_handle); GLint glinternal; GLenum glformat; GLenum gltype; OGL_Mapping::getPixelFormat(m_format, glinternal, glformat, gltype); uint image_size = 0; bool compressed = PixelUtil::isCompressed(m_format); switch (m_target) { case GL_TEXTURE_1D: if (compressed) glCompressedTexSubImage1D(m_target, level, data.x, data.width, glformat, image_size, data.data); else glTexSubImage1D(m_target,level,data.x, data.width, glformat, gltype, data.data); break; case GL_TEXTURE_2D: case GL_TEXTURE_CUBE_MAP: { GLenum target = (m_type == TEX_CUBE) ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + face : GL_TEXTURE_2D; if (compressed) glCompressedTexSubImage2D(target, level, data.x, data.y, data.width, data.height, glformat, image_size, data.data); else glTexSubImage2D(target, level, data.x, data.y, data.width, data.height, glformat, gltype, data.data); } break; case GL_TEXTURE_3D: if (compressed) glCompressedTexSubImage3D(m_target, level, data.x, data.y, data.z, data.width, data.height, data.depth, glformat, image_size, data.data); else glTexSubImage3D(m_target, level, data.x, data.y, data.z, data.width, data.height, data.depth, glformat, gltype, data.data); break; default: break; } } void OGL_Texture::create1D(GLint glinternal, GLenum glformat, GLenum gltype, bool compressed, char fill_mode, const char* data) { size_t block_size = PixelUtil::getBytes(m_format); size_t width, image_size; for (uint32_t array_index = 0; array_index < m_depth; ++array_index) { width = m_width; for (uint32_t level = 0; level < m_mipmaps; ++level) { if (compressed) image_size = ((width + 3) / 4) * block_size; else image_size = width * block_size; switch (fill_mode) { case TEX_NORMAL: glTexImage1D(m_target, level, glinternal, width, 0, glformat, gltype, data); break; case TEX_COMPRESS: glCompressedTexImage1D(m_target, level, glinternal, width, 0, image_size, data); break; case TEX_ARRAYS: glTexImage2D(m_target, level, glinternal, width, m_depth, 0, glformat, gltype, data); break; case TEX_COMPRESS_ARRAY: glCompressedTexImage2D(m_target, level, glinternal, width, m_depth, 0, image_size, data); default: break; } if (width > 1) width >>= 1; if (data != NULL) data += image_size; } } } void OGL_Texture::create2D(GLint glinternal, GLenum glformat, GLenum gltype, bool compressed, char fill_mode, const char* data) { size_t block_size = PixelUtil::getBytes(m_format); size_t width, height, image_size; for (uint32_t array_index = 0; array_index < m_depth; ++array_index) { width = m_width; height = m_height; for (uint32_t level = 0; level < m_mipmaps; ++level) { if (compressed) image_size = ((width + 3) / 4) * ((height + 3) / 4)*block_size; else image_size = width * height * block_size; switch (fill_mode) { case TEX_NORMAL: glTexImage2D(m_target, level, glinternal, width, height, 0, glformat, gltype, data); break; case TEX_COMPRESS: glCompressedTexImage2D(m_target, level, glinternal, width, height, 0, image_size, data); break; case TEX_ARRAYS: glTexImage3D(m_target, level, glinternal, width, height, m_depth, 0, glformat, gltype, data); break; case TEX_COMPRESS_ARRAY: glCompressedTexImage3D(m_target, level, glinternal, width, height, m_depth, 0, image_size, data); default: break; } // if (width > 1) width >>= 1; if (height > 1) height >>= 1; if (data != NULL) data += image_size; } } } void OGL_Texture::create3D(GLint glinternal, GLenum glformat, GLenum gltype, bool compressed, char fill_mode, const char* data) { size_t block_size = PixelUtil::getBytes(m_format); size_t width, height, depth, image_size; width = m_width; height = m_height; depth = m_depth; for (uint32_t level = 0; level < m_mipmaps; ++level) { if (compressed) { image_size = ((width + 3) / 4) * ((height + 3) / 4) * depth *block_size; glCompressedTexImage3D(m_target, level, glinternal, width, height, depth, 0, image_size, data); } else { image_size = width * height * depth * block_size; glTexImage3D(m_target, level, glinternal, width, height, depth, 0, glformat, gltype, data); } if (width > 1) width >>= 1; if (height > 1) height >>= 1; if (depth > 1) depth >>= 1; if (data != NULL) data += image_size; } } void OGL_Texture::createCube(GLint glinternal, GLenum glformat, GLenum gltype, bool compressed, char fill_mode, const char* data) { size_t block_size = PixelUtil::getBytes(m_format); size_t width, height, image_size; GLenum target = GL_TEXTURE_CUBE_MAP_POSITIVE_X; // can change to: _depth * 6 ? for (uint32_t array_index = 0; array_index < m_depth; ++array_index) { for (uint32_t face = 0; face < 6; ++face) { width = m_width; height = m_height; for (uint32_t level = 0; level < m_mipmaps; ++level) { if (compressed) image_size = ((width + 3) / 4) * ((height + 3) / 4)*block_size; else image_size = width * height * block_size; switch (fill_mode) { case TEX_NORMAL: glTexImage2D(target + face, level, glinternal, width, height, 0, glformat, gltype, data); break; case TEX_COMPRESS: glCompressedTexImage2D(target + face, level, glinternal, width, height, 0, image_size, data); break; case TEX_ARRAYS: glTexImage3D(target + face, level, glinternal, width, height, m_depth, 0, glformat, gltype, data); break; case TEX_COMPRESS_ARRAY: glCompressedTexImage3D(target + face, level, glinternal, width, height, m_depth, 0, image_size, data); default: break; } // if (width > 1) width >>= 1; if (height > 1) height >>= 1; if (data != NULL) data += image_size; } } } } CUTE_NS_END
[ "jeckbjy@163.com" ]
jeckbjy@163.com
28ba582bd5d521c3db97db950090064ee01f2c35
325b233263cb724243812b076e8b1bf9d3474749
/example_get/example_get.ino
a8069d28ad6d87164fee0cfe649029229faa0315
[]
no_license
zjohnsilver/micro_project
8a41597b6bfbe5edb53630f5a3cb42aefb0957b7
dde0ae7a1fea0e66247ed111b24c0025d4f1b85a
refs/heads/master
2022-12-22T15:12:36.524357
2019-12-19T07:12:45
2019-12-19T07:12:45
228,718,320
0
0
null
2022-12-13T23:21:00
2019-12-17T23:19:51
C++
UTF-8
C++
false
false
1,129
ino
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> //Definicoes da rede wifi e conexao String ssid = "Lancelot"; //Nome da sua rede wifi String pass = "87654321"; //Senha da sua rede wifi String token = "978440572:AAHqTNTN79X_VyLjgu7f230vVuC5VsICfMQ"; //Token bot Telegram void setup() { Serial.begin(115200); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("Connecting.."); } Serial.print("Successful Conection"); } void loop() { if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status HTTPClient http; //Declare an object of class HTTPClient http.begin("http://d47acae1.ngrok.io/consumptions"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } delay(30000); //Send a request every 30 seconds }
[ "john.silver@delfosim.com" ]
john.silver@delfosim.com
95cc8c3937a4ae23d69fa2ada9a05739186da29e
50bdaa2e71aae37240c61c930decbfe9d1e504b8
/harp-daal-app/daal-src/include/algorithms/boosting/logitboost_training_batch.h
5fba866eb86edb7a476af095f1ac4b8cde3a56c4
[ "Apache-2.0" ]
permissive
prawalgangwar/harp
010b1f669ee54941365ba1204be4e1484c15f108
3c3a3bf2d519f76ccf8ae17d8b3681e0a93048b7
refs/heads/master
2020-09-13T19:57:54.274328
2017-06-20T00:03:57
2017-06-20T00:03:57
94,464,682
0
0
null
2017-06-15T17:49:16
2017-06-15T17:49:16
null
UTF-8
C++
false
false
6,621
h
/* file: logitboost_training_batch.h */ /******************************************************************************* * Copyright 2014-2016 Intel Corporation * * 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. *******************************************************************************/ /* //++ // Implementation of the interface for LogitBoost model-based training //-- */ #ifndef __LOGIT_BOOST_TRAINING_BATCH_H__ #define __LOGIT_BOOST_TRAINING_BATCH_H__ #include "algorithms/boosting/boosting_training_batch.h" #include "algorithms/boosting/logitboost_training_types.h" namespace daal { namespace algorithms { namespace logitboost { namespace training { namespace interface1 { /** * @defgroup logitboost_training_batch Batch * @ingroup logitboost_training * @{ */ /** * <a name="DAAL-CLASS-ALGORITHMS__LOGITBOOST__TRAINING__BATCHCONTAINER"></a> * \brief Provides methods to run implementations of LogitBoost model-based training. * This class is associated with daal::algorithms::logitboost::training::Batch class * * \tparam algorithmFPType Data type to use in intermediate computations for the LogitBoost, double or float * \tparam method LogitBoost model training method, \ref Method */ template<typename algorithmFPType, Method method, CpuType cpu> class DAAL_EXPORT BatchContainer : public TrainingContainerIface<batch> { public: /** * Constructs a container for LogitBoost model-based training with a specified environment * in the batch processing mode * \param[in] daalEnv Environment object */ BatchContainer(daal::services::Environment::env *daalEnv); /** Default destructor */ ~BatchContainer(); /** * Computes the result of LogitBoost model-based training in the batch processing mode */ void compute() DAAL_C11_OVERRIDE; }; /** * <a name="DAAL-CLASS-ALGORITHMS__LOGITBOOST__TRAINING__BATCH"></a> * \brief Trains model of the LogitBoost algorithms in the batch processing mode * \n<a href="DAAL-REF-LOGITBOOST-ALGORITHM">LogitBoost algorithm description and usage models</a> * * \tparam algorithmFPType Data type to use in intermediate computations for LogitBoost, double or float * \tparam method LogitBoost computation method, \ref daal::algorithms::logitboost::training::Method * * \par Enumerations * - \ref Method LogitBoost training methods * - \ref classifier::training::InputId Identifiers of input objects for the LogitBoost training algorithm * - \ref classifier::training::ResultId Identifiers of LogitBoost training results * * \par References * - \ref interface1::Parameter "Parameter" class * - \ref interface1::Model "Model" class * - \ref classifier::training::interface1::Input "classifier::training::Input" class * - Result class */ template<typename algorithmFPType = double, Method method = friedman> class DAAL_EXPORT Batch : public boosting::training::Batch { public: daal::algorithms::logitboost::Parameter parameter; /*!< Parameters of the algorithm */ /** * Constructs the LogitBoost training algorithm * \param[in] nClasses Number of classes */ Batch(size_t nClasses) { initialize(); parameter.nClasses = nClasses; } /** * Constructs a LogitBoost training algorithm by copying input objects and parameters * of another LogitBoost training algorithm * \param[in] other An algorithm to be used as the source to initialize the input objects * and parameters of the algorithm */ Batch(const Batch<algorithmFPType, method> &other) : boosting::training::Batch(other) { initialize(); parameter = other.parameter; } virtual ~Batch() {} /** * Returns the method of the algorithm * \return Method of the algorithm */ virtual int getMethod() const DAAL_C11_OVERRIDE { return(int)method; } /** * Returns the structure that contains results of LogitBoost training * \return Structure that contains results of LogitBoost training */ services::SharedPtr<Result> getResult() { return services::staticPointerCast<Result, classifier::training::Result>(_result); } /** * Registers user-allocated memory to store results of LogitBoost training * \param[in] result Structure to store results of LogitBoost training */ void setResult(const services::SharedPtr<Result>& result) { DAAL_CHECK(result, ErrorNullResult) _result = result; _res = _result.get(); } /** * Resets the training results of the classification algorithm */ void resetResult() DAAL_C11_OVERRIDE { _result = services::SharedPtr<Result>(new Result()); _res = NULL; } /** * Returns a pointer to the newly allocated LogitBoost training algorithm with a copy of input objects * and parameters of this LogitBoost training algorithm * \return Pointer to the newly allocated algorithm */ services::SharedPtr<Batch<algorithmFPType, method> > clone() const { return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl()); } protected: virtual Batch<algorithmFPType, method> * cloneImpl() const DAAL_C11_OVERRIDE { return new Batch<algorithmFPType, method>(*this); } void allocateResult() DAAL_C11_OVERRIDE { services::SharedPtr<Result> res = services::staticPointerCast<Result, classifier::training::Result>(_result); res->template allocate<algorithmFPType>(&input, _par, method); _res = _result.get(); } void initialize() { _ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env); _par = &parameter; _result = services::SharedPtr<Result>(new Result()); } }; /** @} */ } // namespace interface1 using interface1::BatchContainer; using interface1::Batch; } // namespace daal::algorithms::logitboost::training } } } // namespace daal #endif // __LOGIT_BOOST_TRAINING_BATCH_H__
[ "lc37@156-56-102-164.dhcp-bl.indiana.edu" ]
lc37@156-56-102-164.dhcp-bl.indiana.edu
0880b8a22e9a99ee9689e581b6b2f1e8456c6ff9
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/thread/test/sync/mutual_exclusion/locks/shared_lock/obs/mutex_pass.cpp
24f444257e5f92f903f622fd110c6df72f0734e5
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
1,108
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Copyright (C) 2011 Vicente J. Botet Escriba // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // <boost/thread/locks.hpp> // template <class Mutex> class shared_lock; // Mutex *mutex() const; #include <boost/thread/locks.hpp> #include <boost/thread/shared_mutex.hpp> #include <boost/detail/lightweight_test.hpp> boost::shared_mutex m; int main() { boost::shared_lock<boost::shared_mutex> lk0; BOOST_TEST(lk0.mutex() == 0); boost::shared_lock<boost::shared_mutex> lk1(m); BOOST_TEST(lk1.mutex() == &m); lk1.unlock(); BOOST_TEST(lk1.mutex() == &m); return boost::report_errors(); }
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
429c7e771e2b82195e0420acc642114e98085486
016d77fd7e9b3587cd83fb11b805d748a11d2531
/docs/cppprimer/part01/chapter02/src/0203.cpp
425c36c00ddcd344705049114824b9e2312385e3
[]
no_license
kadoyatsukasa/kadoyatsukasa.github.io
3c88459438499abdbfd2106adc8887aca45d9404
b765581d12962dcc2286eda994e5590907ee2dc9
refs/heads/master
2021-07-16T22:33:16.401357
2020-05-25T07:25:03
2020-05-25T07:25:03
165,992,723
1
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
// // Created by ErikLu on 2020/3/14. // #include <iostream> using std::cout; using std::endl; int main(){ unsigned u =10,u2=42; std::cout<<u2-u<<std::endl; std::cout<<u-u2<<std::endl; int i=10,i2=42; std::cout<<i2-i<<std::endl; std::cout<<i-i2<<std::endl; std::cout<<i-u<<std::endl; std::cout<<u-i<<std::endl; return 0; }
[ "amaduesmozart@outlook.com" ]
amaduesmozart@outlook.com
911c0fa501ff3caa35add78965d0b1cbdeb7a87e
1a8ee2cec1d1a5a884dfabb5393db9ecac060151
/src/dawn/engine_dawn.h
50d0d0989b75382b0c7f4001e16ad725df4df98f
[ "Apache-2.0" ]
permissive
dneto0/amber
35499167d90c784cd42e6c28c311ee577f191ad8
6a99f53afd788a5e6d42459bf9338efb8365bc76
refs/heads/master
2023-06-14T14:38:16.050637
2018-11-13T14:58:29
2018-11-13T22:13:18
157,454,306
0
0
Apache-2.0
2018-11-13T22:14:27
2018-11-13T22:14:27
null
UTF-8
C++
false
false
2,415
h
// Copyright 2018 The Amber Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_DAWN_ENGINE_DAWN_H_ #define SRC_DAWN_ENGINE_DAWN_H_ #include "dawn/dawncpp.h" #include "src/engine.h" namespace amber { namespace dawn { class EngineDawn : public Engine { public: EngineDawn(); ~EngineDawn() override; // Engine // Initialize with a default device. Result Initialize() override; // Initialize with a given device, specified as a pointer-to-::dawn::Device // disguised as a pointer-to-void. Result InitializeWithDevice(void* default_device) override; Result Shutdown() override; Result CreatePipeline(PipelineType) override; Result AddRequirement(Feature feature, const Format*) override; Result SetShader(ShaderType type, const std::vector<uint32_t>& data) override; Result SetBuffer(BufferType type, uint8_t location, const Format& format, const std::vector<Value>& data) override; Result DoClearColor(const ClearColorCommand* cmd) override; Result DoClearStencil(const ClearStencilCommand* cmd) override; Result DoClearDepth(const ClearDepthCommand* cmd) override; Result DoClear(const ClearCommand* cmd) override; Result DoDrawRect(const DrawRectCommand* cmd) override; Result DoDrawArrays(const DrawArraysCommand* cmd) override; Result DoCompute(const ComputeCommand* cmd) override; Result DoEntryPoint(const EntryPointCommand* cmd) override; Result DoPatchParameterVertices( const PatchParameterVerticesCommand* cmd) override; Result DoProbe(const ProbeCommand* cmd) override; Result DoProbeSSBO(const ProbeSSBOCommand* cmd) override; Result DoBuffer(const BufferCommand* cmd) override; Result DoTolerance(const ToleranceCommand* cmd) override; private: ::dawn::Device device_; }; } // namespace dawn } // namespace amber #endif // SRC_DAWN_ENGINE_DAWN_H_
[ "dneto@google.com" ]
dneto@google.com
b695002e77498a5a7a318e283edabf659808aae9
ba46ecf353e4c9e765669a4978294bc6b725afc9
/Dustin/IntelligentCameraSystem/Types/encodingparameters.h
28dd986c965519806a03890784824b9f71e63e4c
[]
no_license
mocalab/ScalableVideo
c600ba466807b5addb436afc12d607b5288e2fdc
527babeb716c58c77ca958797cbd2a15a34331d6
refs/heads/master
2020-12-24T18:03:10.503624
2014-10-02T06:02:02
2014-10-02T06:02:02
13,903,683
0
2
null
null
null
null
UTF-8
C++
false
false
1,782
h
/** * @file Definition of the EncodingParameters class. */ #ifndef ENCODINGPARAMETERS_H #define ENCODINGPARAMETERS_H #include <iostream> #include <QString> /** * @brief A type encapsulating the tunable parameters of the encoder. */ class EncodingParameters { public: /** * @brief Default value constructor. */ EncodingParameters(); /** * @brief Copy constructor. * @param cpy The parameters to copy. */ EncodingParameters(EncodingParameters& cpy); /** * @brief Overloaded assignment operator. * @param rhs The EncodingParameters object to copy over. * @return A reference to this object. */ EncodingParameters &operator=(EncodingParameters &rhs); /** * @brief Explicit value constructor. * @param width * @param height * @param fps * @param bitrate */ EncodingParameters(QString width, QString height, QString fps, QString bitrate); QString width() const; void setWidth(const QString &width); QString height() const; void setHeight(const QString &height); QString fps() const; void setFps(const QString &fps); QString bitrate() const; void setBitrate(const QString &bitrate); //Getters as integers int widthAsInt() const; int heightAsInt() const; int fpsAsInt() const; int bitrateAsInt() const; /** * @brief Overloaded equivalence operator. * @param rhs The object for comparison. * @return True if all of the fields are equal, false otherwise. */ bool operator==(const EncodingParameters &rhs); private: QString m_width; QString m_height; QString m_fps; QString m_bitrate; }; #endif // ENCODINGPARAMETERS_H
[ "dustin.wright37@gmail.com" ]
dustin.wright37@gmail.com
595e815559ebf133c3f80f66796580bd92ae1e55
6f72b28dd5fc3e5c04417afa888e6ffc70b00333
/shiva/shivalib/qmake/shivatester/main.cpp
07d68252bdaef679208cbacb5efd6636839def40
[]
no_license
ElmerFuddDK/libshiva
71ffb760ded57920289fa863bffc1a6aa369a9ba
4d9424945f05a30ef3c3719bafe0bc931803cbf7
refs/heads/master
2021-10-26T20:25:37.787532
2021-10-19T06:08:15
2021-10-19T06:08:15
35,969,748
0
0
null
null
null
null
UTF-8
C++
false
false
3,956
cpp
/* * Copyright (C) 2008 by Lars Eriksen * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version with the following * exeptions: * * 1) Static linking to the library does not constitute derivative work * and does not require the author to provide source code for the * application. * Compiling applications with the source code directly linked in is * Considered static linking as well. * * 2) You do not have to provide a copy of the license with programs * that are linked against this code. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "../../../include/platformspc.h" #include "../../../include/framework/shvmodule.h" #include "../../../include/framework/shveventstdin.h" #include "../../../include/frameworkimpl/shvmainthreadeventdispatchergeneric.h" #include "../../../include/shvversion.h" #include "../../../include/framework/shvtimer.h" #include "../../../include/utils/shvmath.h" class SHVTest : public SHVModule { private: SHVTimerInstanceRef TimerInstance; SHVTimer* Timer; public: SHVTest(SHVModuleList& modules) : SHVModule(modules,"Test") { Modules.GetConfig().Set(_S("test"),2); Modules.GetConfig().FindInt(_S("test2"),128); SHVConsole::Printf8("result 128-2^6 : %g\n", SHVMath::EvalMap(_S("test2-test^6"),Modules.GetConfig())); } SHVBool Register() { SHVConsole::Printf8("In register\n"); if (!SHVModuleResolver<SHVTimer>(Modules, Timer, "Timer")) return SHVBool::False; SHVASSERT(Modules.ResolveModule("Test")); Modules.EventSubscribe(SHVModuleList::EventClosing, new SHVEventSubscriber(this)); return SHVModule::Register(); } void PostRegister() { SHVTime now; now.SetNow(); SHVConsole::Printf(_S("Started: Time now %s\n"), now.ToDateString().GetBufferConst()); now.AddSeconds(5); SHVConsole::Printf8("Application running...\n"); TimerInstance = Timer->CreateTimer(new SHVEventSubscriber(this)); TimerInstance->SetAbsolute(now); } void OnEvent(SHVEvent* event) { if (event->GetCaller() == Timer) { SHVTime now; now.SetNow(); SHVConsole::Printf8(_S("Stopped: Time now %s\n"), now.ToDateString().GetBufferConst()); SHVConsole::Printf8("Shutting it down\n"); Modules.CloseApp(); } else { SHVConsole::Printf8("Delaying shutdown by 1000 ms\n"); Modules.EmitEvent(new SHVEventString(this,__EVENT_GLOBAL_DELAYSHUTDOWN,1000)); } } void Unregister() { SHVConsole::Printf8("In unregister\n"); SHVModule::Unregister(); } }; CONSOLEMAIN() { if (!SHVModuleList::CheckVersion(__SHIVA_VERSION_MAJOR, __SHIVA_VERSION_MINOR, __SHIVA_VERSION_RELEASE)) { SHVConsole::ErrPrintf8("WRONG SHIVA VERSION\n"); } else { SHVMainThreadEventQueue mainqueue(new SHVMainThreadEventDispatcherGeneric()); SHVString testStr; CONSOLEPARSEARGS(mainqueue.GetModuleList().GetConfig()); mainqueue.GetModuleList().AddModule(new SHVTest(mainqueue.GetModuleList())); SHVConsole::Printf8("Testing assertions - should fail in debug mode\n"); SHVASSERT(false); testStr.Format(_S("This is a test %s %d.%d.%d\n"), _S("of SHIVA version"), __SHIVA_VERSION_MAJOR, __SHIVA_VERSION_MINOR, __SHIVA_VERSION_RELEASE); SHVConsole::Printf(_S("%s"), testStr.GetSafeBuffer()); return mainqueue.Run().GetError(); } return -1; }
[ "git@jagular.dk" ]
git@jagular.dk
43750184b44aba810c092620713089436dbf8acd
4be7a3f1465554edc9b31aacc2692daac51c46aa
/AFI/DataSet.cpp
cfa1034803fa19be2c3a729fdf547062ce83ad1e
[]
no_license
kbavishi/MineBench
b90eaeb485b736cb80a4a5a7d09f966ef3eedf9d
74a8ef895a07f32164b20876798560f02f2b561e
refs/heads/master
2021-01-18T23:13:07.585731
2017-04-17T21:29:44
2017-04-17T21:29:44
87,095,090
2
0
null
null
null
null
UTF-8
C++
false
false
4,701
cpp
#include "DataSet.h" #include <algorithm> #include <vector> bool operator<(const Bitmap &a, const Bitmap &b) { return (a.CountOnes() < b.CountOnes()); } bool operator==(const Bitmap &a, const Bitmap &b) { bool equal = (a.CountOnes() == b.CountOnes()); return equal; } // load in a file with market-basket data (1-based indexing) DataSet::DataSet(string filename) { ifstream inFile(filename.c_str()); items = 0; // load the data from the file string thisLine; while (getline(inFile, thisLine)) { vector <int> currentLine; int temp; stringstream stream(thisLine, stringstream::in); while (stream >> temp) { currentLine.push_back(temp); if (temp > items) items = temp; } theData.push_back(currentLine); } transactions = theData.size(); // create the vectors of bitmaps for both rows (transactions) and columns (items) for (int item = 0; item < items; item++) { itemBits.push_back(Bitmap(transactions)); itemBits[item].SetID(item+1); itemBits[item].Clear(); } for (int trans = 0; trans < transactions; trans++) { transBits.push_back(Bitmap(items)); transBits[trans].Clear(); } // fill the item bitmaps for (int trans = 0; trans < transactions; trans++) { int size = (int) theData[trans].size(); for (int item = 0; item < size; item++) { itemBits[theData[trans][item]-1].SetBit(trans, true); } } // sort the items in order of increasing support vector<Bitmap>::iterator start = itemBits.begin(); vector<Bitmap>::iterator end = itemBits.end(); sort(start, end); // fill the transaction bitmaps for (int trans = 0; trans < transactions; trans++) { for (int item = 0; item < items; item++) { transBits[trans].SetBit(item, itemBits[item].GetBit(trans)); } } // sort the transactions in order of increasing width /* start = transBits.begin(); end = transBits.end(); sort(start, end);*/ // cerr << "loaded " << transactions << " transactions, " // << items << " items" << endl; } Bitmap * DataSet::GetItemBitmap(int index) { return &(itemBits[index]); } //Bitmap * DataSet::GetBitmaps() const {return itemBits;} int DataSet::GetActualIndex(int index) const { return itemBits[index].GetID(); } void DataSet::AddItemToZeroCount(int *zeros, int item) const { for (int r = 0; r < transactions; r++) { if (!ValueAt(r, item)) { zeros[r]++; //cout << "zero at: " << r << ", " << item << endl; } } } void DataSet::RemoveItemFromZeroCount(int *zeros, int item) const { for (int r = 0; r < transactions; r++) if (!ValueAt(r, item)) zeros[r]--; } int DataSet::GetRemainingOnesInTransaction(int trans, int after) const { return transBits[trans].CountOnesAfter(after); } int * DataSet::GetSupportSet(int searchFor, int *length) { vector<int> indices; for (int i = 0; i < transactions; i++) { if (ValueAt(i, searchFor)) indices.push_back(i); } *length = indices.size(); int *newSet = new int[*length]; for (int i = 0; i < *length; i++) newSet[i] = indices[i]; return newSet; } bool DataSet::ValueAt(int r, int c) const { bool item = itemBits[c].GetBit(r); bool trans = transBits[r].GetBit(c); if (item != trans) cerr << "oh no!!!" << endl; return itemBits[c].GetBit(r);//(supportBitmaps[r / 32][c] & (1 << (r % 32)));// << endl; int lineSize = theData[r].size(); int left = 0; int right = lineSize - 1; int mid; int searchingFor = c + 1; if (r >= transactions) cout << "r value too high: " << r << endl; if (c > items) cout << "c value too high: " << c << endl; while (left < right) { // cout << left << ", " << right << endl; mid = (right + left) / 2; if (theData[r][mid] < searchingFor) { left = mid + 1; } else if (theData[r][mid] > searchingFor) { right = mid - 1; } else if (theData[r][mid] == searchingFor) { return true; } /* if (left == right - 1) return (theData[r][left] == searchingFor || theData[r][right] == searchingFor);*/ } return false; } int DataSet::GetTransactionCount() const {return transactions;} int DataSet::GetItemCount() const {return items;} ostream & operator<<(ostream & out, DataSet & d) { for (int item = 0; item < d.items; item++) { for (int row = 0; row < d.transactions; row++) { out << (d.ValueAt(row, item) ? "X" : "."); } out << " " << d.itemBits[item].GetID() << " - " << d.itemBits[item].CountOnes() << endl; } for (int row = 0; row < d.transactions; row++) { out << d.transBits[row].CountOnes() << endl; } return out; }
[ "karan.bavishi90@gmail.com" ]
karan.bavishi90@gmail.com
7e327a978012df3a255d497d7cd6fa4274b798a8
4533dca4e65cf56b89a710424bea2408d0dabe4d
/drake/systems/LCMSystem.h
2d1cdaa3384f6bab99fee15db927f7f3f1c58fbc
[ "BSD-3-Clause" ]
permissive
hanssusilo/drake
88b471c88abaf0b537befa43fb9726aaab38b4da
0e15c4cb593b1ce81cc53de8563236f3555358b1
refs/heads/master
2021-01-21T07:00:10.679275
2016-01-29T23:25:16
2016-01-29T23:25:16
48,151,060
0
0
null
2015-12-17T03:51:34
2015-12-17T03:51:33
null
UTF-8
C++
false
false
9,407
h
#ifndef DRAKE_LCMSYSTEM_H #define DRAKE_LCMSYSTEM_H #include <unordered_map> #include <mutex> #include <thread> #include <stdexcept> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drake/lcmt_drake_signal.hpp" #include "System.h" #include "Simulation.h" #include <drakeLCMSystem_export.h> namespace Drake { /** @defgroup lcm_vector_concept LCMVector<ScalarType> Concept * @ingroup vector_concept * @brief A specialization of the Vector concept adding the ability to read and publish LCM messages * * | Valid Expressions (which must be implemented) | | * ------------------|-------------------------------------------------------------| * | LCMMessageType | defined with a typedef | * | static std::string channel() const | return the name of the channel to subscribe to/ publish on | * | bool encode(const double& t, const Vector<double>& x, LCMMessageType& msg) | define the mapping from your LCM type to your Vector type | * | bool decode(const LCMMessageType& msg, double& t, Vector<double>& x) | define the mapping from your Vector type to your LCM type | */ template <template <typename> class Vector> bool encode(const double& t, const Vector<double>& x, drake::lcmt_drake_signal& msg) { msg.timestamp = static_cast<int64_t>(t*1000); msg.dim = size(x); auto xvec = toEigen(x); for (int i=0; i<msg.dim; i++) { msg.coord.push_back(getCoordinateName(x,i)); msg.val.push_back(xvec(i)); } return true; } template <template <typename> class Vector> bool decode(const drake::lcmt_drake_signal& msg, double& t, Vector<double>& x) { t = double(msg.timestamp)/1000.0; std::unordered_map<std::string,double> m; for (int i=0; i<msg.dim; i++) { m[msg.coord[i]] = msg.val[i]; } Eigen::Matrix<double,Vector<double>::RowsAtCompileTime,1> xvec(msg.dim); for (int i=0; i<msg.dim; i++) { xvec(i) = m[getCoordinateName(x,i)]; } x = xvec; return true; } namespace internal { template<template<typename> class Vector, typename Enable = void> class LCMInputSystem { public: template<typename ScalarType> using StateVector = NullVector<ScalarType>; template<typename ScalarType> using InputVector = NullVector<ScalarType>; template<typename ScalarType> using OutputVector = Vector<ScalarType>; const static bool has_lcm_input = false; template <typename System> LCMInputSystem(const System& wrapped_sys, const std::shared_ptr<lcm::LCM> &lcm) : all_zeros(Eigen::VectorXd::Zero(getNumInputs(wrapped_sys))) { }; StateVector<double> dynamics(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return StateVector<double>(); } OutputVector<double> output(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return all_zeros; } private: OutputVector<double> all_zeros; }; template<template<typename> class Vector> class LCMInputSystem<Vector, typename std::enable_if<!std::is_void<typename Vector<double>::LCMMessageType>::value>::type> { public: template<typename ScalarType> using StateVector = NullVector<ScalarType>; template<typename ScalarType> using InputVector = NullVector<ScalarType>; template<typename ScalarType> using OutputVector = Vector<ScalarType>; const static bool has_lcm_input = true; template <typename System> LCMInputSystem(const System& sys, const std::shared_ptr<lcm::LCM> &lcm) { lcm::Subscription* sub = lcm->subscribe(Vector<double>::channel(),&LCMInputSystem<Vector>::handleMessage,this); sub->setQueueCapacity(1); }; virtual ~LCMInputSystem() {}; void handleMessage(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const typename Vector<double>::LCMMessageType* msg) { data_mutex.lock(); decode<Vector>(*msg,timestamp,data); data_mutex.unlock(); } StateVector<double> dynamics(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return StateVector<double>(); } OutputVector<double> output(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { data_mutex.lock(); OutputVector<double> y = data; // make a copy of the data data_mutex.unlock(); return y; } private: mutable std::mutex data_mutex; double timestamp; OutputVector<double> data; }; template<template<typename> class Vector, typename Enable = void> class LCMOutputSystem { public: template<typename ScalarType> using StateVector = NullVector<ScalarType>; template<typename ScalarType> using InputVector = Vector<ScalarType>; template<typename ScalarType> using OutputVector = NullVector<ScalarType>; LCMOutputSystem(const std::shared_ptr<lcm::LCM> &lcm) { }; StateVector<double> dynamics(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return StateVector<double>(); } OutputVector<double> output(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return OutputVector<double>(); } }; template<template<typename> class Vector> class LCMOutputSystem<Vector, typename std::enable_if<!std::is_void<typename Vector<double>::LCMMessageType>::value>::type> { public: template<typename ScalarType> using StateVector = NullVector<ScalarType>; template<typename ScalarType> using InputVector = Vector<ScalarType>; template<typename ScalarType> using OutputVector = NullVector<ScalarType>; LCMOutputSystem(const std::shared_ptr<lcm::LCM> &lcm) : lcm(lcm) { }; StateVector<double> dynamics(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { return StateVector<double>(); } OutputVector<double> output(const double &t, const StateVector<double> &x, const InputVector<double> &u) const { typename Vector<double>::LCMMessageType msg; if (!encode(t, u, msg)) throw std::runtime_error(std::string("failed to encode") + msg.getTypeName()); lcm->publish(u.channel(), &msg); return OutputVector<double>(); } private: std::shared_ptr<lcm::LCM> lcm; }; // todo: template specialization for the CombinedVector case class DRAKELCMSYSTEM_EXPORT LCMLoop { public: bool stop; lcm::LCM& lcm; LCMLoop(lcm::LCM& _lcm) : lcm(_lcm), stop(false) {} void loopWithSelect(); }; } // end namespace internal /** runLCM * @brief Simulates the system with the (exposed) inputs being read from LCM and the output being published to LCM. * @ingroup simulation * * The input and output vector types must overload a publishLCM namespace method; the default for new vectors is to not publish anything. */ template <typename System> void runLCM(const std::shared_ptr<System>& sys, const std::shared_ptr<lcm::LCM>& lcm, double t0, double tf, const typename System::template StateVector<double>& x0, const SimulationOptions& options = default_simulation_options) { if(!lcm->good()) throw std::runtime_error("bad LCM reference"); // typename System::template OutputVector<double> x = 1; // useful for debugging auto lcm_input = std::make_shared<internal::LCMInputSystem<System::template InputVector> >(*sys,lcm); auto lcm_output = std::make_shared<internal::LCMOutputSystem<System::template OutputVector> >(lcm); auto lcm_sys = cascade(lcm_input,cascade(sys,lcm_output)); bool has_lcm_input = internal::LCMInputSystem<System::template InputVector>::has_lcm_input; if (has_lcm_input && size(x0)==0 && !sys->isTimeVarying()) { // then this is really a static function, not a dynamical system. // block on receiving lcm input and process the output exactly when a new input message is received. // note: this will never return (unless there is an lcm error) // std::cout << "LCM output will be triggered on receipt of an LCM Input" << std::endl; double t = 0.0; typename System::template StateVector<double> x; NullVector<double> u; while (1) { if (lcm->handle() != 0) { throw std::runtime_error("something went wrong in lcm.handle"); } lcm_sys->output(t, x, u); } } else { internal::LCMLoop lcm_loop(*lcm); std::thread lcm_thread; if (has_lcm_input) { // only start up the listener thread if I actually have inputs to listen to lcm_thread = std::thread(&internal::LCMLoop::loopWithSelect, &lcm_loop); } SimulationOptions lcm_options = options; lcm_options.realtime_factor = 1.0; simulate(*lcm_sys, t0, tf, x0, lcm_options); if (has_lcm_input) { // shutdown the lcm thread lcm_loop.stop = true; lcm_thread.join(); } } } template <typename System> void runLCM(const std::shared_ptr<System>& sys, const std::shared_ptr<lcm::LCM>& lcm, double t0, double tf) { runLCM(sys,lcm,t0,tf,getInitialState(*sys)); } } // end namespace Drake #endif //DRAKE_LCMSYSTEM_H
[ "russt@mit.edu" ]
russt@mit.edu
99e86024d98f60db5bf1f057af40f3a626340a8d
e1908434d0f562dd477f80200e6e0605c79ab8cc
/libjingle/talk/base/virtualsocket_unittest.cc
96819e90d5f58023285db2e69635191ff6f2814c
[ "BSD-3-Clause" ]
permissive
ahiliation/unshackle
5702c6b724c338f89500cdeba88ecc0a7a9f1b1e
1c310947ecbde3162f729c875982fbd4d26cd2d0
refs/heads/master
2021-01-21T05:00:03.626056
2008-08-08T08:06:55
2008-08-08T08:06:55
32,208,151
1
0
null
null
null
null
UTF-8
C++
false
false
6,464
cc
// Copyright 2006, Google Inc. #include <complex> #include <iostream> #include <cassert> #include "talk/base/thread.h" #include "talk/base/virtualsocketserver.h" #include "talk/base/testclient.h" #include "talk/base/time.h" #ifdef POSIX extern "C" { #include <errno.h> } #endif // POSIX using namespace talk_base; void test_basic(Thread* thread, VirtualSocketServer* ss) { std::cout << "basic: "; std::cout.flush(); SocketAddress addr1(ss->GetNextIP(), 5000); AsyncUDPSocket* socket = CreateAsyncUDPSocket(ss); socket->Bind(addr1); TestClient* client1 = new TestClient(socket); TestClient* client2 = new TestClient(CreateAsyncUDPSocket(ss)); SocketAddress addr2; client2->SendTo("foo", 3, addr1); client1->CheckNextPacket("foo", 3, &addr2); SocketAddress addr3; client1->SendTo("bizbaz", 6, addr2); client2->CheckNextPacket("bizbaz", 6, &addr3); assert(addr3 == addr1); for (int i = 0; i < 10; i++) { client2 = new TestClient(CreateAsyncUDPSocket(ss)); SocketAddress addr4; client2->SendTo("foo", 3, addr1); client1->CheckNextPacket("foo", 3, &addr4); assert((addr4.ip() == addr2.ip()) && (addr4.port() == addr2.port() + 1)); SocketAddress addr5; client1->SendTo("bizbaz", 6, addr4); client2->CheckNextPacket("bizbaz", 6, &addr5); assert(addr5 == addr1); addr2 = addr4; } std::cout << "PASS" << std::endl; } // Sends at a constant rate but with random packet sizes. struct Sender : public MessageHandler { Sender(Thread* th, AsyncUDPSocket* s, uint32 rt) : thread(th), socket(s), done(false), rate(rt), count(0) { last_send = GetMillisecondCount(); thread->PostDelayed(NextDelay(), this, 1); } uint32 NextDelay() { uint32 size = (rand() % 4096) + 1; return 1000 * size / rate; } void OnMessage(Message* pmsg) { assert(pmsg->message_id == 1); if (done) return; uint32 cur_time = GetMillisecondCount(); uint32 delay = cur_time - last_send; uint32 size = rate * delay / 1000; size = std::min(size, uint32(4096)); size = std::max(size, uint32(4)); count += size; *reinterpret_cast<uint32*>(dummy) = cur_time; socket->Send(dummy, size); last_send = cur_time; thread->PostDelayed(NextDelay(), this, 1); } Thread* thread; AsyncUDPSocket* socket; bool done; uint32 rate; // bytes per second uint32 count; uint32 last_send; char dummy[4096]; }; struct Receiver : public MessageHandler, public sigslot::has_slots<> { Receiver(Thread* th, AsyncUDPSocket* s, uint32 bw) : thread(th), socket(s), bandwidth(bw), done(false), count(0), sec_count(0), sum(0), sum_sq(0), samples(0) { socket->SignalReadPacket.connect(this, &Receiver::OnReadPacket); thread->PostDelayed(1000, this, 1); } ~Receiver() { thread->Clear(this); } void OnReadPacket( const char* data, size_t size, const SocketAddress& remote_addr, AsyncPacketSocket* s) { assert(s == socket); assert(size >= 4); count += size; sec_count += size; uint32 send_time = *reinterpret_cast<const uint32*>(data); uint32 recv_time = GetMillisecondCount(); uint32 delay = recv_time - send_time; sum += delay; sum_sq += delay * delay; samples += 1; } void OnMessage(Message* pmsg) { assert(pmsg->message_id == 1); // It is always possible for us to receive more than expected because // packets can be further delayed in delivery. if (bandwidth > 0) assert(sec_count <= 5 * bandwidth / 4); sec_count = 0; thread->PostDelayed(1000, this, 1); } Thread* thread; AsyncUDPSocket* socket; uint32 bandwidth; bool done; uint32 count; uint32 sec_count; double sum; double sum_sq; uint32 samples; }; void test_bandwidth(Thread* thread, VirtualSocketServer* ss) { std::cout << "bandwidth: "; std::cout.flush(); AsyncUDPSocket* send_socket = CreateAsyncUDPSocket(ss); AsyncUDPSocket* recv_socket = CreateAsyncUDPSocket(ss); assert(send_socket->Bind(SocketAddress(ss->GetNextIP(), 1000)) >= 0); assert(recv_socket->Bind(SocketAddress(ss->GetNextIP(), 1000)) >= 0); assert(send_socket->Connect(recv_socket->GetLocalAddress()) >= 0); uint32 bandwidth = 64 * 1024; ss->set_bandwidth(bandwidth); Sender sender(thread, send_socket, 80 * 1024); Receiver receiver(thread, recv_socket, bandwidth); Thread* pthMain = Thread::Current(); pthMain->ProcessMessages(5000); sender.done = true; pthMain->ProcessMessages(5000); assert(receiver.count >= 5 * 3 * bandwidth / 4); assert(receiver.count <= 6 * bandwidth); // queue could drain for 1 sec delete send_socket; delete recv_socket; ss->set_bandwidth(0); std::cout << "PASS" << std::endl; } void test_delay(Thread* thread, VirtualSocketServer* ss) { std::cout << "delay: "; std::cout.flush(); uint32 mean = 2000; uint32 stddev = 500; ss->set_delay_mean(mean); ss->set_delay_stddev(stddev); ss->UpdateDelayDistribution(); AsyncUDPSocket* send_socket = CreateAsyncUDPSocket(ss); AsyncUDPSocket* recv_socket = CreateAsyncUDPSocket(ss); assert(send_socket->Bind(SocketAddress(ss->GetNextIP(), 1000)) >= 0); assert(recv_socket->Bind(SocketAddress(ss->GetNextIP(), 1000)) >= 0); assert(send_socket->Connect(recv_socket->GetLocalAddress()) >= 0); Sender sender(thread, send_socket, 64 * 1024); Receiver receiver(thread, recv_socket, 0); Thread* pthMain = Thread::Current(); pthMain->ProcessMessages(5000); sender.done = true; pthMain->ProcessMessages(5000); double sample_mean = receiver.sum / receiver.samples; double num = receiver.sum_sq - 2 * sample_mean * receiver.sum + receiver.samples * sample_mean * sample_mean; double sample_stddev = std::sqrt(num / (receiver.samples - 1)); std::cout << "mean=" << sample_mean << " dev=" << sample_stddev << std::endl; assert(0.9 * mean <= sample_mean); assert(sample_mean <= 1.1 * mean); assert(0.9 * stddev <= sample_stddev); assert(sample_stddev <= 1.1 * stddev); delete send_socket; delete recv_socket; ss->set_delay_mean(0); ss->set_delay_stddev(0); ss->UpdateDelayDistribution(); std::cout << "PASS" << std::endl; } int main (int argc, char** argv) { Thread *pthMain = Thread::Current(); VirtualSocketServer* ss = new VirtualSocketServer(); pthMain->set_socketserver(ss); test_basic(pthMain, ss); test_bandwidth(pthMain, ss); test_delay(pthMain, ss); return 0; }
[ "vu3rdd@cd642896-134c-0410-a112-c17eeddeda9d" ]
vu3rdd@cd642896-134c-0410-a112-c17eeddeda9d
45850f99a432e5eb90264f553996b9957fa5a923
bd9446f4f938f9cc81b44e019cd0b7c470433909
/KinectV1/Test/OpenNITestCode.cpp
8a00baf1f30dd82df5ff42cbfc0709a6ba3bd6fd
[]
no_license
WatsonLy/ToF-SL-3D-Hybridization-Project-Using-BP-MAP-MRF-
00ef4133ac39480997407223145feda6907bf57a
22ce46f06aeaf57c1c5c86124604f593119c5a76
refs/heads/master
2020-05-01T07:05:24.042491
2019-04-07T06:59:11
2019-04-07T06:59:11
177,344,708
0
1
null
2019-04-06T00:04:32
2019-03-23T22:04:20
C++
UTF-8
C++
false
false
2,870
cpp
#include <opencv2/core.hpp> #include <opencv2/opencv.hpp> #include <stdio.h> #include <OpenNI.h> #include <NiTE.h> #include <libfreenect2/libfreenect2.hpp> #include <libfreenect2/frame_listener_impl.h> #include <libfreenect2/registration.h> #include <libfreenect2/packet_pipeline.h> #include <libfreenect2/logger.h> using namespace std; using namespace cv; using namespace openni; //Prototypes bool HandleStatus(Status); char ReadLastCharOfLine(); int main(int argv, char* argc) { //Print OpenNI version number printf("OpenNi Version is %d.%d.%d.%d", OpenNI::getVersion().major, OpenNI::getVersion().minor, OpenNI::getVersion().maintenance, OpenNI::getVersion().build); //Initializes OpenNI status to scan for devices and check for errors printf("\nScanning machine for devices and loading modules/drivers...\r\n"); Status status = STATUS_OK; status = OpenNI::initialize(); //Outputs error if there is one and terminates program Calls user-defined HandleStatus function if (!HandleStatus(status)) return 1; printf("\nCompleted. \r\n"); //Creates an array of DeviceInfo objects called listOfDevices Array<DeviceInfo> listOfDevices; OpenNI::enumerateDevices(&listOfDevices); //enumerates the devices from the array of devices int numberOfDevices = listOfDevices.getSize(); //Executes if devices are found, iterates through the listed devices and shows information if (numberOfDevices > 0) { printf("%d Device(s) are available to use. \r\n\r\n", numberOfDevices); for (int i = 0; i < numberOfDevices; i++) { DeviceInfo device = listOfDevices[i]; printf("%d. %s->%s (VID: %d | PID: %d) is connected at %s\r\n", i, device.getVendor(), device.getName(), device.getUsbVendorId(), device.getUsbProductId(), device.getUri()); } } else { printf("No device connected to this machine."); } Device v1; DeviceInfo v1Info; VideoStream *depth_stream_ = new openni::VideoStream(); v1.open(ANY_DEVICE); VideoStream vid1; vid1.create(v1, SENSOR_DEPTH); VideoCapture capture(CAP_OPENNI_DEPTH_MAP); Mat depthMap; capture.grab(); capture.retrieve(depthMap, CAP_OPENNI); //cout << depthMap; //Stops program from terminating right away printf("Press ENTER to exit. \r\n"); ReadLastCharOfLine(); OpenNI::shutdown(); return 0; } //Function to check for errors bool HandleStatus(Status status) { if (status == STATUS_OK) return true; printf("ERROR: #%d, %s", status, OpenNI::getExtendedError()); ReadLastCharOfLine(); return false; } //Function to wait for userinput before terminating program char ReadLastCharOfLine() { int newChar = 0; int lastChar; fflush(stdout); do { lastChar = newChar; newChar = getchar(); } while ((newChar != '\n') && (newChar != EOF)); return (char)lastChar; }
[ "noreply@github.com" ]
noreply@github.com
bfa87e14172068c75c8a6df54aece05e180de3ff
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/068/704/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_54c.cpp
b4bc43f09ca1d9df58e97fc05229c1ba530c009d
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,294
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_54c.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml Template File: sources-sink-54c.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: memmove * BadSink : Copy TwoIntsClass array to data using memmove * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_54 { /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void badSink_d(TwoIntsClass * data); void badSink_c(TwoIntsClass * data) { badSink_d(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_d(TwoIntsClass * data); void goodG2BSink_c(TwoIntsClass * data) { goodG2BSink_d(data); } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
c48fe7fd120a6a62e53c0e3f540433af1101acef
0a4afb1a59d3d776d366e4cef2cb76541f1b8257
/Factorial.cpp
a5fdc51b6eaf6177424189c87283a4d1ee23396e
[]
no_license
ajarubab/cpp
17f8f1866f53f0a06f7c48db289fa3c0daf582f9
818b0e8bdea40b9f76a4b696f9c9414025a01221
refs/heads/master
2023-08-26T15:06:49.782202
2021-09-09T23:37:28
2021-09-09T23:37:28
400,568,093
0
0
null
null
null
null
UTF-8
C++
false
false
376
cpp
#include<iostream> using namespace std; int fact(int); int main() { int num,res; cout<<"Enter any Number :-\t"; cin>>num; res = fact(num); cout<<"The Facorial of "<<num<<" is "<<res<<endl; return 0; } int fact(int a) { if (a<=0) return 0; else if (a==1) { return 1; } else { return (a*fact(a-1)); } }
[ "noreply@github.com" ]
noreply@github.com
c28d24b18d9fa6d3dd8eca4dd463071ddc6ad0c2
9ae39413391ae9ca70530cf22938169f1e08b7ea
/homescreenapp/stateplugins/hsapplibrarystateplugin/tsrc/t_collectionsstate/src/t_collectionsstate.cpp
0e17dd716c293d5543bb191a81bc9e2b92448577
[]
no_license
SymbianSource/oss.FCL.sf.app.homescreen
1bde9a48b6e676706eb136069226fa1a9a12ae9d
61d721e71cc55557a6ad9c5ae066f07302c87aa2
refs/heads/master
2020-12-20T19:11:40.431784
2010-10-20T12:25:39
2010-10-20T12:25:39
65,833,139
0
0
null
null
null
null
UTF-8
C++
false
false
34,932
cpp
/* * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Main test class for hsHomeScreenStatePlugin library. * */ #include <hbmainwindow.h> #include <hbinstance.h> #include <hbview.h> #include <hbmenu.h> #include <hblabel.h> #include <hblistview.h> #include <hblistviewitem.h> #include <hbgroupbox.h> #include <HbAction> #include <HbPushButton> #include <qscopedpointer> #include "caentry.h" #include "caitemmodel.h" #include "hsmenuviewbuilder.h" #include "hsmenumodewrapper.h" #include "hsmenuevent.h" #include "hsmenueventtransition.h" #include "hscollectionstate.h" #include "hsmainwindow.h" #include "hsscene.h" #include "t_hsaddtohomescreenmockstate.h" #include "t_hsmockmodel.h" #include "t_collectionsstate.h" Q_DECLARE_METATYPE(Hs::HsSortAttribute) // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // class HsMainWindowMock : public HsMainWindow { virtual void setCurrentView(HbView *view); }; // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void HsMainWindowMock::setCurrentView(HbView *view) { Q_UNUSED(view); // do nothing } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::init() { } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::cleanup() { qApp->processEvents(); } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::construction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QState> parent(new QState); parent->setObjectName(tr("testName1")); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, parent.data()); QCOMPARE(collectionState->mSortAttribute, Hs::LatestOnTopHsSortAttribute); QCOMPARE(collectionState->mCollectionId, -1); QCOMPARE(collectionState->mModel, static_cast<HsMenuItemModel *>(0)); QCOMPARE(collectionState->objectName(), tr("testName1/collectionstate")); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::listItemActivated() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); QState *parent = new QState(machine.data()); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, parent); collectionState->mCollectionId = collectionId; HsMenuItemModel *const itemModel = HsMenuService::getAllApplicationsModel(Hs::AscendingNameHsSortAttribute); QModelIndex applicationModelIndex = itemModel->index(1, 0); QList<int> appList; appList << itemModel->data(applicationModelIndex, CaItemModel::IdRole).toInt(); HsMenuService::addApplicationsToCollection(appList, collectionId); collectionState->stateEntered(); QVERIFY(collectionState->mModel != NULL); collectionState->launchItem(applicationModelIndex); collectionState->stateExited(); QTest::qWait(3000); //TODO: made some utils to closing application //HsMenuService::executeAction(appList.at(0), QString("close")); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::listItemLongPressed() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); QState *parent(new QState(machine.data())); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsMenuItemModel *appsModel = HsMenuService::getAllApplicationsModel(); QVERIFY(appsModel!=NULL); QList<int> list; list << appsModel->data(appsModel->index(0),CaItemModel::IdRole).toInt(); HsMenuService::addApplicationsToCollection(list,collectionId); delete appsModel; HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, parent); QVERIFY(collectionState!=NULL); collectionState->mCollectionId = collectionId; collectionState->mCollectionType = "collection"; collectionState->stateEntered(); QScopedPointer<HbAbstractViewItem> item(new HbListViewItem); QModelIndex itemModelIndex = collectionState->mModel->index(0, 0); item->setModelIndex(itemModelIndex); collectionState->showContextMenu(item.data(), QPointF(50,50)); int numberOfActions = 3; EntryFlags rootFlags = collectionState->mModel->root().data(CaItemModel::FlagsRole).value< EntryFlags> (); if (rootFlags & RemovableEntryFlag) { numberOfActions++; } EntryFlags flags = item->modelIndex().data(CaItemModel::FlagsRole).value< EntryFlags> (); if ((flags & RemovableEntryFlag)) { numberOfActions++; } QSharedPointer<const CaEntry> entry = collectionState->mModel->entry(item->modelIndex()); if (!(entry->attribute(Hs::appSettingsPlugin).isEmpty())) { numberOfActions++; } QCOMPARE(collectionState->mContextMenu->actions().length(), numberOfActions); QVERIFY(collectionState->mContextMenu->testAttribute(Qt::WA_DeleteOnClose)); collectionState->stateExited(); qApp->processEvents(); // cleanup if (!list.isEmpty()) { for (int i=0; i<list.count(); i++) { HsMenuService::removeApplicationFromCollection(list[i],collectionId); } } HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::contextMenuAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { QScopedPointer<HbMainWindow> window(new HbMainWindow); HsScene::setInstance( new HsScene(window.data()) ); HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindow mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); // we will start from collection view const QString collectionName("testCollection" + QDateTime::currentDateTime().toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsMenuItemModel *allAppsModel = HsMenuService::getAllApplicationsModel(); QVERIFY(allAppsModel->rowCount() >= 1); QModelIndex appIndex = allAppsModel->index(0, 0); const int appId = allAppsModel->data(appIndex, CaItemModel::IdRole).toInt(); QList<int> appIdList; appIdList << appId; HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; HsMenuService::addApplicationsToCollection(appIdList, collectionId); // create a state which is to be reached when add-to-home-screen // event is triggered AddToHomeScreenMockState *addToHomeScreenState = new AddToHomeScreenMockState(machine.data()); // create a transition to the new child state which will be triggered by // an event with specified operation type HsMenuEventTransition addToHomeScreenTransition( HsMenuEvent::AddToHomeScreen, collectionState, addToHomeScreenState); // prepare the state graph collectionState->addTransition(&addToHomeScreenTransition); machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); HbAction *action = new HbAction("test_addtohomescreen"); action->setData(Hs::AddToHomeScreenContextAction); collectionState->mContextModelIndex = collectionState->mModel->index(0,0); collectionState->contextMenuAction(action); qApp->sendPostedEvents(); qApp->processEvents(); QVERIFY(addToHomeScreenState->enteredValue()); machine->stop(); // cleanup delete action; HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::contextMenuConstruct() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder menuView; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QState> parent(new QState); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(menuView, menuMode, mainWindow, parent.data()); collectionState->mCollectionId = collectionId; collectionState->stateEntered(); qApp->processEvents(); int actionsCount( collectionState->mMenuView->view()->menu()->actions().count()); QCOMPARE(actionsCount , 5); collectionState->stateExited(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::contextMenuConstructNonEmptyCollection() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder menuView; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QState> parent(new QState); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(menuView, menuMode, mainWindow, parent.data()); collectionState->mCollectionId = collectionId; QVERIFY(HsMenuService::addApplicationsToCollection(QList<int>()<<1, collectionId)); collectionState->stateEntered(); qApp->processEvents(); const int actionsCount( collectionState->mMenuView->view()->menu()->actions().count()); // Arrange is available inside options menu. QCOMPARE(actionsCount , 6); collectionState->stateExited(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::addAppsAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; AddToHomeScreenMockState *mockState = new AddToHomeScreenMockState(machine.data()); HsMenuEventTransition transition( HsMenuEvent::AddAppsToCollection, collectionState, mockState); collectionState->addTransition(&transition); machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); qApp->processEvents(); collectionState->addAppsAction(); qApp->sendPostedEvents(); qApp->processEvents(); QVERIFY(mockState->enteredValue()); machine->stop(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::renameAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; AddToHomeScreenMockState *mockState = new AddToHomeScreenMockState(machine.data()); HsMenuEventTransition transition( HsMenuEvent::RenameCollection, collectionState, mockState); collectionState->addTransition(&transition); machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); collectionState->renameAction(); qApp->sendPostedEvents(); QVERIFY(mockState->enteredValue()); machine->stop(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::deleteAppsAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; machine->setInitialState(collectionState); AddToHomeScreenMockState *mockState = new AddToHomeScreenMockState(machine.data()); HsMenuEventTransition transition( HsMenuEvent::DeleteCollection, collectionState, mockState); collectionState->addTransition(&transition); machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); collectionState->deleteAction(); qApp->sendPostedEvents(); QVERIFY(mockState->enteredValue()); machine->stop(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::updateLabel() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; const QString collectionName("testCollection" + QDateTime::currentDateTime().toString( "ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection( collectionName); HsCollectionState collectionState(builder, menuMode, mainWindow); collectionState.mModel = HsMenuService::getCollectionModel( collectionId ); collectionState.updateLabel(); const QString label = builder.currentViewLabel()->heading(); QString parentName = collectionState.mModel->root().data( CaItemModel::CollectionTitleRole).toString(); // cleanup HsMenuService::removeCollection(collectionId); QCOMPARE(label, parentName); } #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::addElementToHomeScreen() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsMenuItemModel *allAppsModel = HsMenuService::getAllApplicationsModel(); QVERIFY(allAppsModel->rowCount() >= 1); QModelIndex appIndex = allAppsModel->index(0, 0); const int appId = allAppsModel->data(appIndex, CaItemModel::IdRole).toInt(); QList<int> appIdList; appIdList << appId; HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; HsMenuService::addApplicationsToCollection(appIdList, collectionId); // create a state which is to be reached when add-to-home-screen // event is triggered AddToHomeScreenMockState *addToHomeScreenState = new AddToHomeScreenMockState(machine.data()); // create a transition to the new child state which will be triggered by // an event with specified operation type HsMenuEventTransition addToHomeScreenTransition( HsMenuEvent::AddToHomeScreen, collectionState, addToHomeScreenState); // prepare the state graph collectionState->addTransition(&addToHomeScreenTransition); machine->setInitialState(collectionState); machine->start(); qApp->processEvents(); const QModelIndex idx = collectionState->mModel->index(0); collectionState->addToHomeScreen(idx.data(CaItemModel::IdRole).toInt()); qApp->processEvents(); QVERIFY(addToHomeScreenState->enteredValue()); machine->stop(); // cleanup if (!appIdList.isEmpty()) { for (int i=0; i<appIdList.count(); i++) { HsMenuService::removeApplicationFromCollection(appIdList[i],collectionId); } } HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::addCollectionShortcutToHomeScreenAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); // we will start from collection view const QString collectionName("testCollection" + QDateTime::currentDateTime().toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; // create a state which is to be reached when add-to-home-screen // event is triggered AddToHomeScreenMockState *addToHomeScreenState = new AddToHomeScreenMockState(machine.data()); // create a transition to the new child state which will be triggered by // an event with specified operation type HsMenuEventTransition addToHomeScreenTransition( HsMenuEvent::AddToHomeScreen, collectionState, addToHomeScreenState); // prepare the state graph collectionState->addTransition(&addToHomeScreenTransition); machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); collectionState->addCollectionShortcutToHomeScreenAction(); qApp->sendPostedEvents(); QVERIFY(addToHomeScreenState->enteredValue()); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::latestOnTopMenuAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QState> parent(new QState); parent->setObjectName(tr("testName1")); const QString collectionName("testCollection" + QDateTime::currentDateTime().toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState( builder, menuMode, mainWindow, parent.data()); collectionState->mCollectionId = collectionId; collectionState->mSortAttribute = Hs::OldestOnTopHsSortAttribute; MockModel *collectionModel = new MockModel; collectionState->mModel = collectionModel; collectionState->mMenuView->setModel(collectionModel); qRegisterMetaType<Hs::HsSortAttribute>( "Hs::HsSortAttribute"); collectionState->mCollectionType = Hs::collectionDownloadedTypeName; collectionState->setMenuOptions(); QVERIFY(collectionModel->rowCount() > 1 ); QVERIFY(collectionState->mLatestOnTopMenuAction != 0); QVERIFY(collectionState->mOldestOnTopMenuAction != 0); collectionState->latestOnTopMenuAction(); QCOMPARE(collectionState->mSortAttribute, Hs::LatestOnTopHsSortAttribute); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::oldestOnTopMenuAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { // GUI objects set up HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QState> parent(new QState); parent->setObjectName(tr("testName1")); const QString collectionName("testCollection" + QDateTime::currentDateTime().toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, parent.data()); collectionState->mCollectionId = collectionId; collectionState->mSortAttribute = Hs::LatestOnTopHsSortAttribute; MockModel *collectionModel = new MockModel; collectionState->mModel = collectionModel; collectionState->mMenuView->setModel(collectionModel); qRegisterMetaType<Hs::HsSortAttribute>( "Hs::HsSortAttribute"); collectionState->mCollectionType = Hs::collectionDownloadedTypeName; collectionState->setMenuOptions(); QVERIFY(collectionModel->rowCount() > 1 ); QVERIFY(collectionState->mLatestOnTopMenuAction != 0); QVERIFY(collectionState->mOldestOnTopMenuAction != 0); collectionState->oldestOnTopMenuAction(); QCOMPARE(collectionState->mSortAttribute, Hs::OldestOnTopHsSortAttribute); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::createArrangeCollection() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QStateMachine *machine = new QStateMachine(0); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine); collectionState->mCollectionId = collectionId; machine->setInitialState(collectionState); AddToHomeScreenMockState *mockState = new AddToHomeScreenMockState(machine); // create a transition to the new child state which will be triggered by // an event with specified operation type HsMenuEventTransition *transition = new HsMenuEventTransition( HsMenuEvent::ArrangeCollection, collectionState, mockState); collectionState->addTransition(transition); machine->start(); qApp->sendPostedEvents(); collectionState->createArrangeCollection(); qApp->sendPostedEvents(); QVERIFY(mockState->enteredValue()); qApp->removePostedEvents(0); machine->stop(); delete machine; } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // #ifdef Q_OS_SYMBIAN void MenuStatesTest::openTaskSwitcher() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); QVERIFY(collectionState->openTaskSwitcher()); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } #endif//Q_OS_SYMBIAN // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- // void MenuStatesTest::disableSearchAction() { #ifdef Q_OS_SYMBIAN User::ResetInactivityTime();//it should help for Viewserver11 panic #ifdef UT_MEMORY_CHECK __UHEAP_MARK; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN { HsMenuViewBuilder builder; HsMenuModeWrapper menuMode; HsMainWindowMock mainWindow; QScopedPointer<QStateMachine> machine(new QStateMachine(0)); const QString collectionName("testCollection" + QDateTime::currentDateTime(). toString("ddmmyyyy_hh_mm_ss_zzz")); const int collectionId = HsMenuService::createCollection(collectionName); HsCollectionState *collectionState = new HsCollectionState(builder, menuMode, mainWindow, machine.data()); collectionState->mCollectionId = collectionId; machine->setInitialState(collectionState); machine->start(); qApp->sendPostedEvents(); collectionState->stateEntered(); collectionState->mMenuView->disableSearch(true); QVERIFY(!collectionState->mMenuView->mBuilder.searchAction()->isEnabled()); collectionState->mMenuView->disableSearch(false); QVERIFY(collectionState->mMenuView->mBuilder.searchAction()->isEnabled()); collectionState->lockSearchButton(true); QVERIFY(!collectionState->mMenuView->mBuilder.searchAction()->isEnabled()); collectionState->lockSearchButton(false); QVERIFY(collectionState->mMenuView->mBuilder.searchAction()->isEnabled()); collectionState->stateExited(); machine->stop(); // cleanup HsMenuService::removeCollection(collectionId); } #ifdef Q_OS_SYMBIAN #ifdef UT_MEMORY_CHECK __UHEAP_MARKEND; #endif//UT_MEMORY_CHECK #endif//Q_OS_SYMBIAN } QTEST_MAIN(MenuStatesTest)
[ "none@none" ]
none@none
4b576ced1f7246c6ce2ec40378005ac751825ae9
55562b54d397407c7561c2385b1319399633448e
/src/sgetrf2_msub.cpp
5643e8245865daa6be89796667a3e94d57fc880a
[]
no_license
kjbartel/clmagma
0183fa30d7a0e27c53bfd8aa4b8dca64895ccaa4
86a58e5d4f28af7942e31d742c3104598d41d796
refs/heads/master
2020-05-26T22:07:09.530467
2015-07-05T11:26:42
2015-07-05T11:26:42
38,567,931
2
4
null
null
null
null
UTF-8
C++
false
false
17,838
cpp
/* -- clMAGMA (version 1.3.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @generated from zgetrf2_msub.cpp normal z -> s, Sat Nov 15 00:21:37 2014 */ #include <math.h> #include "common_magma.h" extern "C" magma_int_t magma_sgetrf2_msub( magma_int_t num_subs, magma_int_t ngpu, magma_int_t m, magma_int_t n, magma_int_t nb, magma_int_t offset, magmaFloat_ptr *d_lAT, size_t dlAT_offset, magma_int_t lddat, magma_int_t *ipiv, magmaFloat_ptr *d_panel, magmaFloat_ptr *d_lAP, size_t dlAP_offset, float *w, magma_int_t ldw, magma_queue_t *queues, magma_int_t *info) { /* -- clMAGMA (version 1.3.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 Purpose ======= SGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. Use two buffer to send panels.. Arguments ========= NUM_GPUS (input) INTEGER The number of GPUS to be used for the factorization. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array on the GPU, dimension (LDDA,N). On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDDA (input) INTEGER The leading dimension of the array A. LDDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value or another error occured, such as memory allocation failed. > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== */ #define d_lAT(id,i,j) d_lAT[(id)], (((offset)+(i)*nb)*lddat + (j)*nb) #define d_lAT_offset(i, j) (((offset)+(i)*nb)*lddat + (j)*nb) #define W(j) (w +((j)%(1+ngpu))*nb*ldw) float c_one = MAGMA_S_ONE; float c_neg_one = MAGMA_S_NEG_ONE; magma_int_t tot_subs = num_subs * ngpu; magma_int_t block_size = 32; magma_int_t iinfo, maxm, mindim; magma_int_t i, j, d, dd, rows, cols, s; magma_int_t id, j_local, j_local2, nb0, nb1; /* local submatrix info */ magma_int_t ldpan[MagmaMaxSubs * MagmaMaxGPUs], n_local[MagmaMaxSubs * MagmaMaxGPUs]; size_t dpanel_local_offset[MagmaMaxSubs * MagmaMaxGPUs]; magmaFloat_ptr dpanel_local[MagmaMaxSubs * MagmaMaxGPUs]; /* Check arguments */ *info = 0; if (m < 0) *info = -2; else if (n < 0) *info = -3; else if (tot_subs*lddat < max(1,n)) *info = -5; if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } /* Quick return if possible */ if (m == 0 || n == 0) return *info; /* Function Body */ mindim = min(m, n); if (tot_subs > ceil((float)n/nb)) { *info = -1; return *info; } else { /* Use hybrid blocked code. */ maxm = ((m + block_size-1)/block_size)*block_size; /* some initializations */ for (i=0; i < tot_subs; i++) { n_local[i] = ((n/nb)/tot_subs)*nb; if (i < (n/nb)%tot_subs) n_local[i] += nb; else if (i == (n/nb)%tot_subs) n_local[i] += n%nb; } /* start sending the first panel to cpu */ nb0 = min(mindim, nb); magmablas_stranspose( nb0, maxm, d_lAT(0,0,0), lddat, d_lAP[0], dlAP_offset, maxm, queues[2*0+1] ); magma_sgetmatrix_async( m, nb0, d_lAP[0], dlAP_offset, maxm, W(0), ldw, queues[2*0+1], NULL ); clFlush(queues[2*0+1]); /* ------------------------------------------------------------------------------------- */ s = mindim / nb; for (j=0; j < s; j++) { /* Set the submatrix ID that holds the current panel */ id = j%tot_subs; /* Set the local index where the current panel is */ j_local = j/tot_subs; // cols for gpu panel cols = maxm - j*nb; // rows for cpu panel rows = m - j*nb; /* synchrnoize j-th panel from id-th gpu into work */ magma_queue_sync( queues[2*(id%ngpu)+1] ); /* j-th panel factorization */ lapackf77_sgetrf( &rows, &nb, W(j), &ldw, ipiv+j*nb, &iinfo); if ((*info == 0) && (iinfo > 0)) { *info = iinfo + j*nb; //break; } /* start sending the panel to all the gpus */ d = (j+1)%ngpu; for (dd=0; dd < ngpu; dd++) { magma_ssetmatrix_async( rows, nb, W(j), ldw, d_lAP[d], dlAP_offset+(j%(2+ngpu))*nb*maxm, maxm, queues[2*d+1], NULL ); d = (d+1)%ngpu; } /* apply the pivoting */ for( i=j*nb; i < j*nb + nb; ++i ) { ipiv[i] += j*nb; } d = (j+1)%tot_subs; for (dd=0; dd < tot_subs; dd++) { magmablas_slaswp( lddat, d_lAT(d,0,0), lddat, j*nb + 1, j*nb + nb, ipiv, 1, queues[2*(d%ngpu)] ); d = (d+1)%tot_subs; } /* update the trailing-matrix/look-ahead */ d = (j+1)%tot_subs; for (dd=0; dd < tot_subs; dd++) { /* storage for panel */ if (d%ngpu == id%ngpu) { /* the panel belond to this gpu */ dpanel_local[d] = d_lAT[id]; dpanel_local_offset[d] = d_lAT_offset(j, j_local); ldpan[d] = lddat; /* next column */ j_local2 = j_local; if ( d <= id ) j_local2++; } else { /* the panel belong to another gpu */ dpanel_local[d] = d_panel[d%ngpu]; dpanel_local_offset[d] = (j%(2+ngpu))*nb*maxm; ldpan[d] = nb; /* next column */ j_local2 = j_local; if ( d < id ) j_local2++; } /* the size of the next column */ if (s > (j+1)) { nb0 = nb; } else { nb0 = n_local[d]-nb*(s/tot_subs); if (d < s%tot_subs) nb0 -= nb; } if (d == (j+1)%tot_subs) { /* owns the next column, look-ahead the column */ nb1 = nb0; } else { /* update the entire trailing matrix */ nb1 = n_local[d] - j_local2*nb; } /* gpu updating the trailing matrix */ if (d == (j+1)%tot_subs) { /* look-ahead, this is executed first (j.e., dd=0) */ magma_queue_sync(queues[2*(d%ngpu)]); /* pivoting done? (overwrite with panel) */ magmablas_stranspose( cols, nb, d_lAP[d%ngpu], dlAP_offset+(j%(2+ngpu))*nb*maxm, maxm, dpanel_local[d], dpanel_local_offset[d], ldpan[d], queues[2*(d%ngpu)+1] ); magma_queue_sync(queues[2*(d%ngpu)+1]); /* panel arrived and transposed for remaining update ? */ magma_strsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, nb1, nb, c_one, dpanel_local[d], dpanel_local_offset[d], ldpan[d], d_lAT(d, j, j_local2), lddat, queues[2*(d%ngpu)+1]); magma_sgemm( MagmaNoTrans, MagmaNoTrans, nb1, m-(j+1)*nb, nb, c_neg_one, d_lAT(d, j, j_local2), lddat, dpanel_local[d], dpanel_local_offset[d]+nb*ldpan[d], ldpan[d], c_one, d_lAT(d, j+1, j_local2), lddat, queues[2*(d%ngpu)+1]); } else { /* no look-ahead */ if (dd < ngpu) { /* synch and transpose only the first time */ magma_queue_sync(queues[2*(d%ngpu)+1]); /* panel arrived? */ magmablas_stranspose( cols, nb, d_lAP[d%ngpu], dlAP_offset+(j%(2+ngpu))*nb*maxm, maxm, dpanel_local[d], dpanel_local_offset[d], ldpan[d], queues[2*(d%ngpu)] ); } magma_strsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, nb1, nb, c_one, dpanel_local[d], dpanel_local_offset[d], ldpan[d], d_lAT(d, j, j_local2), lddat, queues[2*(d%ngpu)]); magma_sgemm( MagmaNoTrans, MagmaNoTrans, nb1, m-(j+1)*nb, nb, c_neg_one, d_lAT(d, j, j_local2), lddat, dpanel_local[d], dpanel_local_offset[d]+nb*ldpan[d], ldpan[d], c_one, d_lAT(d, j+1, j_local2), lddat, queues[2*(d%ngpu)]); } if (d == (j+1)%tot_subs) { /* Set the local index where the current panel is */ int loff = j+1; int j_local = (j+1)/tot_subs; int ldda = maxm - (j+1)*nb; int cols = m - (j+1)*nb; nb0 = min(nb, mindim - (j+1)*nb); /* size of the diagonal block */ if (nb0 > 0) { /* transpose the panel for sending it to cpu */ magmablas_stranspose( nb0, ldda, d_lAT(d,loff,j_local), lddat, d_lAP[d%ngpu], dlAP_offset + ((j+1)%(2+ngpu))*nb*maxm, ldda, queues[2*(d%ngpu)+1] ); /* send the panel to cpu */ magma_sgetmatrix_async( cols, nb0, d_lAP[d%ngpu], dlAP_offset + ((j+1)%(2+ngpu))*nb*maxm, ldda, W(j+1), ldw, queues[2*(d%ngpu)+1], NULL ); } } else { //trace_gpu_end( d, 0 ); } d = (d+1)%tot_subs; } /* update the remaining matrix by gpu owning the next panel */ if ((j+1) < s) { d = (j+1)%tot_subs; int j_local = (j+1)/tot_subs; int rows = m - (j+1)*nb; magma_strsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, n_local[d] - (j_local+1)*nb, nb, c_one, dpanel_local[d], dpanel_local_offset[d], ldpan[d], d_lAT(d,j,j_local+1), lddat, queues[2*(d%ngpu)] ); magma_sgemm( MagmaNoTrans, MagmaNoTrans, n_local[d]-(j_local+1)*nb, rows, nb, c_neg_one, d_lAT(d,j,j_local+1), lddat, dpanel_local[d], dpanel_local_offset[d]+nb*ldpan[d], ldpan[d], c_one, d_lAT(d,j+1, j_local+1), lddat, queues[2*(d%ngpu)] ); } } /* end of for j=1..s */ /* ------------------------------------------------------------------------------ */ /* Set the GPU number that holds the last panel */ id = s%tot_subs; /* Set the local index where the last panel is */ j_local = s/tot_subs; /* size of the last diagonal-block */ nb0 = min(m - s*nb, n - s*nb); rows = m - s*nb; cols = maxm - s*nb; if (nb0 > 0) { /* wait for the last panel on cpu */ magma_queue_sync( queues[2*(id%ngpu)+1] ); /* factor on cpu */ lapackf77_sgetrf( &rows, &nb0, W(s), &ldw, ipiv+s*nb, &iinfo ); if ( (*info == 0) && (iinfo > 0) ) *info = iinfo + s*nb; /* send the factor to gpus */ for (d=0; d < ngpu; d++) { magma_ssetmatrix_async( rows, nb0, W(s), ldw, d_lAP[d], dlAP_offset+(s%(2+ngpu))*nb*maxm, cols, queues[2*d+1], NULL ); } for( i=s*nb; i < s*nb + nb0; ++i ) { ipiv[i] += s*nb; } for (d=0; d < tot_subs; d++) { magmablas_slaswp( lddat, d_lAT(d,0,0), lddat, s*nb + 1, s*nb + nb0, ipiv, 1, queues[2*(d%ngpu)] ); } d = id; for (dd=0; dd < tot_subs; dd++) { /* wait for the pivoting to be done */ if (dd < ngpu) { /* synch only the first time */ magma_queue_sync( queues[2*(d%ngpu)] ); } j_local2 = j_local; if (d%ngpu == id%ngpu) { /* the panel belond to this gpu */ dpanel_local[d] = d_lAT[id]; dpanel_local_offset[d] = d_lAT_offset(s, j_local); if (dd < ngpu) { magmablas_stranspose( rows, nb0, d_lAP[d%ngpu], dlAP_offset+(s%(2+ngpu))*nb*maxm, cols, dpanel_local[d], dpanel_local_offset[d], lddat, queues[2*(d%ngpu)+1] ); } /* size of the "extra" block */ if (d == id) { /* the last diagonal block belongs to this submatrix */ nb1 = nb0; } else if (d < id) { nb1 = nb; } else { nb1 = 0; } if (n_local[d] > j_local*nb+nb1) { magma_strsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, n_local[d] - (j_local*nb+nb1), nb0, c_one, dpanel_local[d], dpanel_local_offset[d], lddat, d_lAT(d, s, j_local)+nb1, lddat, queues[2*(d%ngpu)+1]); } } else if (n_local[d] > j_local2*nb) { /* the panel belong to another gpu */ dpanel_local[d] = d_panel[d%ngpu]; dpanel_local_offset[d] = (s%(2+ngpu))*nb*maxm; /* next column */ if (d < ngpu) { /* transpose only the first time */ magmablas_stranspose( rows, nb0, d_lAP[d%ngpu], dlAP_offset+(s%(2+ngpu))*nb*maxm, cols, dpanel_local[d], dpanel_local_offset[d], nb, queues[2*(d%ngpu)+1] ); } if (d < id) j_local2++; nb1 = n_local[d] - j_local2*nb; magma_strsm( MagmaRight, MagmaUpper, MagmaNoTrans, MagmaUnit, nb1, nb0, c_one, dpanel_local[d], dpanel_local_offset[d], nb, d_lAT(d,s,j_local2), lddat, queues[2*(d%ngpu)+1]); } d = (d+1)%tot_subs; } } /* if( nb0 > 0 ) */ /* clean up */ for (d=0; d < ngpu; d++) { magma_queue_sync( queues[2*d] ); magma_queue_sync( queues[2*d+1] ); } } return *info; /* End of MAGMA_SGETRF2_MSUB */ } #undef d_lAT
[ "kjbartel@users.noreply.github.com" ]
kjbartel@users.noreply.github.com
34e8896ead7b0b6dab3e160934270c3e5b84bfa2
1deccd9718fe2dc701e77498fbcbf746c262150a
/src/morganaDofs/stateVector.cpp
526d3d56e842bfb064bcbec393fd2ebe839bda73
[]
no_license
lacrymose/morganaPublic
ce577067102ba626f136c1b5ca4b8181a6f38a71
6422b8d0c6c201fd5a4dfeef81db3c1b214f6ace
refs/heads/master
2022-11-16T01:27:14.401469
2020-07-14T14:54:14
2020-07-14T14:54:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,541
cpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This file is part of Morgana. Author: Andrea Villa, andrea.villa81@fastwebnet.it Morgana is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Morgana is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Morgana. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "stateVector.h" //_________________________________________________________________________________________________ // CONSTRUCTORS //------------------------------------------------------------------------------------------------- stateVector:: stateVector(const UInt & N) : Epetra_SerialDenseVector(N) { } stateVector:: stateVector(Real *Comp, const UInt & N) : Epetra_SerialDenseVector(Copy,Comp,N) { } stateVector:: stateVector(const stateVector &C) : Epetra_SerialDenseVector(C) { } //_________________________________________________________________________________________________ // OPERATORS //------------------------------------------------------------------------------------------------- void stateVector:: operator+=(const stateVector &C) { if(C.Length() != this->Length()) { this->Resize(C.Length()); } for(int i=1; i <= this->Length(); ++i) { this->operator()(i) += C(i); } } void stateVector:: operator-=(const stateVector & C) { if(C.Length() != this->Length()) { this->Resize(C.Length()); } for(int i=1; i <= this->Length(); ++i) { this->operator()(i) -= C(i); } } void stateVector:: operator*=(const Real &a) { for(int i=1; i <= this->Length(); ++i) { this->operator()(i) *= a; } } void stateVector:: operator/=(const Real &a) { for(int i=1; i <= this->Length(); ++i) { this->operator()(i) /= a; } } Real stateVector:: operator*(const stateVector &C) const { assert(C.Length() == this->Length()); Real tot=0.0; for(int i=1; i<=this->Length(); ++i) { tot += this->operator()(i) * C(i); } return(tot); } //_________________________________________________________________________________________________ // INTERNAL FUNCTIONS //------------------------------------------------------------------------------------------------- Real stateVector:: sum() const { Real tot = 0.0; for(int i=1; i<=this->Length(); ++i) { tot += this->operator()(i); } return(tot); } Real stateVector:: norm1() const { Real tot = 0.0; for(int i=1; i<=this->Length(); ++i) { tot += abs(this->operator()(i)); } return(tot); } void stateVector:: cancel() { for(int i=1; i <= this->Length(); ++i) { this->operator()(i) = 0.0; } } UInt stateVector:: size() const { return(UInt(this->Length())); } //_________________________________________________________________________________________________ // ORDINAL FUNCTIONS //------------------------------------------------------------------------------------------------- bool stateVector:: operator<(const stateVector & V) const { assert(V.Length() == this->Length()); for(int i=1; i <= V.Length(); ++i) { if( this->operator()(i) < (V.operator()(i) - geoToll) ) { return(true); } if( this->operator()(i) > (V.operator()(i) - geoToll) ) { return(false); } } return(false); } bool stateVector:: operator!=(const stateVector & V) const { assert(V.Length() == this->Length()); for(int i=1; i <= V.Length(); ++i) { if( ( this->operator()(i) > (V.operator()(i) + geoToll) ) || ( this->operator()(i) < (V.operator()(i) - geoToll) ) ) { return(true); } } return(false); } //_________________________________________________________________________________________________ // OTHER FUNCTIONS //------------------------------------------------------------------------------------------------- ostream & operator<<( ostream & f, const stateVector & A) { for(int i=1; i <= A.Length(); ++i) { f << A(i) << " "; } f << endl; return(f); }
[ "andrea.villa81@fastwebnet.it" ]
andrea.villa81@fastwebnet.it
919bae465cdb06d69b4a31dd09f4bd4377264b02
4922586d83199b43c4039ab008d59aed420dee02
/bindings/cpp/bindings.cpp
82cef3b7539ca10f92cbd089f7e2f1d11ba141ce
[ "MIT" ]
permissive
Chandler/wykobi_js
14208db043795c08d6f4d33e5e4dfadc976fd052
1c13c7aba7c7a10cc1588069b42862ff78555bea
refs/heads/master
2021-01-25T13:57:21.895830
2018-03-03T00:10:28
2018-03-03T00:10:28
123,625,080
2
0
null
null
null
null
UTF-8
C++
false
false
2,465
cpp
/* (***********************************************************************) (* *) (* Wykobi Computational Geometry Library *) (* Release Version 0.0.5 *) (* http://www.wykobi.com *) (* Copyright (c) 2005-2017 Arash Partow, All Rights Reserved. *) (* *) (* The Wykobi computational geometry library and its components are *) (* supplied under the terms of the General Wykobi License agreement. *) (* The contents of the Wykobi computational geometry library and its *) (* components may not be copied or disclosed except in accordance with *) (* the terms of that agreement. *) (* *) (* URL: https://opensource.org/licenses/MIT *) (* *) (***********************************************************************) */ #include <iostream> #include <vector> #include "wykobi.hpp" #include "wykobi_utilities.hpp" #include <emscripten/emscripten.h> #include <numeric> #include <string> #ifdef __cplusplus extern "C" { #endif /* Javascript bindings for some wykobi C++ methods */ const char* EMSCRIPTEN_KEEPALIVE segmentTriangleIntersect( double segmentx1, double segmenty1, double segmentx2, double segmenty2, double triAx, double triAy, double triBx, double triBy, double triCx, double triCy){ typedef double T; wykobi::segment<T,2> segment = wykobi::make_segment(segmentx1,segmenty1,segmentx2,segmenty2); wykobi::triangle <T,2> triangle = wykobi::make_triangle(triAx,triAy,triBx,triBy,triCx,triCy); std::vector<std::string> clipped_segment_list; wykobi::segment<T,2> clipped_segment; if (wykobi::clip(segment, triangle, clipped_segment)){ for (std::size_t i = 0; i < clipped_segment.size(); i++){ clipped_segment_list.push_back(std::to_string(clipped_segment[i].x)); clipped_segment_list.push_back(std::to_string(clipped_segment[i].y)); } } std::string s; for (const auto &piece : clipped_segment_list){ s += piece; s += ","; } return s.c_str(); } #ifdef __cplusplus } #endif
[ "chandler@planet.com" ]
chandler@planet.com
84a5c573e18b841fb4005a801e107e2caa851b59
ece46d54db148fcd1717ae33e9c277e156067155
/SDK/arxsdk2006/samples/editor/mfcsamps/modal/stdafx.cpp
1a9acb8da6884f8fc5f907c8e48346fd93040db8
[]
no_license
15831944/ObjectArx
ffb3675875681b1478930aeac596cff6f4187ffd
8c15611148264593730ff5b6213214cebd647d23
refs/heads/main
2023-06-16T07:36:01.588122
2021-07-09T10:17:27
2021-07-09T10:17:27
384,473,453
0
1
null
2021-07-09T15:08:56
2021-07-09T15:08:56
null
UTF-8
C++
false
false
243
cpp
// stdafx.cpp : source file that includes just the standard includes // (C) Copyright 1998 by Autodesk, Inc. // MFCTemplate.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "zhangsensen@zwcad.com" ]
zhangsensen@zwcad.com
4f14ddc9a4ff8056c004bfcfd0e1d1aca9e32d99
35b929181f587c81ad507c24103d172d004ee911
/SrcLib/patch/fwMDSemanticPatch/src/fwMDSemanticPatch/V1/V2/fwData/Composite.cpp
3ca1829db6cc12c1ed9d4230b1da9dac0ff40e09
[]
no_license
hamalawy/fw4spl
7853aa46ed5f96660123e88d2ba8b0465bd3f58d
680376662bf3fad54b9616d1e9d4c043d9d990df
refs/heads/master
2021-01-10T11:33:53.571504
2015-07-23T08:01:59
2015-07-23T08:01:59
50,699,438
2
1
null
null
null
null
UTF-8
C++
false
false
15,218
cpp
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2009-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #include <string> #include <vector> #include <boost/foreach.hpp> #include <boost/algorithm/string.hpp> #include <fwTools/UUID.hpp> #include <fwAtoms/Object.hpp> #include <fwAtoms/Object.hxx> #include <fwAtoms/Numeric.hpp> #include <fwAtoms/String.hpp> #include <fwAtoms/Boolean.hpp> #include <fwAtoms/Blob.hpp> #include <fwAtoms/Sequence.hpp> #include <fwAtoms/Map.hpp> #include <fwAtomsPatch/StructuralCreatorDB.hpp> #include <fwAtomsPatch/helper/functions.hpp> #include <fwMedData/ActivitySeries.hpp> #include <fwMemory/BufferObject.hpp> #include "fwMDSemanticPatch/V1/V2/fwData/Composite.hpp" namespace fwMDSemanticPatch { namespace V1 { namespace V2 { namespace fwData { typedef std::map< ::fwAtoms::Object::sptr, ::fwAtoms::Object::sptr > Image2ModelType; Composite::Composite() : ::fwAtomsPatch::ISemanticPatch() { m_originClassname = "::fwData::Composite"; m_originVersion = "1"; this->addContext("MedicalData", "V1", "V2"); } // ---------------------------------------------------------------------------- Composite::~Composite() { } // ---------------------------------------------------------------------------- Composite::Composite( const Composite &cpy ) : ::fwAtomsPatch::ISemanticPatch(cpy) { } // ---------------------------------------------------------------------------- void processPlanning( const ::fwAtoms::Map::sptr& oldCompositeMap, const ::fwAtoms::Sequence::sptr& series, const Image2ModelType& image2Model, ::fwAtomsPatch::IPatch::NewVersionsType& newVersions) { ::fwAtoms::Object::sptr oldPlanningDB = ::fwAtoms::Object::dynamicCast( (*oldCompositeMap)["planningDB"] ); ::fwAtoms::Map::sptr oldPlannings = oldPlanningDB->getAttribute< ::fwAtoms::Map >("values"); BOOST_FOREACH( ::fwAtoms::Map::value_type oldPlanningAtom, oldPlannings->getValue() ) { ::fwAtoms::Map::sptr oldPlanning = ::fwAtoms::Object::dynamicCast(oldPlanningAtom.second)->getAttribute< ::fwAtoms::Map >("values"); SLM_ASSERT("Didn't find 'acquisition' in planning", oldPlanning->getValue().find("acquisition") != oldPlanning->getValue().end()); ::fwAtoms::Base::sptr acquisition = oldPlanning->getValue().find("acquisition")->second; ::fwAtoms::Object::sptr acqObj = ::fwAtoms::Object::dynamicCast(acquisition); SLM_ASSERT("Failed to cast acquisition to object", acqObj); Image2ModelType::const_iterator it = image2Model.find(newVersions[acqObj]); SLM_ASSERT("Didn't find image series related to acquisition", it != image2Model.end()); ::fwAtoms::Object::sptr imageSeries = it->first; ::fwAtoms::Object::sptr resectionDB = ::fwAtoms::Object::dynamicCast(oldPlanning->getValue().find("resectionDB")->second); // Retrieves expert who performed the resection ::fwAtoms::Object::sptr expert = ::fwAtoms::Object::dynamicCast(oldPlanning->getValue().find("expert")->second); ::fwAtoms::Sequence::sptr experts = ::fwAtoms::Sequence::New(); experts->push_back( ::fwAtoms::String::dynamicCast(expert->getAttribute< ::fwAtoms::String >("value"))); // Retrieves resection information ::fwAtoms::Object::sptr information = ::fwAtoms::Object::dynamicCast(oldPlanning->getValue().find("information")->second); ::fwAtoms::String::sptr informationStr = ::fwAtoms::String::dynamicCast(information->getAttribute< ::fwAtoms::String >("value")); // Retrieves resection date and time ::fwAtoms::Object::sptr dateTimeObj = ::fwAtoms::Object::dynamicCast(oldPlanning->getValue().find("startDateTime")->second); ::fwAtoms::String::sptr dateTimeStr = ::fwAtoms::String::dynamicCast(dateTimeObj->getAttribute< ::fwAtoms::String >("value")); ::fwAtoms::String::sptr time = ::fwAtoms::String::New(""); ::fwAtoms::String::sptr date = ::fwAtoms::String::New(""); std::string dateTimeStd = dateTimeStr->getString(); std::vector< std::string > strs; ::boost::split(strs, dateTimeStd, ::boost::is_any_of(" ")); if(strs.size() >= 2) { date->setValue(strs[0]); time->setValue(strs[1]); } ::fwAtomsPatch::StructuralCreatorDB::sptr creators = ::fwAtomsPatch::StructuralCreatorDB::getDefault(); ::fwAtoms::Object::sptr newActivitySeries = creators->create( "::fwMedData::ActivitySeries", "1"); ::fwAtoms::Object::sptr imgComposite = ::fwAtoms::Object::New(); ::fwAtomsPatch::helper::setClassname(imgComposite, "::fwData::Composite"); ::fwAtomsPatch::helper::setVersion(imgComposite, "1"); ::fwAtomsPatch::helper::generateID(imgComposite); ::fwAtomsPatch::helper::cleanFields(imgComposite); ::fwAtomsPatch::helper::Object imgCompositeHelper(imgComposite); ::fwAtoms::Map::sptr compositeMap = ::fwAtoms::Map::New(); compositeMap->insert("OptionalInputImageKey", imageSeries->getAttribute< ::fwAtoms::Object >("image")); imgCompositeHelper.addAttribute("values", compositeMap); ::fwAtoms::Map::sptr activityDataMap = ::fwAtoms::Map::New(); activityDataMap->insert("resectionDB", resectionDB); activityDataMap->insert("modelSeries", it->second); activityDataMap->insert("imageSeries", imgComposite); ::fwAtoms::Object::sptr mapObj = ::fwAtoms::Object::New(); ::fwAtomsPatch::helper::setClassname(mapObj, "::fwData::Composite"); ::fwAtomsPatch::helper::setVersion(mapObj, "1"); ::fwAtomsPatch::helper::generateID(mapObj); ::fwAtomsPatch::helper::cleanFields(mapObj); ::fwAtomsPatch::helper::Object mapObjHelper(mapObj); mapObjHelper.addAttribute("values", activityDataMap); ::fwAtomsPatch::helper::Object helperActivity(newActivitySeries); helperActivity.replaceAttribute("activity_config_id", ::fwAtoms::String::New("Resection")); helperActivity.replaceAttribute("data", mapObj); helperActivity.replaceAttribute("modality", ::fwAtoms::String::New("OT") ); helperActivity.replaceAttribute("instance_uid", ::fwAtoms::String::New(::fwTools::UUID::generateUUID())); helperActivity.replaceAttribute("date", date); helperActivity.replaceAttribute("time", time); helperActivity.replaceAttribute("performing_physicians_name", experts); helperActivity.replaceAttribute("description" , informationStr); helperActivity.replaceAttribute("patient", imageSeries->getAttribute< ::fwAtoms::Object >("patient")); helperActivity.replaceAttribute("study", imageSeries->getAttribute< ::fwAtoms::Object >("study")); helperActivity.replaceAttribute("equipment", imageSeries->getAttribute< ::fwAtoms::Object >("equipment")); series->push_back(newActivitySeries); } } // ---------------------------------------------------------------------------- void Composite::apply( const ::fwAtoms::Object::sptr& previous, const ::fwAtoms::Object::sptr& current, ::fwAtomsPatch::IPatch::NewVersionsType& newVersions) { Image2ModelType image2Model; ISemanticPatch::apply(previous, current, newVersions); // Create helper ::fwAtomsPatch::helper::Object helper(current); // If fwData::Composite is a MedicalWorkspace if ( previous->getMetaInfo("compositeType") == "MedicalWorkspace" ) { // Update type/version ::fwAtomsPatch::helper::setClassname( current, "::fwMedData::SeriesDB" ); ::fwAtomsPatch::helper::setVersion( current, "1" ); // Update Attributes ::fwAtomsPatch::helper::cleanFields( current ); // Replace fwAtoms::Map by fwAtoms::Sequence ( have the same key ) ::fwAtoms::Sequence::sptr series = ::fwAtoms::Sequence::New(); helper.replaceAttribute( "values", series ); // Add ImageSeries and create ModelSeries if they are necessary ::fwAtoms::Map::sptr oldCompositeMap = previous->getAttribute< ::fwAtoms::Map >("values"); ::fwAtoms::Object::sptr oldPatientDB = ::fwAtoms::Object::dynamicCast( (*oldCompositeMap)["patientDB"] ); ::fwAtoms::Sequence::sptr oldPatients = oldPatientDB->getAttribute< ::fwAtoms::Sequence >("patients"); ::fwAtomsPatch::StructuralCreatorDB::sptr creators = ::fwAtomsPatch::StructuralCreatorDB::getDefault(); BOOST_FOREACH( ::fwAtoms::Base::sptr oldPatientAtom, oldPatients->getValue() ) { ::fwAtoms::Object::sptr oldPatient = ::fwAtoms::Object::dynamicCast( oldPatientAtom ); ::fwAtoms::Object::sptr newPatient = newVersions[oldPatient]; ::fwAtoms::Sequence::sptr oldStudies = oldPatient->getAttribute< ::fwAtoms::Sequence >("studies"); BOOST_FOREACH( ::fwAtoms::Base::sptr oldStudyAtom, oldStudies->getValue() ) { ::fwAtoms::Object::sptr oldStudy = ::fwAtoms::Object::dynamicCast( oldStudyAtom ); ::fwAtoms::Object::sptr newStudy = newVersions[oldStudy]; ::fwAtoms::Sequence::sptr oldAcquisitions = oldStudy->getAttribute< ::fwAtoms::Sequence >("acquisitions"); BOOST_FOREACH( ::fwAtoms::Base::sptr oldAcqAtom, oldAcquisitions->getValue() ) { ::fwAtoms::Object::sptr oldAcq = ::fwAtoms::Object::dynamicCast( oldAcqAtom ); // finalize and push newImgSeries ::fwAtoms::Object::sptr newImgSeries = newVersions[oldAcq]; ::fwAtomsPatch::helper::Object imgSeriesHelper (newImgSeries); ::fwAtoms::Object::sptr clonedPatient = ::fwAtoms::Object::dynamicCast(newPatient->clone()); ::fwAtomsPatch::helper::changeUID(clonedPatient); imgSeriesHelper.replaceAttribute("patient", clonedPatient ); ::fwAtoms::Object::sptr clonedStudy = ::fwAtoms::Object::dynamicCast(newStudy->clone()); ::fwAtomsPatch::helper::changeUID(clonedStudy); imgSeriesHelper.replaceAttribute("study", clonedStudy ); imgSeriesHelper.replaceAttribute("modality", oldStudy->getAttribute("modality")->clone() ); ::fwAtoms::String::sptr institution; institution = ::fwAtoms::String::dynamicCast( oldStudy->getAttribute("hospital")->clone() ); ::fwAtoms::Object::sptr equipment = newImgSeries->getAttribute< ::fwAtoms::Object >("equipment"); ::fwAtomsPatch::helper::Object equipmentHelper(equipment); equipmentHelper.replaceAttribute("institution_name", institution); // Set study date and time if necessary ::fwAtoms::String::sptr studyDate = newStudy->getAttribute< ::fwAtoms::String >("date"); ::fwAtomsPatch::helper::Object studyHelper(clonedStudy); if ( studyDate->getValue().empty() ) { studyHelper.replaceAttribute("date", newImgSeries->getAttribute("date")->clone()); } ::fwAtoms::String::sptr studyTime = newStudy->getAttribute< ::fwAtoms::String >("time"); if ( studyTime->getValue().empty() ) { studyHelper.replaceAttribute("time", newImgSeries->getAttribute("time")->clone()); } series->push_back( newImgSeries ); // finalize and push newModelSeries ::fwAtoms::Sequence::sptr oldReconstructions = oldAcq->getAttribute< ::fwAtoms::Sequence >("reconstructions"); if ( oldReconstructions->size() > 0 ) { // Create new model series ::fwAtoms::Object::sptr newModelSeries = creators->create( "::fwMedData::ModelSeries", "1"); ::fwAtomsPatch::helper::Object msHelper (newModelSeries); ::fwAtoms::Object::sptr msPatient = ::fwAtoms::Object::dynamicCast(clonedPatient->clone()); ::fwAtomsPatch::helper::changeUID(msPatient); msHelper.replaceAttribute("patient", msPatient ); ::fwAtoms::Object::sptr msStudy = ::fwAtoms::Object::dynamicCast(clonedStudy->clone()); ::fwAtomsPatch::helper::changeUID(msStudy); msHelper.replaceAttribute("study", msStudy ); ::fwAtoms::Object::sptr msEquipment = ::fwAtoms::Object::dynamicCast(equipment->clone()); ::fwAtomsPatch::helper::changeUID(msEquipment); msHelper.replaceAttribute("equipment", msEquipment ); msHelper.replaceAttribute("modality", ::fwAtoms::String::New("OT") ); msHelper.replaceAttribute("instance_uid" , ::fwAtoms::String::New(::fwTools::UUID::generateUUID()) ); msHelper.replaceAttribute("date" , newImgSeries->getAttribute("date")->clone() ); msHelper.replaceAttribute("time", newImgSeries->getAttribute("time")->clone() ); msHelper.replaceAttribute("performing_physicians_name" , newImgSeries->getAttribute("performing_physicians_name")->clone() ); msHelper.replaceAttribute("description" , newImgSeries->getAttribute("description")->clone() ); ::fwAtoms::Sequence::sptr newReconstructions = newModelSeries->getAttribute< ::fwAtoms::Sequence >("reconstruction_db"); BOOST_FOREACH( ::fwAtoms::Base::sptr oldRecAtom, oldReconstructions->getValue() ) { ::fwAtoms::Object::sptr oldRec = ::fwAtoms::Object::dynamicCast( oldRecAtom ); newReconstructions->push_back(newVersions[oldRec]); } image2Model[newImgSeries] = newModelSeries; series->push_back( newModelSeries ); } } } } processPlanning(oldCompositeMap, series, image2Model, newVersions); } // End "MedicalWorkspace" } } // namespace fwData } // namespace V2 } // namespace V1 } // namespace fwMDSemanticPatch
[ "fbridault@IRCAD.FR" ]
fbridault@IRCAD.FR
81518f8ab9146a23e51f1e43ae401637ee64368a
51e744fcec9aab44fe45ac246b0c7fd1450a2946
/alg/regression/ridge/ridge.hpp
8c9042cfac035eef5a8ffd38364b3c0a7db991cb
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
zjzshyq/paracel
6053fc0e68ef9bc0d4c5f7e3ae820839fd88174a
b3513495f6c54c66be338a4051a624490ac3aecc
refs/heads/master
2020-04-07T10:45:45.239038
2016-08-28T09:34:30
2016-08-28T09:34:30
67,780,078
1
0
null
2016-09-09T08:14:42
2016-09-09T08:14:42
null
UTF-8
C++
false
false
5,498
hpp
/** * Copyright (c) 2014, Douban Inc. * All rights reserved. * * Distributed under the BSD License. Check out the LICENSE file for full text. * * Paracel - A distributed optimization framework with parameter server. * * Downloading * git clone https://github.com/douban/paracel.git * * Authors: Hong Wu <xunzhangthu@gmail.com> * */ #ifndef FILE_49bad1db_ea7d_9a05_78f3_28202165825f_HPP #define FILE_49bad1db_ea7d_9a05_78f3_28202165825f_HPP #include <math.h> #include <string> #include <vector> #include <algorithm> #include <chrono> #include <iostream> #include "ps.hpp" #include "utils.hpp" namespace paracel { namespace alg { class ridge_regression: public paracel::paralg { public: ridge_regression(paracel::Comm comm, std::string hosts_dct_str, std::string _input, std::string output, std::string update_fn, std::string update_fcn, int _rounds, double _alpha, double _beta) : paracel::paralg(hosts_dct_str, comm, output, _rounds, 0, false), input(_input), update_file(update_fn), update_func(update_fcn), worker_id(comm.get_rank()), rounds(_rounds), alpha(_alpha), beta(_beta) { kdim = 0; loss_error.resize(0); } virtual ~ridge_regression() {} virtual void solve() { auto lines = paracel_load(input); local_parser(lines); paracel_sync(); ipm_learning(); paracel_sync(); } void ipm_learning() { int data_sz = samples.size(); int data_dim = samples[0].size(); theta = paracel::random_double_list(data_dim); paracel_write("theta", theta); std::vector<int> idx; for(int i = 0; i < data_sz; ++i) { idx.push_back(i); } paracel_register_bupdate(update_file, update_func); double coff2 = 2. * beta * alpha; double wgt = 1. / get_worker_size(); std::vector<double> delta(data_dim); unsigned time_seed = std::chrono::system_clock::now().time_since_epoch().count(); for(int rd = 0; rd < rounds; ++rd) { std::shuffle(idx.begin(), idx.end(), std::default_random_engine(time_seed)); theta = paracel_read<std::vector<double> >("theta"); std::vector<double> theta_old(theta); for(auto sample_id : idx) { double coff1 = alpha * (labels[sample_id] - paracel::dot_product(samples[sample_id], theta)); for(int i = 0; i < data_dim; ++i) { double t = coff1 * samples[sample_id][i] - coff2 * theta[i]; theta[i] += t; } } for(int i = 0; i < data_dim; ++i) { delta[i] = wgt * (theta[i] - theta_old[i]); } paracel_sync(); paracel_bupdate("theta", delta); paracel_sync(); std::cout << "worker" << worker_id << " finished round: " << rd << std::endl; } // rounds theta = paracel_read<std::vector<double> >("theta"); } double calc_loss() { double loss = 0.; for(size_t i = 0; i < samples.size(); ++i) { double h = paracel::dot_product(samples[i], theta) - labels[i]; loss += h * h; } auto worker_comm = get_comm(); worker_comm.allreduce(loss); int sz = samples.size(); worker_comm.allreduce(sz); return loss / static_cast<double>(sz); } void dump_result() { if(worker_id == 0) { paracel_dump_vector(theta, "ridge_theta_", "|"); } paracel_dump_vector(predv, "pred_v_", "\n"); } void test(const std::string & test_fn) { auto lines = paracel_load(test_fn); local_parser(lines); std::cout << "loss in test dataset is: " << calc_loss() << std::endl; paracel_sync(); } void predict(const std::string & pred_fn) { auto lines = paracel_load(pred_fn); pred_samples.resize(0); local_parser_pred(lines); predv.resize(0); for(size_t i = 0; i < pred_samples.size(); ++i) { predv.push_back(std::make_pair(pred_samples[i], paracel::dot_product(pred_samples[i], theta))); } paracel_sync(); } private: void local_parser(const std::vector<std::string> & linelst, const char sep = ',') { samples.resize(0); labels.resize(0); for(auto & line : linelst) { std::vector<double> tmp; auto linev = paracel::str_split(line, sep); tmp.push_back(1.); for(size_t i = 0; i < linev.size() - 1; ++i) { tmp.push_back(std::stod(linev[i])); } samples.push_back(tmp); labels.push_back(std::stod(linev.back())); if(kdim == 0) { kdim = samples[0].size() - 1; } } } void local_parser_pred(const std::vector<std::string> & linelst, const char sep = ',') { for(auto & line : linelst) { std::vector<double> tmp; auto linev = paracel::str_split(line, sep); tmp.push_back(1.); for(int i = 0; i < kdim; ++i) { tmp.push_back(std::stod(linev[i])); } pred_samples.push_back(tmp); } } private: std::string input; std::string update_file, update_func; int worker_id; int rounds; double alpha, beta; std::vector<std::vector<double> > samples, pred_samples; std::vector<double> labels; std::vector<double> theta; std::vector<double> loss_error; std::vector<std::pair<std::vector<double>, double> > predv; int kdim; }; // class ridge_regression } // namespacec alg } // namespace paracel #endif
[ "xunzhangthu@gmail.com" ]
xunzhangthu@gmail.com
ab329446c94c9dbe0d259a4c1c55c8fed4139b2b
a22e075e5cd68cd61c822b7d6b28b63f5dcb4c1c
/data_structure/201119_table_to_tree.cpp
384ba4ef33378a771cdd779578fddfe1f0873f96
[]
no_license
Liuqianqian007/learncs
52cc81f638653138799627f6269ed2f0bd9cae60
497aab2b44e505b3c2d3d174aba07f0f97f928e5
refs/heads/main
2023-07-11T03:33:12.003729
2021-08-21T03:59:06
2021-08-21T03:59:06
320,240,746
0
0
null
null
null
null
UTF-8
C++
false
false
4,906
cpp
/************************************************************************* > File Name: table_to_tree.cpp > Author: liuqian > Mail: > Created Time: Thu 19 Nov 2020 08:24:03 PM CST ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> //由广义表还原二叉树 //二叉树结点定义 typedef struct Node{ char data; struct Node *lchild, *rchild; } Node; //二叉树树定义 //n为结点数 typedef struct Tree { Node *root; int n; } Tree; //栈定义:data数组储存栈内元素,栈内元素为二叉树结点的指针, typedef struct Stack { Node **data; int top, size; } Stack; //初始化树结点 Node *getNewNode(char val) { Node *p = (Node *)malloc(sizeof(Node)); p->data = val; p->lchild = p->rchild = NULL; return p; } //初始化二叉树 Tree *getNewTree() { Tree *tree = (Tree *)malloc(sizeof(Tree)); tree->root = NULL; tree->n = 0; return tree; } //初始化栈 Stack *init_stack(int n) { Stack *s = (Stack *) malloc(sizeof(Stack)); s->data = (Node **)malloc(sizeof(Node *) * n); s->top = -1; s->size = n; return s; } //获取栈顶元素 Node *top(Stack *s) { return s->data[s->top]; } //栈的判空 int empty(Stack *s) { return s->top == -1; } //入栈 int push(Stack *s, Node *val) { if (s == NULL) return 0; if (s->top == s->size - 1) return 0; s->data[++(s->top)] = val; return 1; } //出栈 int pop(Stack *s) { if (s == NULL) return 0; if (empty(s)) return 0; s->top -= 1; return 1; } //销毁栈 void clear_stack(Stack *s) { if (s == NULL) return; free(s->data); free(s); return; } //销毁二叉树结点 void clear_node(Node *node) { if (node == NULL) return; clear_node(node->lchild); clear_node(node->rchild); free(node); return; } //销毁二叉树 void clear_tree(Tree *tree) { if (tree == NULL) return; clear_node(tree->root); free(tree); return; } //从广义表还原二叉树 //传入字符串形式的广义表,node_num记录并传出结点数 Node *build(const char *str, int *node_num) { Stack *s = init_stack(strlen(str)); //flag标记是左孩子还是右孩子 int flag = 0; //temp记录当前入栈的结点,p记录根结点 Node *temp = NULL, *p = NULL; while(str[0]) { switch (str[0]) { //遇到(则把(前的元素入栈,并把flag标记成zuohaizi case '(': { push(s, temp); flag = 0; break; } //遇到)则把栈顶元素作为根结点并弹出栈顶元素 case ')': { p = top(s); pop(s); break; } //遇到,则把flag标记成右孩子 case ',': { flag = 1; break; } //遇到空格什么都不做 case ' ': break; //遇到元素则生成结点和二叉树 default: { temp = getNewNode(str[0]); if (!empty(s) && flag == 0) { top(s)->lchild = temp; } else if (!empty(s) && flag == 1) { top(s)->rchild = temp; } ++(*node_num); break; } } ++str; } clear_stack(s); //只有一个根节点,没有()的情况 if (temp && !p) p = temp; return p; } //前序遍历 void pre_order_node(Node *root) { if (root == NULL) return; printf("%c ", root->data); pre_order_node(root->lchild); pre_order_node(root->rchild); } void pre_order(Tree *tree) { if (tree == NULL) return; printf("pre_order : "); pre_order_node(tree->root); printf("\n"); return; } //中序遍历 void in_order_node(Node *root) { if (root == NULL) return; in_order_node(root->lchild); printf("%c ", root->data); in_order_node(root->rchild); } void in_order(Tree *tree) { if (tree == NULL) return; printf("in_order : "); in_order_node(tree->root); printf("\n"); return; } //后序遍历 void post_order_node(Node *root) { if (root == NULL) return; post_order_node(root->lchild); post_order_node(root->rchild); printf("%c ", root->data); } void post_order(Tree *tree) { if (tree == NULL) return; printf("post_order : "); post_order_node(tree->root); printf("\n"); return; } int main() { char str[1000] = {0}; int node_num = 0; scanf("%[^\n]s", str); //由广义表生成二叉树 Tree *tree = getNewTree(); tree->root = build(str, &node_num); tree->n = node_num; //前中后序遍历二叉树 pre_order(tree); in_order(tree); post_order(tree); return 0; }
[ "liuq@github.com" ]
liuq@github.com
d7dbbb2ece7d59b003f31676f1989dea2db48080
bb6ebff7a7f6140903d37905c350954ff6599091
/chrome/test/chromedriver/chrome/device_manager_unittest.cc
cb12f010e1be267268c2b7fa9ef460d9376bf896
[ "BSD-3-Clause" ]
permissive
PDi-Communication-Systems-Inc/lollipop_external_chromium_org
faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f
ccadf4e63dd34be157281f53fe213d09a8c66d2c
refs/heads/master
2022-12-23T18:07:04.568931
2016-04-11T16:03:36
2016-04-11T16:03:36
53,677,925
0
1
BSD-3-Clause
2022-12-09T23:46:46
2016-03-11T15:49:07
C++
UTF-8
C++
false
false
4,442
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "chrome/test/chromedriver/chrome/adb.h" #include "chrome/test/chromedriver/chrome/device_manager.h" #include "chrome/test/chromedriver/chrome/status.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class FakeAdb : public Adb { public: FakeAdb() {} virtual ~FakeAdb() {} virtual Status GetDevices(std::vector<std::string>* devices) OVERRIDE { devices->push_back("a"); devices->push_back("b"); return Status(kOk); } virtual Status ForwardPort(const std::string& device_serial, int local_port, const std::string& remote_abstract) OVERRIDE { return Status(kOk); } virtual Status SetCommandLineFile(const std::string& device_serial, const std::string& command_line_file, const std::string& exec_name, const std::string& args) OVERRIDE { return Status(kOk); } virtual Status CheckAppInstalled(const std::string& device_serial, const std::string& package) OVERRIDE { return Status(kOk); } virtual Status ClearAppData(const std::string& device_serial, const std::string& package) OVERRIDE { return Status(kOk); } virtual Status SetDebugApp(const std::string& device_serial, const std::string& package) OVERRIDE { return Status(kOk); } virtual Status Launch(const std::string& device_serial, const std::string& package, const std::string& activity) OVERRIDE { return Status(kOk); } virtual Status ForceStop(const std::string& device_serial, const std::string& package) OVERRIDE { return Status(kOk); } virtual Status GetPidByName(const std::string& device_serial, const std::string& process_name, int* pid) OVERRIDE { return Status(kOk); } }; } // namespace TEST(DeviceManager, AcquireDevice) { FakeAdb adb; DeviceManager device_manager(&adb); scoped_ptr<Device> device1; scoped_ptr<Device> device2; scoped_ptr<Device> device3; ASSERT_TRUE(device_manager.AcquireDevice(&device1).IsOk()); ASSERT_TRUE(device_manager.AcquireDevice(&device2).IsOk()); ASSERT_FALSE(device_manager.AcquireDevice(&device3).IsOk()); device1.reset(NULL); ASSERT_TRUE(device_manager.AcquireDevice(&device3).IsOk()); ASSERT_FALSE(device_manager.AcquireDevice(&device1).IsOk()); } TEST(DeviceManager, AcquireSpecificDevice) { FakeAdb adb; DeviceManager device_manager(&adb); scoped_ptr<Device> device1; scoped_ptr<Device> device2; scoped_ptr<Device> device3; ASSERT_TRUE(device_manager.AcquireSpecificDevice("a", &device1).IsOk()); ASSERT_FALSE(device_manager.AcquireSpecificDevice("a", &device2).IsOk()); ASSERT_TRUE(device_manager.AcquireSpecificDevice("b", &device3).IsOk()); device1.reset(NULL); ASSERT_TRUE(device_manager.AcquireSpecificDevice("a", &device2).IsOk()); ASSERT_FALSE(device_manager.AcquireSpecificDevice("a", &device1).IsOk()); ASSERT_FALSE(device_manager.AcquireSpecificDevice("b", &device1).IsOk()); } TEST(Device, StartStopApp) { FakeAdb adb; DeviceManager device_manager(&adb); scoped_ptr<Device> device1; ASSERT_TRUE(device_manager.AcquireDevice(&device1).IsOk()); ASSERT_TRUE(device1->TearDown().IsOk()); ASSERT_TRUE(device1->SetUp("a.chrome.package", "", "", "", false, 0).IsOk()); ASSERT_FALSE(device1->SetUp("a.chrome.package", "", "", "", false, 0).IsOk()); ASSERT_TRUE(device1->TearDown().IsOk()); ASSERT_FALSE(device1->SetUp( "a.chrome.package", "an.activity", "", "", false, 0).IsOk()); ASSERT_FALSE(device1->SetUp("a.package", "", "", "", false, 0).IsOk()); ASSERT_TRUE(device1->SetUp( "a.package", "an.activity", "", "", false, 0).IsOk()); ASSERT_TRUE(device1->TearDown().IsOk()); ASSERT_TRUE(device1->TearDown().IsOk()); ASSERT_TRUE(device1->SetUp( "a.package", "an.activity", "a.process", "", false, 0).IsOk()); ASSERT_TRUE(device1->TearDown().IsOk()); }
[ "mrobbeloth@pdiarm.com" ]
mrobbeloth@pdiarm.com
be223f0d8753ee5443afce7aedf66481ab1b524d
2ea7d56215ac5b18df1b735fb9020ec157261d63
/lib/utility/include/zeno/Utility/StringExtensions.hpp
2f8d3cbdc2330d7a450eb4300a532a856ea1db1b
[ "MIT" ]
permissive
MarkRDavison/zeno
f73330d8d664c746f96fadea46eefbf2f8ac4b5a
cea002e716e624d28130e836bf56e9f2f1d2e484
refs/heads/master
2023-07-07T19:41:51.308909
2021-08-21T22:57:28
2021-08-21T22:57:28
274,806,040
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
hpp
#ifndef INCLUDED_ZENO_UTILITY_STRING_EXTENSIONS_HPP_ #define INCLUDED_ZENO_UTILITY_STRING_EXTENSIONS_HPP_ #include <vector> #include <string> namespace ze { class StringExtensions { public: static std::string loadFileToString(const std::string& _path); static std::vector<std::string> splitStringByDelimeter(const std::string& _parameter, const std::string& _delimeter); static std::size_t hash(const std::string& _string); static std::vector<std::string> splitStringByString(const std::string& _string, const std::string& _splitString); static bool startsWith(const std::string& _str, const std::string& _start); static bool endsWith(const std::string& _str, const std::string& _end); static std::string stripLeadingWhitespace(const std::string& _str); static void replaceAll(std::string& _string, const std::string& _substring, const std::string& _replacement); private: StringExtensions(void) = delete; ~StringExtensions(void) = delete; }; } #endif // INCLUDED_ZENO_UTILITY_STRING_EXTENSIONS_HPP_
[ "Mark@DESKTOP-V1BKCDT" ]
Mark@DESKTOP-V1BKCDT
fb31d9275f22e28a552615170bcac66f499589b5
562363c841306f88173a49da6ae273305696d6ba
/MicrosoftJoyn/org.alljoyn.Notification/NotificationServiceEventArgs.h
57b73c61f4228ea68164b952e86d411c12cfd021
[]
no_license
NathanielRose/MicrosoftJoyn
b288dc5fb19a6c5a5cb00844b0e5a4f79810224f
76a614a0dad2b02f62c135998ce1e80f0d4ac8f5
refs/heads/master
2021-01-10T15:52:39.812778
2016-03-23T01:19:17
2016-03-23T01:19:17
45,492,968
4
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
//----------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // Tool: AllJoynCodeGenerator.exe // // This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn // Visual Studio Extension in the Visual Studio Gallery. // // The generated code should be packaged in a Windows 10 C++/CX Runtime // Component which can be consumed in any UWP-supported language using // APIs that are available in Windows.Devices.AllJoyn. // // Using AllJoynCodeGenerator - Invoke the following command with a valid // Introspection XML file and a writable output directory: // AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY> // </auto-generated> //----------------------------------------------------------------------------- #pragma once namespace org { namespace alljoyn { namespace Notification { // Methods // Readable Properties // Writable Properties } } }
[ "rose.nathanielm@gmail.com" ]
rose.nathanielm@gmail.com
782556e2e51e5705a7a9da6e02ae758d5db999a1
cb083845ee088f7ed57ce21216c917005389853b
/public/src/user_exception.cpp
7a7d405a6e1e97e91b74e77514963532266ed112
[]
no_license
jjzhang166/ServiceGalaxy
1258f2432e1e169edf1fcc422806eb5a12ac353b
6f7be491616a8bffa9d39d7925c5d6733e85d3b3
refs/heads/master
2023-03-16T13:39:30.787314
2016-06-25T01:18:34
2016-06-25T01:18:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,717
cpp
/** * @file user_exception.cpp * @brief The implement of the user's exceptions. * * @author Dejin Bao * @author Former author list: Genquan Xu * @version 3.5 * @date 2005-11-15 */ #include "user_exception.h" namespace ai { namespace sg { using namespace std; const char* bad_file::messages[] = { "bad_stat", "bad_lstat", "bad_statfs", "bad_sock", "bad_open", "bad_seek", "bad_read", "bad_write", "bad_flush", "bad_close", "bad_remove", "bad_rename", "bad_opendir", "bad_ioctl", "bad_popen" }; /** * @fn util::bad_file::bad_file(const string& file, * int line, * int error_code_, * const string& obj = "") throw() * @brief The constructor function. * * Creates a bad_file object. To avoid the nested exception, it cannot throw a * new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. * @param[in] error_code_ The error code of the exception. And the error code is * one of the util::bad_file::bad_type which is an enumeration type. * @param[in] obj The object of the exception, and the default value is null. */ bad_file::bad_file(const string& file, int line, int sys_code_, int error_code_, const string& obj) throw() { sys_code = sys_code_; error_code = error_code_; what_ = (_("ERROR: In file {1}:{2}: error code: {3}, object: {4}") % file % line % error_code % obj).str(SGLOCALE); } /** * @fn util::bad_file::~bad_file() throw() * @brief The destructor function. * * Destroys a bad_file object. To avoid the nested exception, it cannot throw a * new exception. */ bad_file::~bad_file() throw() { } /** * @fn const char* util::bad_file::error_msg() const throw() * @brief Returns the error content associated with the error code. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_file::error_msg() const throw() { return messages[error_code]; } /** * @fn const char* util::bad_file::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_file::what () const throw() { return what_.c_str(); } const char* bad_system::messages[] = { "bad_cmd", "bad_dlopen", "bad_dlsym", "bad_dlclose", "bad_reg", "bad_sem", "bad_shm", "bad_msg", "bad_pstat", "bad_alloc", "bad_select", "bad_fork", "bad_exec", "bad_other" }; /** * @fn util::bad_system::bad_system(const string& file, * int line, * int error_code_, * const string& cause = "") throw() * @brief The constructor function. * * Creates a bad_system object. To avoid the nested exception, it cannot throw a * new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. * @param[in] error_code_ The error code of the exception. And the error code is * one of the util::bad_system::bad_type which is an enumeration type. * @param[in] cause The cause of the exception, and the default value is null. */ bad_system::bad_system(const string& file, int line, int sys_code_, int error_code_, const string& cause) throw() { sys_code = sys_code_; error_code = error_code_; if (cause.empty()) { what_ = (_("ERROR: In file {1}:{2}: error code: {3}") % file % line % error_code).str(SGLOCALE); } else { what_ = (_("ERROR: In file {1}:{2}: error code: {3}, cause: {4}") % file % line % error_code % cause).str(SGLOCALE); } } /** * @fn util::bad_system::~bad_system() throw() * @brief The destructor function. * * Destroys a bad_system object. To avoid the nested exception, it cannot throw * a new exception. */ bad_system::~bad_system() throw() { } /** * @fn const char* util::bad_system::error_msg() const throw() * @brief Returns the error content associated with the error code. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_system::error_msg() const throw() { return messages[error_code]; } /** * @fn const char* util::bad_system::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_system::what () const throw() { return what_.c_str(); } /** * @fn util::bad_auth::bad_auth(const string& file, int line) throw() * @brief The constructor function. * * Creates a bad_auth object. To avoid the nested exception, it cannot throw a * new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. */ bad_auth::bad_auth(const string& file, int line, int sys_code_) throw() { sys_code = sys_code_; what_ = (_("ERROR: In file {1}:{2}") % file % line).str(SGLOCALE); } /** * @fn util::bad_auth::~bad_auth() throw() * @brief The destructor function. * * Destroys a bad_auth object. To avoid the nested exception, it cannot throw a * new exception. */ bad_auth::~bad_auth() throw() { } /** * @fn const char* util::bad_auth::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_auth::what () const throw() { return what_.c_str(); } /** * @fn util::bad_param::bad_param(const string& file, * int line, * const string& cause) throw() * @brief The constructor function. * * Creates a bad_param object. To avoid the nested exception, it cannot throw a * new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. * @param[in] cause The cause of the exception. */ bad_param::bad_param(const string& file, int line, int sys_code_, const string& cause) throw() { sys_code = sys_code_; if (cause.empty()) { what_ = (_("ERROR: In file {1}:{2}") % file % line).str(SGLOCALE); } else { what_ = (_("ERROR: In file {1}:{2}: cause: {3}") % file % line % cause).str(SGLOCALE); } } /** * @fn util::bad_param::~bad_param() throw() * @brief The destructor function. * * Destroys a bad_param object. To avoid the nested exception, it cannot throw a * new exception. */ bad_param::~bad_param() throw() { } /** * @fn const char* util::bad_param::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_param::what () const throw() { return what_.c_str(); } const char* bad_datetime::messages[] = { "bad_year", "bad_month", "bad_day", "bad_hour", "bad_minute", "bad_second", "bad_other" }; /** * @fn util::bad_datetime::bad_datetime(const string& file, * int line, * int error_code_, * const string& obj = "") throw() * @brief The constructor function. * * Creates a bad_datetime object. To avoid the nested exception, it cannot throw * a new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. * @param[in] error_code_ The error code of the exception. And the error code is * one of the util::bad_datetime::bad_type which is an enumeration type. * @param[in] obj The object of the exception, and the default value is null. */ bad_datetime::bad_datetime(const string& file, int line, int sys_code_, int error_code_, const string& obj) throw() { sys_code = sys_code_; error_code = error_code_; what_ = (_("ERROR: In file {1}:{2}: error code: {3}, object: {4}") % file % line % error_code % obj).str(SGLOCALE); } /** * @fn util::bad_datetime::~bad_datetime() throw() * @brief The destructor function. * * Destroys a bad_datetime object. To avoid the nested exception, it cannot * throw a new exception. */ bad_datetime::~bad_datetime() throw() { } /** * @fn const char* util::bad_datetime::error_msg() const throw() * @brief Returns the error content associated with the error code. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_datetime::error_msg() const throw() { return messages[error_code]; } /** * @fn const char* util::bad_datetime::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_datetime::what () const throw() { return what_.c_str(); } /** * @fn util::bad_msg::bad_msg(const string& file, * int line, * const string& msg) throw() * @brief The constructor function. * * Creates a bad_msg object. To avoid the nested exception, it cannot throw a * new exception. * * @param[in] file The filename which throws an exception. * @param[in] line The line number of the file which throws an exception. * @param[in] msg The error message of the exception. */ bad_msg::bad_msg(const string& file, int line, int sys_code_, const string& msg) throw() { sys_code = sys_code_; what_ = (_("ERROR: In file {1}:{2}: message: {3}") % file % line % msg).str(SGLOCALE); } /** * @fn util::bad_msg::~bad_msg() throw() * @brief The destructor function. * * Destroys a bad_msg object. To avoid the nested exception, it cannot throw a * new exception. */ bad_msg::~bad_msg() throw() { } /** * @fn const char* util::bad_msg::what() const throw() * @brief Returns the error message associated with the exception. * * To avoid the nested exception, it cannot throw a new exception. */ const char* bad_msg::what () const throw() { return what_.c_str(); } } }
[ "xugq@asiainfo.com" ]
xugq@asiainfo.com
380af296f030f868d175599eda6b1cf2959cd3d3
53fbc3854cc13b580f16dbc1b59e86d498199036
/src/crypto/sha512.cpp
342101cec86c5427613867d283944bfa8dfb9807
[ "MIT" ]
permissive
syglee7/ZenaCoin
d654ea11b8e5081f6cad4e656f9c9ead7bbc08f1
f1f438444e59aca9d4f9950e267f37153afb60c4
refs/heads/master
2020-11-24T06:19:26.602965
2020-02-07T07:53:09
2020-02-07T07:53:09
228,004,960
1
0
null
null
null
null
UTF-8
C++
false
false
11,007
cpp
// Copyright (c) 2014 The Zenacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/sha512.h" #include "crypto/common.h" #include <string.h> // Internal implementation code. namespace { /// Internal SHA-512 implementation. namespace sha512 { uint64_t inline Ch(uint64_t x, uint64_t y, uint64_t z) { return z ^ (x & (y ^ z)); } uint64_t inline Maj(uint64_t x, uint64_t y, uint64_t z) { return (x & y) | (z & (x | y)); } uint64_t inline Sigma0(uint64_t x) { return (x >> 28 | x << 36) ^ (x >> 34 | x << 30) ^ (x >> 39 | x << 25); } uint64_t inline Sigma1(uint64_t x) { return (x >> 14 | x << 50) ^ (x >> 18 | x << 46) ^ (x >> 41 | x << 23); } uint64_t inline sigma0(uint64_t x) { return (x >> 1 | x << 63) ^ (x >> 8 | x << 56) ^ (x >> 7); } uint64_t inline sigma1(uint64_t x) { return (x >> 19 | x << 45) ^ (x >> 61 | x << 3) ^ (x >> 6); } /** One round of SHA-512. */ void inline Round(uint64_t a, uint64_t b, uint64_t c, uint64_t& d, uint64_t e, uint64_t f, uint64_t g, uint64_t& h, uint64_t k, uint64_t w) { uint64_t t1 = h + Sigma1(e) + Ch(e, f, g) + k + w; uint64_t t2 = Sigma0(a) + Maj(a, b, c); d += t1; h = t1 + t2; } /** Initialize SHA-256 state. */ void inline Initialize(uint64_t* s) { s[0] = 0x6a09e667f3bcc908ull; s[1] = 0xbb67ae8584caa73bull; s[2] = 0x3c6ef372fe94f82bull; s[3] = 0xa54ff53a5f1d36f1ull; s[4] = 0x510e527fade682d1ull; s[5] = 0x9b05688c2b3e6c1full; s[6] = 0x1f83d9abfb41bd6bull; s[7] = 0x5be0cd19137e2179ull; } /** Perform one SHA-512 transformation, processing a 128-byte chunk. */ void Transform(uint64_t* s, const unsigned char* chunk) { uint64_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; uint64_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; Round(a, b, c, d, e, f, g, h, 0x428a2f98d728ae22ull, w0 = ReadBE64(chunk + 0)); Round(h, a, b, c, d, e, f, g, 0x7137449123ef65cdull, w1 = ReadBE64(chunk + 8)); Round(g, h, a, b, c, d, e, f, 0xb5c0fbcfec4d3b2full, w2 = ReadBE64(chunk + 16)); Round(f, g, h, a, b, c, d, e, 0xe9b5dba58189dbbcull, w3 = ReadBE64(chunk + 24)); Round(e, f, g, h, a, b, c, d, 0x3956c25bf348b538ull, w4 = ReadBE64(chunk + 32)); Round(d, e, f, g, h, a, b, c, 0x59f111f1b605d019ull, w5 = ReadBE64(chunk + 40)); Round(c, d, e, f, g, h, a, b, 0x923f82a4af194f9bull, w6 = ReadBE64(chunk + 48)); Round(b, c, d, e, f, g, h, a, 0xab1c5ed5da6d8118ull, w7 = ReadBE64(chunk + 56)); Round(a, b, c, d, e, f, g, h, 0xd807aa98a3030242ull, w8 = ReadBE64(chunk + 64)); Round(h, a, b, c, d, e, f, g, 0x12835b0145706fbeull, w9 = ReadBE64(chunk + 72)); Round(g, h, a, b, c, d, e, f, 0x243185be4ee4b28cull, w10 = ReadBE64(chunk + 80)); Round(f, g, h, a, b, c, d, e, 0x550c7dc3d5ffb4e2ull, w11 = ReadBE64(chunk + 88)); Round(e, f, g, h, a, b, c, d, 0x72be5d74f27b896full, w12 = ReadBE64(chunk + 96)); Round(d, e, f, g, h, a, b, c, 0x80deb1fe3b1696b1ull, w13 = ReadBE64(chunk + 104)); Round(c, d, e, f, g, h, a, b, 0x9bdc06a725c71235ull, w14 = ReadBE64(chunk + 112)); Round(b, c, d, e, f, g, h, a, 0xc19bf174cf692694ull, w15 = ReadBE64(chunk + 120)); Round(a, b, c, d, e, f, g, h, 0xe49b69c19ef14ad2ull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0xefbe4786384f25e3ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x0fc19dc68b8cd5b5ull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x240ca1cc77ac9c65ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x2de92c6f592b0275ull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x4a7484aa6ea6e483ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x5cb0a9dcbd41fbd4ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x76f988da831153b5ull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x983e5152ee66dfabull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0xa831c66d2db43210ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0xb00327c898fb213full, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0xbf597fc7beef0ee4ull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0xc6e00bf33da88fc2ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xd5a79147930aa725ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0x06ca6351e003826full, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x142929670a0e6e70ull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0x27b70a8546d22ffcull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0x2e1b21385c26c926ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc5ac42aedull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x53380d139d95b3dfull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x650a73548baf63deull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x766a0abb3c77b2a8ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x81c2c92e47edaee6ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x92722c851482353bull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0xa2bfe8a14cf10364ull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0xa81a664bbc423001ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0xc24b8b70d0f89791ull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0xc76c51a30654be30ull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0xd192e819d6ef5218ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xd69906245565a910ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0xf40e35855771202aull, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x106aa07032bbd1b8ull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0x19a4c116b8d2d0c8ull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0x1e376c085141ab53ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0x2748774cdf8eeb99ull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0x34b0bcb5e19b48a8ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x391c0cb3c5c95a63ull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x4ed8aa4ae3418acbull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x5b9cca4f7763e373ull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x682e6ff3d6b2b8a3ull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x748f82ee5defb2fcull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0x78a5636f43172f60ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0x84c87814a1f0ab72ull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0x8cc702081a6439ecull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0x90befffa23631e28ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0xa4506cebde82bde9ull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0xbef9a3f7b2c67915ull, w14 += sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0xc67178f2e372532bull, w15 += sigma1(w13) + w8 + sigma0(w0)); Round(a, b, c, d, e, f, g, h, 0xca273eceea26619cull, w0 += sigma1(w14) + w9 + sigma0(w1)); Round(h, a, b, c, d, e, f, g, 0xd186b8c721c0c207ull, w1 += sigma1(w15) + w10 + sigma0(w2)); Round(g, h, a, b, c, d, e, f, 0xeada7dd6cde0eb1eull, w2 += sigma1(w0) + w11 + sigma0(w3)); Round(f, g, h, a, b, c, d, e, 0xf57d4f7fee6ed178ull, w3 += sigma1(w1) + w12 + sigma0(w4)); Round(e, f, g, h, a, b, c, d, 0x06f067aa72176fbaull, w4 += sigma1(w2) + w13 + sigma0(w5)); Round(d, e, f, g, h, a, b, c, 0x0a637dc5a2c898a6ull, w5 += sigma1(w3) + w14 + sigma0(w6)); Round(c, d, e, f, g, h, a, b, 0x113f9804bef90daeull, w6 += sigma1(w4) + w15 + sigma0(w7)); Round(b, c, d, e, f, g, h, a, 0x1b710b35131c471bull, w7 += sigma1(w5) + w0 + sigma0(w8)); Round(a, b, c, d, e, f, g, h, 0x28db77f523047d84ull, w8 += sigma1(w6) + w1 + sigma0(w9)); Round(h, a, b, c, d, e, f, g, 0x32caab7b40c72493ull, w9 += sigma1(w7) + w2 + sigma0(w10)); Round(g, h, a, b, c, d, e, f, 0x3c9ebe0a15c9bebcull, w10 += sigma1(w8) + w3 + sigma0(w11)); Round(f, g, h, a, b, c, d, e, 0x431d67c49c100d4cull, w11 += sigma1(w9) + w4 + sigma0(w12)); Round(e, f, g, h, a, b, c, d, 0x4cc5d4becb3e42b6ull, w12 += sigma1(w10) + w5 + sigma0(w13)); Round(d, e, f, g, h, a, b, c, 0x597f299cfc657e2aull, w13 += sigma1(w11) + w6 + sigma0(w14)); Round(c, d, e, f, g, h, a, b, 0x5fcb6fab3ad6faecull, w14 + sigma1(w12) + w7 + sigma0(w15)); Round(b, c, d, e, f, g, h, a, 0x6c44198c4a475817ull, w15 + sigma1(w13) + w8 + sigma0(w0)); s[0] += a; s[1] += b; s[2] += c; s[3] += d; s[4] += e; s[5] += f; s[6] += g; s[7] += h; } } // namespace sha512 } // namespace ////// SHA-512 CSHA512::CSHA512() : bytes(0) { sha512::Initialize(s); } CSHA512& CSHA512::Write(const unsigned char* data, size_t len) { const unsigned char* end = data + len; size_t bufsize = bytes % 128; if (bufsize && bufsize + len >= 128) { // Fill the buffer, and process it. memcpy(buf + bufsize, data, 128 - bufsize); bytes += 128 - bufsize; data += 128 - bufsize; sha512::Transform(s, buf); bufsize = 0; } while (end >= data + 128) { // Process full chunks directly from the source. sha512::Transform(s, data); data += 128; bytes += 128; } if (end > data) { // Fill the buffer with what remains. memcpy(buf + bufsize, data, end - data); bytes += end - data; } return *this; } void CSHA512::Finalize(unsigned char hash[OUTPUT_SIZE]) { static const unsigned char pad[128] = {0x80}; unsigned char sizedesc[16] = {0x00}; WriteBE64(sizedesc + 8, bytes << 3); Write(pad, 1 + ((239 - (bytes % 128)) % 128)); Write(sizedesc, 16); WriteBE64(hash, s[0]); WriteBE64(hash + 8, s[1]); WriteBE64(hash + 16, s[2]); WriteBE64(hash + 24, s[3]); WriteBE64(hash + 32, s[4]); WriteBE64(hash + 40, s[5]); WriteBE64(hash + 48, s[6]); WriteBE64(hash + 56, s[7]); } CSHA512& CSHA512::Reset() { bytes = 0; sha512::Initialize(s); return *this; }
[ "syglee7@gmail.com" ]
syglee7@gmail.com
a8bcbe257c278204a7aacbe318529d78e92c3f59
d1ad68da0d7d3a71c2d43d297d6fd3cffbbf75c2
/library/short-cycles/NotOptimized/PCycles.04b.cpp
9bd5275f39bff5aacab59500806bfea32186acb9
[]
no_license
hamko/procon
2a0a685b88a69951be7a9217dd32955f9500df57
a822f8089a3063a158d47ea48c54aca89934f855
refs/heads/master
2021-01-17T00:00:10.915298
2020-02-24T06:24:33
2020-02-24T06:24:33
55,990,248
7
1
null
2020-02-24T06:24:34
2016-04-11T16:49:50
C++
UTF-8
C++
false
false
3,841
cpp
/** * ---==== Counting the Number of 4-Cycles in a Bipartite Undirected Graph ====--- * Parallel version with Int128 answer type * * AUTHORS: Anton N. Voropaev * ``````` Artem M. Karavaev ( http://www.flowproblem.ru ) * * CREATED: 25.11.2009 * ``````` * VERSION: 6.0 ( from 21.03.2010 ) * ``````` */ #include "mpi.h" #define VERSION "6.0" #define N 128 // The maximum number of vertices ( YOU MAY CHANGE IT ) #define K 4 // The length of the cycles ( DO NOT CHANGE ) #include "Int128.h" using namespace Zeal; typedef Int128 TAnswer; #include <stdio.h> #include <stdlib.h> int n, m; FILE * in, * out = stdout; int A1 [ N ] [ N ]; TAnswer A [ K ] [ N ] [ N ]; TAnswer ans; void c4b ( ); #define MAIN 0 char nameOfProc [ MPI_MAX_PROCESSOR_NAME ]; int myId, numOfProcs, lenOfName; double startTime, endTime, Time; MPI_Status status; int64 number [ 2 ]; void sumAndDiv ( TAnswer s, int k ) { int p; TAnswer tmp; if ( myId != MAIN ) { number [ 0 ] = s . l; number [ 1 ] = s . h; MPI_Send ( number, 2, MPI_LONG_LONG, MAIN, 1, MPI_COMM_WORLD ); } if ( myId == MAIN ) { for ( p = 1; p < numOfProcs; p ++ ) { MPI_Recv ( number, 2, MPI_LONG_LONG, p, 1, MPI_COMM_WORLD, & status ); tmp . l = number [ 0 ]; tmp . h = number [ 1 ]; s += tmp; } } ans = s; ans /= k; } // Multiply A * B. A contains only 0 and 1. void MulMatrix ( int A [ N ] [ N ], TAnswer B [ N ] [ N ], TAnswer C [ N ] [ N ] ) { int i, j, r; for ( i = 0; i < n; i ++ ) for ( r = 0; r < n; r ++ ) if ( A [ i ] [ r ] ) for ( j = 0; j < n; j ++ ) C [ i ] [ j ] += B [ r ] [ j ]; } void Init ( ) { int i, p, q; fscanf ( in, "%d %d", &n, &m ); if ( n > N ) { fprintf ( stderr, "n is too big (%d), make constant `N' bigger\n", n ); exit ( 1 ); } for ( i = 0; i < m; i ++ ) { fscanf ( in, "%d %d", &p, &q ); A1 [ p - 1 ] [ q - 1 ] = 1; A1 [ q - 1 ] [ p - 1 ] = 1; A [ 0 ] [ p - 1 ] [ q - 1 ] = 1; A [ 0 ] [ q - 1 ] [ p - 1 ] = 1; } for ( i = 1; i < K; i ++ ) MulMatrix ( A1, A [ i - 1 ], A [ i ] ); } int main ( int argc, char * argv [ ] ) { int i; // Init MPI variables MPI_Init ( & argc, & argv ); MPI_Comm_size ( MPI_COMM_WORLD, & numOfProcs ); MPI_Comm_rank ( MPI_COMM_WORLD, & myId ); MPI_Get_processor_name ( nameOfProc, & lenOfName ); if ( argc < 2 ) { fprintf ( stderr, "Usage: %s ``input-file'' [ ``output-file'' ]\n", argv [ 0 ] ); return 0; } if ( argc > 3 ) { fprintf ( stderr, "Too many parameters: %d\n", argc ); return 1; } if ( ( in = fopen ( argv [ 1 ], "r" ) ) == NULL ) { fprintf ( stderr, "Cannot open file %s for reading\n", argv [ 1 ] ); return 1; } if ( argc == 3 && myId == MAIN && ( out = fopen ( argv [ 2 ], "w" ) ) == NULL ) { fprintf ( stderr, "Cannot open file %s for writing\n", argv [ 2 ] ); return 1; } Init ( ); fclose ( in ); c4b ( ); if ( myId == MAIN ) { ans . print ( out ); fclose ( out ); } // Waiting for all to finish at once MPI_Barrier ( MPI_COMM_WORLD ); MPI_Finalize ( ); return 0; } void c4b ( ) { TAnswer s, t1, t2; int i, i1, i2; s = 0; /* TWO */ t1 = 0; for ( i = myId; i < n * n; i += numOfProcs ) { i1 = i / n; i2 = i - i1 * n; t1 += A[1][i1][i2]; } s += t1 * ( -2 ); /* ONE */ t1 = t2 = 0; for ( i1 = myId; i1 < n; i1 += numOfProcs ) { t1 += A[3][i1][i1]; t2 += A[1][i1][i1]; } s += t1 * ( 1 ); s += t2 * ( 1 ); sumAndDiv ( s, 8 ); }
[ "wakataberyo@gmail.com" ]
wakataberyo@gmail.com
6822fc860a25f31854f3d2c1ab0b72eb43dd6838
de2f597a55545c3315ad3f462062b4e29a7a5c53
/ZyboZ7-10_PID_MotorControl.srcs/sources_1/bd/Block_Diagram/ip/Block_Diagram_xlconstant_0_0/sim/Block_Diagram_xlconstant_0_0.h
63e93f46d54abdff7cb3081f00fa99a7c5416b4f
[]
no_license
RemcoKuijpers/ZyboZ7-10_PID_MotorControl
0e9b24c7ae6fac3ef7f72f99ef0aa24f8e2c3cde
f240b3d9a2ada8f262bc38dc08800c5c767e80cf
refs/heads/master
2020-12-11T10:00:42.117682
2020-01-31T12:17:28
2020-01-31T12:17:28
233,814,981
1
0
null
null
null
null
UTF-8
C++
false
false
2,692
h
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:xlconstant:1.1 // IP Revision: 1 #ifndef _Block_Diagram_xlconstant_0_0_H_ #define _Block_Diagram_xlconstant_0_0_H_ #include "xlconstant_v1_1.h" #include "systemc.h" class Block_Diagram_xlconstant_0_0 : public sc_module { public: xlconstant_v1_1_5<1,1> mod; sc_out< sc_bv<1> > dout; Block_Diagram_xlconstant_0_0 (sc_core::sc_module_name name) :sc_module(name), mod("mod") { mod.dout(dout); } }; #endif
[ "remco.kuijpers@hotmail.nl" ]
remco.kuijpers@hotmail.nl
ba3d263e9ffa12928540b07456f28f262f925b93
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/Unity_IO_Compression_Unity_IO_Compression_OutputBu1763155281.h
0577672d82a1359302c56bdfcd9fcc6f2874b6f2
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
2,363
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Byte[] struct ByteU5BU5D_t3397334013; #include "mscorlib_System_Object2689449295.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Unity.IO.Compression.OutputBuffer struct OutputBuffer_t1763155281 : public Il2CppObject { public: // System.Byte[] Unity.IO.Compression.OutputBuffer::byteBuffer ByteU5BU5D_t3397334013* ___byteBuffer_0; // System.Int32 Unity.IO.Compression.OutputBuffer::pos int32_t ___pos_1; // System.UInt32 Unity.IO.Compression.OutputBuffer::bitBuf uint32_t ___bitBuf_2; // System.Int32 Unity.IO.Compression.OutputBuffer::bitCount int32_t ___bitCount_3; public: inline static int32_t get_offset_of_byteBuffer_0() { return static_cast<int32_t>(offsetof(OutputBuffer_t1763155281, ___byteBuffer_0)); } inline ByteU5BU5D_t3397334013* get_byteBuffer_0() const { return ___byteBuffer_0; } inline ByteU5BU5D_t3397334013** get_address_of_byteBuffer_0() { return &___byteBuffer_0; } inline void set_byteBuffer_0(ByteU5BU5D_t3397334013* value) { ___byteBuffer_0 = value; Il2CppCodeGenWriteBarrier(&___byteBuffer_0, value); } inline static int32_t get_offset_of_pos_1() { return static_cast<int32_t>(offsetof(OutputBuffer_t1763155281, ___pos_1)); } inline int32_t get_pos_1() const { return ___pos_1; } inline int32_t* get_address_of_pos_1() { return &___pos_1; } inline void set_pos_1(int32_t value) { ___pos_1 = value; } inline static int32_t get_offset_of_bitBuf_2() { return static_cast<int32_t>(offsetof(OutputBuffer_t1763155281, ___bitBuf_2)); } inline uint32_t get_bitBuf_2() const { return ___bitBuf_2; } inline uint32_t* get_address_of_bitBuf_2() { return &___bitBuf_2; } inline void set_bitBuf_2(uint32_t value) { ___bitBuf_2 = value; } inline static int32_t get_offset_of_bitCount_3() { return static_cast<int32_t>(offsetof(OutputBuffer_t1763155281, ___bitCount_3)); } inline int32_t get_bitCount_3() const { return ___bitCount_3; } inline int32_t* get_address_of_bitCount_3() { return &___bitCount_3; } inline void set_bitCount_3(int32_t value) { ___bitCount_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "gdesmarais@gsngames.com" ]
gdesmarais@gsngames.com
73c0fb5dde366c66969e5aeda2f33e1f3832fe27
051211c627f63aa37cce1cf085bf8b33cd6494af
/EPI/EPI_bak/trunk/.svn/text-base/Merge_sorted_lists.cpp.svn-base
01606e8b76dd8bf6c8604c62486d68d28d364b20
[]
no_license
roykim0823/Interview
32994ea0ec341ec19a644c7f3ef3b0774b228f2c
660ab546a72ca86b4c4a91d3c7279a8171398652
refs/heads/master
2020-03-24T02:37:01.125120
2019-11-19T05:25:15
2019-11-19T05:25:15
139,811,693
0
0
null
null
null
null
UTF-8
C++
false
false
1,686
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved. #include <cassert> #include <iostream> #include <limits> #include <memory> #include <random> #include <string> #include "./Linked_list_prototype.h" #include "./Merge_sorted_lists.h" using std::cout; using std::default_random_engine; using std::endl; using std::make_shared; using std::numeric_limits; using std::random_device; using std::stoi; using std::uniform_int_distribution; int main(int argc, char* argv[]) { default_random_engine gen((random_device())()); for (int times = 0; times < 10000; ++times) { shared_ptr<ListNode<int>> F = nullptr, L = nullptr; int n, m; if (argc == 3) { n = stoi(argv[1]), m = stoi(argv[2]); } else if (argc == 2) { n = stoi(argv[1]), m = stoi(argv[1]); } else { uniform_int_distribution<int> dis(0, 99); n = dis(gen), m = dis(gen); } for (int i = n; i > 0; --i) { shared_ptr<ListNode<int>> temp = make_shared<ListNode<int>>(ListNode<int>{i, nullptr}); temp->next = F; F = temp; } for (int j = m; j > 0; --j) { shared_ptr<ListNode<int>> temp = make_shared<ListNode<int>>(ListNode<int>{j, nullptr}); temp->next = L; L = temp; } shared_ptr<ListNode<int>> sorted_head = merge_sorted_linked_lists(F, L); int count = 0; int pre = numeric_limits<int>::min(); while (sorted_head) { assert(pre <= sorted_head->data); pre = sorted_head->data; sorted_head = sorted_head->next; ++count; } // Make sure the merged list have the same number of nodes as F and L. assert(count == n + m); } return 0; }
[ "roykim0823@gmail.com" ]
roykim0823@gmail.com
70537340b266ecf4ab19f00807abafe3e0644eef
5d81e3fe85535549e890512cb0f3f284d08d7516
/aula05/experiment.hpp
1fb91722e51999980db9bbbcbd20705fbb97bb00
[]
no_license
chends888/Supercomp
a63c1ed2c1fcd47e92afede746a8989caacd4fc0
6945df1eaf0a5c1d39bb6e41be88c854a81a7a7b
refs/heads/master
2020-07-02T07:15:02.230867
2019-10-03T15:36:54
2019-10-03T15:36:54
201,453,573
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
hpp
#ifndef EXPERIMENT_H #define EXPERIMENT_H #include <iostream> #include <random> #include <math.h> #include <chrono> #include <tuple> #include <vector> class Experiment { public: std::vector<double> vec1; int n; Experiment(int size) { n = size; generate_input(); std::cout << "Test object and matrix created!\n"; } double duration; void generate_input(); double get_duration(); virtual void experiment_code(); std::pair<double, double> run(); operator double() { return duration; } bool operator < (Experiment &exper) { if ((this->duration < exper.duration) && (this->n == exper.n)) { return true; } else { return false; } } bool operator < (double testnum) { if (this->duration < testnum) { return true; } else { return false; } } }; #endif
[ "lchends@gmail.com" ]
lchends@gmail.com
7a355bb0e23c444d2a631e11cff48a6fd1784470
ab4022bac74247a770a5ff629637ed1c4b592aef
/LeetCode/maps/P1160.cpp
1ec621f771984fd4b07f974a45c15bd119ea9378
[]
no_license
zcfang/Playground
6b723697fe6f6a186fa768c7debefb0a6998b249
05954fba1063a9398d27994e54d98adc6d3d5165
refs/heads/master
2021-07-01T20:18:09.515734
2020-10-14T03:43:43
2020-10-14T03:43:43
178,296,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cpp
#include <string> #include <vector> #include <unordered_map> #include <assert.h> /** * Problem from LeetCode 1160: Find Words That Can Be Formed by Characters. * You can find the problem * <a href="https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/"> * here</a>. * * @param[in] words: A vector of words * @param[in] chars: A string of characters * @returns A string is good if it can be formed by characters from chars * (each character can only be used once). Return the sum of lengths of all * good strings in words. */ int count_characters(std::vector<std::string> &words, std::string chars); int main(int argc, char const *argv[]) { std::vector<std::string> words = {"cat","bt","hat","tree"}; std::string chars = "atach"; assert(count_characters(words, chars) == 6); return 0; } int count_characters(std::vector<std::string> &words, std::string chars) { int output = 0; std::unordered_map<char, int> char_count; for (const char character : chars) { char_count[character]++; } for (const std::string word : words) { std::unordered_map<char, int> letters = char_count; for (std::size_t i = 0; i < word.size(); i++) { if (!letters.count(word[i])) { break; } else if (letters[word[i]] == 0) { break; } else if (i == word.size() - 1) { output += word.size(); } else { letters[word[i]]--; } } letters = char_count; } return output; }
[ "zhongcfang@gmail.com" ]
zhongcfang@gmail.com
dcec713fce76de0dd483f6c45d9b31791fa6cd6f
8d4dd77dc7f0b55e37365d62b2774d7cdaebc1b8
/source/MicroBitSounder.cpp
aec6f3df6b90b1062560de1eb8d6781e63576db9
[ "MIT" ]
permissive
KevinNapper/FreenoveMicroRover
5ba4c7c38acb873645502e819fa893676d047f46
a9641ca48f25029d39600441707655b1f805f6d1
refs/heads/master
2020-12-02T04:50:21.047116
2020-02-09T12:36:37
2020-02-09T12:36:37
230,893,788
1
0
MIT
2020-02-09T11:42:42
2019-12-30T10:13:50
C++
UTF-8
C++
false
false
1,576
cpp
/* MIT License Copyright (c) 2019 Kevin Napper Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "MicroBitSounder.h" #include "MicroBitFiber.h" MicroBitSounder::MicroBitSounder(MicroBitPin& pin) : pin(pin) { } int MicroBitSounder::Play(int frequency, int duration_ms) { if (frequency <= 0) { pin.setAnalogValue(0); } else { pin.setAnalogValue(512); pin.setAnalogPeriodUs(1000000/frequency); } if (duration_ms > 0) { fiber_sleep(duration_ms); pin.setAnalogValue(0); wait_ms(5); } return 0; }
[ "kevin.napper@ntlworld.com" ]
kevin.napper@ntlworld.com
dcb7997c5d709f8d87852b3d6613a69b848f1a6d
991c6eb48d83e1612821b777fb7a136c469b10ce
/ToothBrushGame/Classes/VirusTooth.h
111b6444846797d3abf12641215531d467394565
[]
no_license
sutaa12/BrushToothGame
2ae5aee46669072d4012b4601d87d1ded9294111
7c40498faa1b117fab7472151dfa21831ee63a71
refs/heads/master
2016-09-06T17:52:56.917126
2015-03-23T08:18:32
2015-03-23T08:18:32
25,025,103
0
1
null
2015-03-23T08:18:32
2014-10-10T07:29:47
C++
UTF-8
C++
false
false
1,286
h
// // VirusTooth.h // ToothBrushGame // // Created by 鈴木 愛忠 on 2014/10/28. // // #ifndef __ToothBrushGame__VirusTooth__ #define __ToothBrushGame__VirusTooth__ #include "cocos2d.h" #include "TextureFile.h" #include "AchievementDataBase.h" using namespace cocos2d; class VirusTooth { public: VirusTooth(); //コンストラクタ ~VirusTooth(); //デストラクタ bool init(); //初期設定 void uninit(); // void update(); //更新 void disappear(); //消滅 static VirusTooth* create(const Vec2& pos = Vec2(0.0f,0.0f)); Sprite* getSprite(void){return m_pSprite;} bool getDisapper(void){return m_bDeath;} //行動選択関数 void choiceAction(void); //位置を画像に適用 void refreshSpritePos(void){m_pSprite->setPosition(m_pos);} //出現 void setSpawn(Vec2 pos); //倒れたフラグを拾う bool getVirusToothDownFlag(void){return m_bDown;} private: Sprite* m_pSprite; Vec2 m_pos; //時間 int m_time; //行動状態 int m_actionMode; //敵が倒れたフラグ bool m_bDown; //生きてるか死んでるかのフラグ bool m_bDeath; //定数 public: }; #endif /* defined(__ToothBrushGame__VirusTooth__) */
[ "snaritada@gmail.com" ]
snaritada@gmail.com
305776c362ccbc3afdf75dcf64f554b70ada8045
79c9ab2cf119c106c3c42353e766750bbcf497fa
/hdu/4913.cpp
b5ee31ff524bf99f41f44ebfe34d3cf5bc57acb1
[]
no_license
cen5bin/Algorithm-Problem
12e17dd300f69fd8121ea3f5be2f1d1a61cb3485
00099428c1b4199f3a6dc286c43e91acf94c58b0
refs/heads/master
2021-01-17T13:35:00.819979
2016-11-30T03:05:49
2016-11-30T03:05:49
22,202,801
1
1
null
null
null
null
UTF-8
C++
false
false
3,535
cpp
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N = 100010; struct point { LL a, b; int x; }p[N]; LL exp_mod(LL a, LL b, LL c) { LL ret = 1; while (b) { if (b & 1) ret = ret * a % c; a = a * a % c; b >>= 1; } return ret; } const LL MOD = 1000000000+7; int add[N<<2], cnt[N<<2]; LL sum[N<<2]; void push_down(int rt) { if (add[rt] == 0) return; sum[rt<<1] = sum[rt<<1] * exp_mod(2, add[rt], MOD) % MOD; sum[rt<<1|1] = sum[rt<<1|1] * exp_mod(2, add[rt], MOD) % MOD; add[rt<<1] += add[rt]; add[rt<<1|1] += add[rt]; add[rt] = 0; } void push_up(int rt) { sum[rt] = (sum[rt<<1] + sum[rt<<1|1]) % MOD; cnt[rt] = cnt[rt<<1] + cnt[rt<<1|1]; } void build(int l, int r, int rt) { sum[rt] = add[rt] = cnt[rt] = 0; if (l == r) return; int mid = (l + r) >> 1; build(l, mid, rt<<1); build(mid+1, r, rt<<1|1); } void update1(LL v, LL a, int p, int l, int r, int rt) { if (l == r) { sum[rt] = (sum[rt] + v * exp_mod(2, a, MOD) % MOD ) % MOD; cnt[rt]++; return; } push_down(rt); int mid = (l + r) >> 1; if (p <= mid) update1(v, a, p, l, mid, rt<<1); else update1(v, a, p, mid+1, r, rt<<1|1); push_up(rt); } void update2(int v, int L, int R, int l, int r, int rt) { if (L <= l && R >= r) { add[rt] += v; sum[rt] = sum[rt] * exp_mod(2, v, MOD) % MOD; return; } push_down(rt); int mid = (l + r) >> 1; if (L <= mid) update2(v, L, R, l, mid, rt<<1); if (R > mid) update2(v, L, R, mid+1, r, rt<<1|1); push_up(rt); } int query1(int L, int R, int l, int r, int rt) { if (L <= l && R >= r) return cnt[rt]; int mid = (l + r) >> 1; int ret = 0; if (L <= mid) ret += query1(L, R, l, mid, rt<<1); if (R > mid) ret += query1(L, R, mid+1, r, rt<<1|1); return ret; } LL query2(int L, int R, int l, int r, int rt) { if (L <= l && R >= r) return sum[rt]; push_down(rt); int mid = (l + r) >> 1; LL ret = 0; if (L <= mid) ret = query2(L, R, l, mid, rt<<1); if (R > mid) ret = (ret + query2(L, R, mid+1, r, rt<<1|1)) % MOD; return ret; } struct node { LL x; int id; }pp[N]; //pair<LL, int> pp[N]; int cmp(const node & p1, const node &p2) { return p1.x < p2.x; } int cmp2(const point &p1, const point &p2) { return p1.b < p2.b; } int main() { int n; while (scanf("%d", &n) == 1) { for (int i = 0; i < n; i++) { scanf("%lld%lld", &p[i].a, &p[i].b); pp[i].x = p[i].a; pp[i].id = i; } sort(pp, pp+n, cmp); int last = -1, cnt = 0; for (int i = 0; i < n; i++) { if (pp[i].x != last) cnt++; p[pp[i].id].x = cnt; last = pp[i].x; } sort(p, p+n, cmp2); build(1, cnt, 1); LL ans = 0; for (int i = 0; i < n; i++) { int tmp1 = query1(1, p[i].x, 1, cnt, 1); ans = (ans + exp_mod(2, p[i].a, MOD) * exp_mod(3, p[i].b, MOD) % MOD * exp_mod(2, tmp1, MOD) % MOD) % MOD; LL tmp2 = query2(p[i].x, cnt, 1, cnt, 1); ans = (ans + tmp2 * exp_mod(3, p[i].b, MOD) % MOD) % MOD; update1(1, p[i].a, p[i].x, 1, cnt, 1); update2(1, p[i].x, cnt, 1, cnt, 1); } printf("%lld\n", ans); } return 0; }
[ "wubincen@vm.(none)" ]
wubincen@vm.(none)
8c15f6386898612286c39759402978ef819ff90b
1e9ba268815b7cd908006a45940fbe1043df5755
/src/apps/grypto_rng/coinflipper.h
b705105af79b06490f1b4395a9322cc04803dcca
[ "Apache-2.0" ]
permissive
karagog/Gryptonite
41501c5f36deb2b9c02bae56bc57f209cc755da7
e2d0ec0761d81568d41ab4bc13a6bcdfce77a0a1
refs/heads/master
2021-06-03T02:07:27.346582
2019-09-15T03:10:00
2019-09-15T03:54:10
23,114,233
16
2
null
null
null
null
UTF-8
C++
false
false
1,265
h
/*Copyright 2015 George Karagoulis 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 COINFLIPPER_H #define COINFLIPPER_H #include "coinmodel.h" #include <gutil/qt_settings.h> #include <QWidget> #include <QProgressDialog> namespace Ui { class coinflipper; } class CoinModel; class CoinFlipper : public QWidget { Q_OBJECT public: explicit CoinFlipper(QWidget *parent = 0); ~CoinFlipper(); void SaveParameters(GUtil::Qt::Settings *) const; void RestoreParameters(GUtil::Qt::Settings *); private slots: void _flip(); void _clear(); void _progress_updated(int); private: Ui::coinflipper *ui; CoinModel *m_model; QProgressDialog m_pd; void _update(); void _set_controls_enabled(bool); }; #endif // COINFLIPPER_H
[ "karagog@gmail.com" ]
karagog@gmail.com
03a28e5dc7d4755669e0f3a958fec88dc42a38ae
d6face59a153b062f1a86b75fc377fdb5f5a52d4
/src/cobalt/bindings/generated/v8c/testing/cobalt/bindings/testing/v8c_disabled_interface.h
7b3ad3de8f6f76e1fd9c8718c12de3850aa82913
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
blockspacer/cobalt-clone-28052019
27fd44e64104e84a4a72d67ceaa8bafcfa72b4a8
b94e4f78f0ba877fc15310648c72c9c4df8b0ae2
refs/heads/master
2022-10-26T04:35:33.702874
2019-05-29T11:07:12
2019-05-29T11:54:58
188,976,123
0
2
null
2022-10-03T12:37:17
2019-05-28T07:22:56
null
UTF-8
C++
false
false
1,953
h
// Copyright 2019 The Cobalt 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. // clang-format off // This file has been auto-generated by bindings/code_generator_cobalt.py. DO NOT MODIFY! // Auto-generated from template: bindings/v8c/templates/interface.h.template #ifndef V8cDisabledInterface_h #define V8cDisabledInterface_h // This must be included above the check for NO_ENABLE_CONDITIONAL_INTERFACE, since // NO_ENABLE_CONDITIONAL_INTERFACE may be defined within. #include "cobalt/bindings/shared/idl_conditional_macros.h" #if defined(NO_ENABLE_CONDITIONAL_INTERFACE) #include "base/containers/hash_tables.h" #include "base/lazy_instance.h" #include "base/memory/ref_counted.h" #include "base/threading/thread_checker.h" #include "cobalt/base/polymorphic_downcast.h" #include "cobalt/script/wrappable.h" #include "cobalt/bindings/testing/disabled_interface.h" #include "cobalt/script/v8c/v8c_global_environment.h" #include "v8/include/v8.h" namespace cobalt { namespace bindings { namespace testing { class V8cDisabledInterface { public: static v8::Local<v8::Object> CreateWrapper(v8::Isolate* isolate, const scoped_refptr<script::Wrappable>& wrappable); static v8::Local<v8::FunctionTemplate> GetTemplate(v8::Isolate* isolate); }; } // namespace testing } // namespace bindings } // namespace cobalt #endif // defined(NO_ENABLE_CONDITIONAL_INTERFACE) #endif // V8cDisabledInterface_h
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
24cf5d3d53f3ae9c91446bda261b93107002f4ba
55b3b381500167017e0661e7230344e2a2f0c423
/hw-kim503/hw3/parser.cpp
a4249da6814f0e4b51b46394e5edc5adb212057b
[]
no_license
san-kim/CS-104-2018
c4c256757763620f07be2a550e72b88bded9abcc
c4756462b5cad095762d8248fb0675938c49c430
refs/heads/master
2020-04-16T22:35:15.790170
2019-01-16T04:50:54
2019-01-16T04:50:54
165,974,954
0
0
null
null
null
null
UTF-8
C++
false
false
13,538
cpp
#include <iostream> #include <fstream> #include <sstream> #include <string> #include "stackint.h" using namespace std; int valueInParenthesis(StackInt& stack); bool is_integer(char input); bool is_operator(char input); int operator_to_int(char input); bool isOnlyWhiteSpace(string equation); int main(int argc, char* argv[]) { if(argc != 2) { return 1; } ifstream ifile(argv[1]); if(ifile.fail()) { return 1; } string equation = ""; while(getline(ifile, equation)) { //instantiate stack used for this equation line StackInt stack; //if it is an empty line if(equation.size() == 0) { continue; } bool onlyWhiteSpace = isOnlyWhiteSpace(equation); if(onlyWhiteSpace) { //ignore the line that is just whitespace continue; } //give the getline to a stringstream stringstream ss; ss << equation; //read each character by element, find later whether it's int or +/* char element; // for if it was Malformed within this inner while loop bool broken = false; //while it can read elements, aka read until it can't while(ss >> element) { //ignore whitespace if(isspace(element)) { continue; } //if we read something that is neither an integer nor an operator if(is_integer(element)==false && is_operator(element)==false) { cout << "Malformed" << endl; broken = true; break; } //at this point onwards the element is either an integer or //an operator if the element read is an integer value if(is_integer(element)) { //integer reader reads every new digit as its new ones value int IntegerInput = (int)element - '0'; //to check the next element whether it is an int or not ss >> element; //if it fails, the singular number was the last int value if(ss.fail()) { stack.push(IntegerInput); break; } //to break the larger loop in the while below bool integerEndsInput = false; //keep reading until element is not an integer while(is_integer(element)) { //multiply the previous value by 10 and add new value IntegerInput = IntegerInput*10 + ((int)element - '0'); ss >> element; //where an integer ends getline & is last thing but longer //than one number long, integerEndsInput breaks 2nd while if(ss.fail()) { integerEndsInput = true; stack.push(IntegerInput); break; } } //case where int ends the line, should go to next line, //integer has been pushed already if(integerEndsInput) { break; } //regular case stack.push(IntegerInput); } //this operation above will read in one extra element if succeeds //works even if the if reads an extra element, unless it ended if(is_operator(element) == true) { int operatorToint = operator_to_int(element); stack.push(operatorToint); //if our input is a closed parenthsis if(operatorToint == operator_to_int(')')) { //will do the popping within the function //this will check whether there are too many ')'s int result = valueInParenthesis(stack); if(result == -1) { cout << "Malformed" << endl; broken = true; break; } //the valueInParenthesis function will pop everything from ) //to ( and return the result if it is not malformed. else { stack.push(result); } } } } //if it was malformed within inner while loop, skip to next eq if(broken) { continue; } //When we get to here, SHOULD have only shifts and our integer result //from all our paren ops, we took care of every ) as it came in // any open parenthesis, +, or * should be counted as a malformation int answer = -10000; //our top of the stack SHOULD ALWAYS be an integer //result of all of the paren ops if there were any if(!(stack.top() >= 0) ) { cout << "Malformed" << endl; //to next equation continue; } if(stack.top() >= 0) { answer = stack.top(); } //last integer is stored in "answer", now pop to see if anything after stack.pop(); //if it was only thing in the stack //SUCCESS!!! if(stack.empty()) { cout << answer << endl; continue; } //for if we find a malformation in this while loop bool brokeAgain = false; while(!stack.empty()) { //there should be NO more open parens, +, *, or Integers left if(stack.top() == -1 || stack.top() == -3 || stack.top() == -4 || stack.top() >= 0) { cout << "Malformed" << endl; brokeAgain = true; break; } //if there is a legal leftshift found on top of stack else if(stack.top() == operator_to_int('<')) { stack.pop(); answer = answer*2; //if consuming < finishes the eq legally & empties the stack, // SUCCESS!!!!!, ex: "<<(1+2+3+4)" -> "<<10" -> "<<" = "<" = 40 if(stack.empty()) { cout << answer << endl; brokeAgain = true; break; } } //if there is a legal rightshift found on top of stack else if(stack.top() == operator_to_int('>')) { stack.pop(); answer = answer/2; //if consuming a > finishes the eq legally & empties the stack, // SUCCESS!!!!! if(stack.empty()) { cout << answer << endl; brokeAgain = true; break; } } //these if's should cover all cases so if top is anything else, malform else { cout << "Malformed" << endl; brokeAgain = true; break; } } //this while loop should succeed and break or malform and break at this //point as we already consumed the parenthetical right most result & we //are just doing shift operations and checking whether any malformed +, // (, *, or integers remain. in the case where it malformed or succeeded // within above while loop if(brokeAgain) { continue; } } return 0; } //do operations within parenthesis when a ')' is found //will be called for the first ')' found, shouldnt have any ()'s in them' int valueInParenthesis(StackInt& stack) { //pop the closed parenthesis, this should always be true when called if(stack.top() == operator_to_int(')')) { stack.pop(); } //if it is the case that it is empty () if(stack.top() == operator_to_int('(')) { stack.pop(); return -1; } //missing open parenthesis, malformed if(stack.empty()) { return -1; } bool isRightmostElement = true; bool isFirstOperator = true; // checks that one exists and is consistent thru the parenthesis int operatorType = -100; int result = -10; //keep looping until it finds an ( or errors while(stack.top() != operator_to_int('(')) { //element is current reading element, stack.top() is the next one after pop int element; if(isRightmostElement) { element = stack.top(); stack.pop(); } //also if it goes to empty without succeeding, means failure if(stack.empty() == true) { return -1; } //if this is the first, rightmost element being read if(isRightmostElement) { if(!(element >= 0)) { //if it is not an integer, malformed return -1; } //if integer was the only thing in the parens ex:(123), malformed if(stack.top() == operator_to_int('(')) { return -1; } isRightmostElement = false; result = element; //set result for the first time //if the very rightmost integer has shifts right after it //we just increment result here, is just the first integer shifted while(stack.top() == -5 || stack.top() == -6) { if(stack.top() == operator_to_int('<')) { //if shift left //pop the shift operand, the integer element already popped stack.pop(); //missing open parenthesis, malformed: ex <<3) if(stack.empty() == true) { return -1; } result = result*2; //multiply result by 2 to keep track } //if shift right if(stack.top() == operator_to_int('>')) { //pop the shift operand, the integer element already popped stack.pop(); //missing open parenthesis, malformed: ex >>3) if(stack.empty() == true) { return -1; } result = result/2; //divide result by 2 to keep track } } //result is shifted (if is the case) first rightmost integer //if it is the case that input is something like (<<8) if(stack.top() == operator_to_int('(')) { return -1; } //if it is the case that (5>>4) if(stack.top() >= 0) { return -1; } } //if it is the first + or *, store to error check for mixing operators if(isFirstOperator && (stack.top() == -3 || stack.top() == -4)) { operatorType = stack.top(); isFirstOperator = false; } //we now know there is an integer at rightmost part of the eq in parens //after second iteration we should know the operator element = stack.top(); stack.pop(); if(stack.empty() == true) { return -1; } //from here on out, we will want to read OPERATOR and Integer pairs with //which we append its output to result so our current "element" is //should always be an operand after the first element, ALL new inputs //should now be operands + or * if(!isRightmostElement && element != -3 && element != -4) { return -1; } if(element == -3 || element == -4) { //if + or * //if the next element is NOT an integer or at the end at (, //then malformed in all cases as (+5) and (5++4) will be malformed //we already popped element, so the next element is just stack.top() if(stack.top() == operator_to_int('(') || !(stack.top() >= 0)) { return -1; } //if the operator is not the first one, mixing operators, malformed if(element != operatorType) { return -1; } //regular cases where it is of legal usage (finally)where the next //element after the operator is an integer, top is an int //if it is PLUS if(element == -3) { int addend = stack.top(); stack.pop(); //pop the addend //missing open parenthesis, malformed: ex 3+6) if(stack.empty() == true) { return -1; } //if the addend has shift(s) after it while(stack.top() == -5 || stack.top() == -6) { //if shift left if(stack.top() == operator_to_int('<')) { stack.pop(); //pop the shift operand //missing open parenthesis, malformed: ex <<3+6) if(stack.empty() == true) { return -1; } addend = addend*2; } if(stack.top() == operator_to_int('>')) { //if shift right stack.pop(); //pop the shift operand //missing open parenthesis, malformed: ex >>3+6) if(stack.empty() == true) { return -1; } addend = addend/2; } } //if is case that (5>>4+9) 9,+ consumed, (5>>4) -> (5) malformed //stack.top() SHOULD BE OPERATOR namely + here or ( if finished if(stack.top() >= 0) { return -1; } //if it is the legal end if(stack.top() == operator_to_int('(')) { stack.pop(); //pop the open parenthesis return result + addend; } //if there is another + operation after that //if it is *, will return -1 next iteration if(stack.top() == operator_to_int('+')) { result = result + addend; } } //if it is MULTIPLY else if(element == -4) { int multiplicand = stack.top(); stack.pop(); //pop the multiplicand //missing open parenthesis, malformed: ex 3*6) if(stack.empty() == true) { return -1; } //if the multiplicand has shift(s) after it while(stack.top() == -5 || stack.top() == -6) { if(stack.top() == operator_to_int('<')) { //if shift left stack.pop();//pop the shift operand //missing open parenthesis, malformed: ex <<3*6) if(stack.empty() == true) { return -1; } multiplicand = multiplicand*2; } //if shift right if(stack.top() == operator_to_int('>')) { //pop the shift operand, integer already popped at start stack.pop(); //missing open parenthesis, malformed: ex >>3*6) if(stack.empty() == true) { return -1; } multiplicand = multiplicand/2; } } //if case that (5>>4*9) 9,*,(5>>4),>>4 consumed,(5)malformed //stack.top() SHOULD BE OPERATOR namely * here or ( if finished if(stack.top() >= 0) { return -1; } //if it is the legal end if(stack.top() == operator_to_int('(')) { stack.pop(); //pop the open parenthesis return result * multiplicand; } //if there is another * operation after that //if it is +, will return -1 next iteration if(stack.top() == operator_to_int('*')) { result = result * multiplicand; } } } } return -1; //assume malformed if it got to here? } //returns true if the char input is an integer between 0-9 bool is_integer(char input) { if((int)input - '0' >= 0 && (int)input - '0' <= 9) { return true; } return false; } //returns true is the input is one of our bool is_operator(char input) { if(input == '<' || input == '>' || input == '(' || input == ')' || input == '+' || input == '*') { return true; } return false; } int operator_to_int(char input) { if(input == '(') { return -1; } else if(input == ')') { return -2; } else if(input == '+') { return -3; } else if(input == '*') { return -4; } else if(input == '<') { return -5; } else if(input == '>') { return -6; } //error case else { return -100; } } //if the equation is only whitespace, return true. bool isOnlyWhiteSpace(string equation) { for(unsigned int i = 0; i<equation.size(); i++) { //if it is not a whitespace, return false if(!(isspace(equation[i]))) { return false; } } return true; }
[ "kim503@usc.edu" ]
kim503@usc.edu
1bdd206effcfb6f4babcedf8b74700298377ffa3
f5f750efbde0ccd95856820c975ec88ee6ace0f8
/aws-cpp-sdk-directconnect/include/aws/directconnect/model/ConfirmPublicVirtualInterfaceRequest.h
6c17c579493d1ff7115e50be7241257bcaaff815
[ "JSON", "MIT", "Apache-2.0" ]
permissive
csimmons0/aws-sdk-cpp
578a4ae6e7899944f8850dc37accba5568b919eb
1d0e1ddb51022a02700a9d1d3658abf628bb41c8
refs/heads/develop
2020-06-17T14:58:41.406919
2017-04-12T03:45:33
2017-04-12T03:45:33
74,995,798
0
0
null
2017-03-02T05:35:49
2016-11-28T17:12:34
C++
UTF-8
C++
false
false
2,497
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/directconnect/DirectConnect_EXPORTS.h> #include <aws/directconnect/DirectConnectRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace DirectConnect { namespace Model { /** * <p>Container for the parameters to the ConfirmPublicVirtualInterface * operation.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ConfirmPublicVirtualInterfaceRequest">AWS * API Reference</a></p> */ class AWS_DIRECTCONNECT_API ConfirmPublicVirtualInterfaceRequest : public DirectConnectRequest { public: ConfirmPublicVirtualInterfaceRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; inline const Aws::String& GetVirtualInterfaceId() const{ return m_virtualInterfaceId; } inline void SetVirtualInterfaceId(const Aws::String& value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId = value; } inline void SetVirtualInterfaceId(Aws::String&& value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId = value; } inline void SetVirtualInterfaceId(const char* value) { m_virtualInterfaceIdHasBeenSet = true; m_virtualInterfaceId.assign(value); } inline ConfirmPublicVirtualInterfaceRequest& WithVirtualInterfaceId(const Aws::String& value) { SetVirtualInterfaceId(value); return *this;} inline ConfirmPublicVirtualInterfaceRequest& WithVirtualInterfaceId(Aws::String&& value) { SetVirtualInterfaceId(value); return *this;} inline ConfirmPublicVirtualInterfaceRequest& WithVirtualInterfaceId(const char* value) { SetVirtualInterfaceId(value); return *this;} private: Aws::String m_virtualInterfaceId; bool m_virtualInterfaceIdHasBeenSet; }; } // namespace Model } // namespace DirectConnect } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
67ea810f1b11eef2beec02a5d684b3c8877aa1a8
896b5a6aab6cb6c1e3ee2e59aad0128226471871
/third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h
5f126cbd735b1d74623051446f25b763fb88cbae
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
bkueppers/chromium
86f09d32b7cb418f431b3b01a00ffe018e24de32
d160b8b58d58120a9b2331671d0bda228d469482
refs/heads/master
2023-03-14T10:41:52.563439
2019-11-08T13:33:40
2019-11-08T13:33:40
219,389,734
0
0
BSD-3-Clause
2019-11-04T01:05:37
2019-11-04T01:05:37
null
UTF-8
C++
false
false
5,906
h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALLOCATOR_PARTITION_ALLOCATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALLOCATOR_PARTITION_ALLOCATOR_H_ // This is the allocator that is used for allocations that are not on the // traced, garbage collected heap. It uses FastMalloc for collections, // but uses the partition allocator for the backing store of the collections. #include <string.h> #include "base/allocator/partition_allocator/partition_alloc_constants.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/type_traits.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" namespace WTF { class PartitionAllocatorDummyVisitor { DISALLOW_NEW(); }; class WTF_EXPORT PartitionAllocator { public: typedef PartitionAllocatorDummyVisitor Visitor; static constexpr bool kIsGarbageCollected = false; template <typename T> static size_t MaxElementCountInBackingStore() { return base::kGenericMaxDirectMapped / sizeof(T); } template <typename T> static size_t QuantizedSize(size_t count) { CHECK_LE(count, MaxElementCountInBackingStore<T>()); return WTF::Partitions::BufferActualSize(count * sizeof(T)); } template <typename T> static T* AllocateVectorBacking(size_t size) { return reinterpret_cast<T*>( AllocateBacking(size, WTF_HEAP_PROFILER_TYPE_NAME(T))); } template <typename T> static T* AllocateExpandedVectorBacking(size_t size) { return reinterpret_cast<T*>( AllocateBacking(size, WTF_HEAP_PROFILER_TYPE_NAME(T))); } static void FreeVectorBacking(void* address); static inline bool ExpandVectorBacking(void*, size_t) { return false; } static inline bool ShrinkVectorBacking(void* address, size_t quantized_current_size, size_t quantized_shrunk_size) { // Optimization: if we're downsizing inside the same allocator bucket, // we can skip reallocation. return quantized_current_size == quantized_shrunk_size; } template <typename T, typename HashTable> static T* AllocateHashTableBacking(size_t size) { return reinterpret_cast<T*>( AllocateBacking(size, WTF_HEAP_PROFILER_TYPE_NAME(T))); } template <typename T, typename HashTable> static T* AllocateZeroedHashTableBacking(size_t size) { void* result = AllocateBacking(size, WTF_HEAP_PROFILER_TYPE_NAME(T)); memset(result, 0, size); return reinterpret_cast<T*>(result); } static void FreeHashTableBacking(void* address); template <typename Return, typename Metadata> static Return Malloc(size_t size, const char* type_name) { return reinterpret_cast<Return>( WTF::Partitions::FastMalloc(size, type_name)); } static inline bool ExpandHashTableBacking(void*, size_t) { return false; } static void Free(void* address) { WTF::Partitions::FastFree(address); } template <typename T> static void* NewArray(size_t bytes) { return Malloc<void*, void>(bytes, WTF_HEAP_PROFILER_TYPE_NAME(T)); } static void DeleteArray(void* ptr) { Free(ptr); // Not the system free, the one from this class. } static void TraceMarkedBackingStore(void*) {} static void BackingWriteBarrier(void*) {} static void BackingWriteBarrier(void*, size_t) {} template <typename> static void BackingWriteBarrierForHashTable(void*) {} static bool IsAllocationAllowed() { return true; } static bool IsObjectResurrectionForbidden() { return false; } static bool IsSweepForbidden() { return false; } static void EnterGCForbiddenScope() {} static void LeaveGCForbiddenScope() {} template <typename T, typename Traits> static void NotifyNewObject(T* object) {} template <typename T, typename Traits> static void NotifyNewObjects(T* array, size_t len) {} private: static void* AllocateBacking(size_t, const char* type_name); }; // Specializations for heap profiling, so type profiling of |char| is possible // even in official builds (because |char| makes up a large portion of the // heap.) template <> WTF_EXPORT char* PartitionAllocator::AllocateVectorBacking<char>(size_t); template <> WTF_EXPORT char* PartitionAllocator::AllocateExpandedVectorBacking<char>( size_t); } // namespace WTF #define USE_ALLOCATOR(ClassName, Allocator) \ public: \ void* operator new(size_t size) { \ return Allocator::template Malloc<void*, ClassName>( \ size, WTF_HEAP_PROFILER_TYPE_NAME(ClassName)); \ } \ void operator delete(void* p) { Allocator::Free(p); } \ void* operator new[](size_t size) { \ return Allocator::template NewArray<ClassName>(size); \ } \ void operator delete[](void* p) { Allocator::DeleteArray(p); } \ void* operator new(size_t, NotNullTag, void* location) { \ DCHECK(location); \ return location; \ } \ void* operator new(size_t, void* location) { return location; } \ \ private: \ typedef int __thisIsHereToForceASemicolonAfterThisMacro #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALLOCATOR_PARTITION_ALLOCATOR_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
563f2afee90ee0513817c2c69c507a7ced9f5ddf
67f865009c64a37261e85e6e6b44009c3883f20f
/cau_truc_du_lieu_giai_thuat/homework/chapter1/menu.cpp
2eec00a3c48b4947a4ac5a32ddfe3254deedad32
[]
no_license
tabvn/ued
762a25ff68042ff8b77b6f307f3182f3713e5f31
005b07c4f9924247b819d9611f84a80c8938fb21
refs/heads/master
2021-07-10T06:49:21.535462
2020-06-28T07:53:57
2020-06-28T07:53:57
153,631,981
0
0
null
null
null
null
UTF-8
C++
false
false
13,653
cpp
#include <iostream> #include <math.h> #ifdef _WIN32 #include "windows.h" #include <conio.h> #endif using namespace std; #ifdef _WIN32 void gotoxy(int x, int y) { COORD cur = {x, y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur); } #else char getch() { } void gotoxy(int x, int y) { printf("\033[%dG\033[%dd", x + 1, y + 1); } #endif int textcolor(int Color) { #ifdef _WIN32 HANDLE h; h = GetStdHandle(STD_OUTPUT_HANDLE); return SetConsoleTextAttribute(h, Color); #endif } #define CYAN 10 #define YELLOW 14 int n = 0, m = 0, A[50], B[50]; int KTra(int x, int n, int A[]) { for (int i = 0; i < n; i++) if (x == A[i]) return 1; return 0; } void Insert(int x, int &n, int A[]) { if (KTra(x, n, A) == 0) { A[n] = x; n++; } } void View(int n, int A[]) { cout << "\n"; for (int i = 0; i < n; i++) cout << A[i] << " "; } void Bosung(int &n, int A[]) { char ch; int x; do { cout << "\nNhap x= "; cin >> x; Insert(x, n, A); cout << "\nNhan <ESC> de ket thuc nhap!"; #ifdef _WIN_32 ch = getch(); #endif } while (ch != 27); } int Tong(int n, int a[]) { if (n == 0) return 0; else return a[n] + Tong(n - 1, a); } void Nhap(int &n, int a[]) { cout << endl << "Nhap n = "; cin >> n; for (int i = 1; i <= n; i++) { cout << endl << "A[" << i << "]="; cin >> a[i]; } } void Baitap7() { system("cls"); cout << endl << "Tinh tong mang"; int n, a[100]; Nhap(n, a); cout << endl << "Tong mang = " << Tong(n, a); getch(); } //Viet xau s ra man hinh tai toa do (x,y) voi mau la color void Write(char *s, int x, int y, int color) { textcolor(color); gotoxy(x, y); cout << s; textcolor(15); } void Khung(int x1, int y1, int x2, int y2) { int x, y; gotoxy(x1, y1); cout << "É"; gotoxy(x2, y1); cout << "»"; gotoxy(x1, y2); cout << "È"; gotoxy(x2, y2); cout << "¼"; for (x = x1 + 1; x < x2; x++) { gotoxy(x, y1); cout << "Í"; gotoxy(x, y2); cout << "Í"; } for (y = y1 + 1; y < y2; y++) { gotoxy(x1, y); cout << "º"; gotoxy(x2, y); cout << "º"; } } /*Tao ra menu tai toa do (x0,y0) voi n dong luu trong bien s chon: dong menu hien thoi (khac mau voi cac dong khac) */ void Ve_menu(int x0, int y0, int chon, int n, char *s[]) { system("cls"); Khung(x0 - 2, y0 - 1, x0 + 30, y0 + n); for (int i = 0; i < n; i++) if (i == chon) Write(s[i], x0, y0 + i, CYAN); else Write(s[i], x0, y0 + i, YELLOW); Write("Copyright (c) 2016 by Pham Anh Phuong.", x0 - 4, y0 + n + 5, 10); } // Bai Tap int ucln(int a, int b) { if (a == b) { return a; } if (a > b) { return ucln(a - b, b); } return ucln(a, b - a); } void baitap1() { int a, b; cout << "Nhap A: "; cin >> a; cout << "Nhap B: "; cin >> b; cout << ucln(a, b); } int count(int n) { int total = 0; while (n > 0) { n /= 10; total++; } return total; } int recusiveCount(int n, int total) { if (n == 0) { return total; } return recusiveCount(n / 10, total + 1); } void baitap2() { int n; cout << "Nhap so nguyen duong N: "; cin >> n; cout << "Dem theo cach khong de quy:" << count(n) << endl; cout << "Dem theo cach dung de quy: " << recusiveCount(n, 0); } long long fib(int n) { if (n <= 2) { return 1; } return fib(n - 1) + fib(n - 2); } void baitap3() { int n; cout << "Nhap n: "; cin >> n; cout << "Ket qua Fib(" << n << ") = " << fib(n); } long long ackermann(int m, int n) { if (m == 0) { return n + 1; } if (n == 0) { return ackermann(m - 1, 1); } return ackermann(m - 1, ackermann(m, n - 1)); } void baitap4() { int m, n; cout << "Nhap m: "; cin >> m; cout << "Nhap n: "; cin >> n; cout << "A(" << m << "," << n << ") = " << ackermann(m, n); } bool isP(string s, int left, int right){ if(s.size() ==1 || left >= right){ return true; } if(s[left] != s[right]){ return false; } return isP(s, left+1, right-1); } void baitap5(){ string s; cout << "Nhap chuoi can kiem tra: "; cin >> s; if(isP(s, 0 , s.size() -1)){ cout << "Chuoi doi xung"; }else{ cout << "Chuoi khong doi xung"; } } long long sum(int n){ long long s = 0; for (int i = 1; i <= n; ++i){ s+= i; } return s; } long long recursiveSum(int n){ if(n == 1){ return 1; } return n + recursiveSum(n-1); } void baitap6a(){ int n; cout << "Nhap N: "; cin >> n; cout << "ket qua khong dung de quy: " << sum(n) << endl; cout << "ket qua dung de quy: " << recursiveSum(n); } /* Tổng nghịch đảo dạng phân số */ struct PhanSo { long long tu,mau; PhanSo(long long tu, long long mau){ this->tu = tu; this->mau = mau; } long long gcd(long long a, long long b){ if(a %b == 0){ return b; } if(b%a == 0){ return a; } while(a != b){ if(a > b){ a = a-b; }else{ b = b -a; } } return a; } PhanSo operator + (const PhanSo &b){ // 1/2 + 1/3 long long tuSo, mauSo; tuSo = (this->tu * b.mau) + b.tu * this->mau; mauSo = this->mau * b.mau; long long uc = this->gcd(tuSo, mauSo); return PhanSo(tuSo/uc, mauSo/uc); } void print(){ cout << this->tu << "/" << this->mau; } }; void sum_b(int n){ PhanSo p(1,1); for (int i = 2; i <= n; ++i){ p = p + PhanSo(1, i); } p.print(); } PhanSo recurseSum(int n){ if(n == 1){ return PhanSo(1, 1); } return PhanSo(1, n) + recurseSum(n-1); } void baitap6b(){ int n; cout << "Nhap N: "; cin >> n; cout << "Tinh tong phan so khong dung de quy: "; sum_b(n); cout << endl; cout << "Tinh tong phan so dung de quy: "; PhanSo kq = recurseSum(n); kq.print(); } void sub(int n){ PhanSo p(1,1); for (int i = 2; i <= n; ++i){ p = p + PhanSo(1 * pow(-1, i+1), i); } p.print(); } PhanSo recurseSub(int n){ if(n == 1){ return PhanSo(1, 1); } return PhanSo(1 * pow(-1, n+1) , n) + recurseSub(n-1); } void baitap6c(){ int n; cout << "Nhap N: "; cin >> n; cout << "Ket qua khong dung de quy: "; sub(n); cout << endl; cout << "ket qua dung de quy: "; PhanSo kq = recurseSub(n); kq.print(); } long double *a; double toRadial(int x){ return x*3.14159265359/180; } long double p(double sinx, int n){ long double v = a[n]; if(v != -1){ return v; } v = 1; for (int i = 1; i <= n; ++i){ v*= sinx; a[i] = v; } return v; } long double tongSin(int n, double x){ long double s = 0; long double sinX = sin(x); for (int i = n; i >=0; --i){ long double v = a[i]; s+= p(sinX, i); } return s; } long double tongSinDequy(int n, double x){ if(n== 0){ return 1; } long double sinX = sin(x); return p(sinX, n) + tongSinDequy(n-1, x); } void baitap6d(){ int n; int x; cout << "Nhap N: "; cin >> n; // khoi tao mang cached a = new long double[n+1]; for (int i = 0; i <= n; ++i){ a[i] = -1; } cout << "Nhap X (degree): "; cin >> x; cout << "Ket qua khong dung de quy: " << tongSin(n,toRadial(x)) << endl; cout << "Ket qua dung de quy: " << tongSinDequy(n,toRadial(x)); } long long cn(int n, int k){ if(k==0 || n == k){ return 1; } return cn(n-1, k-1) + cn(n-1, k); } void baitap7(){ int n,k; cout << "Nhap N: "; cin >> n; cout << "Nhap K: "; cin >> k; cout << "Ket qua to hop chap k cua N la: " << cn(n, k); } int daoSo(int n){ int ds = 0; int tmp; while(n > 0){ tmp = n%10; ds = ds * 10 + tmp; n/= 10; } return ds; } int daoSoDequy(int n, int kq){ if(n == 0){ return kq; } return daoSoDequy(n/10, kq*10+n%10); } void baitap8(){ int n; cout << "Nhap vao N: "; cin >> n; cout << "So dao nguoc cua N: " << daoSo(n) << endl; cout << "So dao nguoc cua N dung de quy: " << daoSoDequy(n, 0); } int aa[8]; const int nn = 8; bool isOK(int x, int y){ for(int i = 1; i< x; i++ ){ if(aa[i] == y){ // chung cột return false; } if(abs(aa[i] - y) == abs(i-x)){ // duong cheo // cong thuc copy return false; } } return true; } void print(){ for (int i = 1; i <= nn; ++i){ cout << aa[i] << " "; } cout << endl; } void Try(int i){ for (int j = 1; j <= nn; ++j){ if(isOK(i, j)){ // dat tai hang i cot j aa[i] = j; if(i == nn){ print(); // in ra phuong an } Try(i+1); // tang hang len 1 } } } void baitap9(){ Try(1); } // Ket thuc bai tap int main() { char ch, *st[20]; system("cls"); st[0] = "B1: UCLN"; st[1] = "B2: Dem chu so"; st[2] = "B3: Fibonacci"; st[3] = "B4: Ackermann"; st[4] = "B5: So doi xung"; st[5] = "B6a: 1+2 +3+......+n"; st[6] = "B6b: 1+1/2 + .....+ 1/n "; st[7] = "B6c: 1-1/2+......"; st[8] = "B6d: 1 + sin(x)+..."; st[9] = "B7: To hop chap k cua N"; st[10] = "B8: Dao so"; st[11] = "B9: 8 quan hau"; const int end_index = 12; st[end_index] = "<ESC> Ket thuc chuong trinh!"; int x0 = 25, y0 = 10, chon = 0, luuchon, sodong = end_index + 1, ok = false; Ve_menu(x0, y0, chon, sodong, st); do { ch = getch(); //Nhan mot phim switch (ch) { case 72: //phim len luuchon = chon; chon--; if (chon < 0) chon = sodong - 1; Write(st[luuchon], x0, y0 + luuchon, YELLOW); Write(st[chon], x0, y0 + chon, CYAN); break; case 80://phim xuong luuchon = chon; chon++; if (chon == sodong) chon = 0; Write(st[luuchon], x0, y0 + luuchon, YELLOW); Write(st[chon], x0, y0 + chon, CYAN); break; case 13: //phim ENTER ok = true; break; default: break; } if (ok) //Neu phim ENTER duoc nhan { switch (chon) { case 0: system("cls"); baitap1(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 1: system("cls"); baitap2(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 2: system("cls"); baitap3(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 3: system("cls"); baitap4(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 4: system("cls"); baitap5(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 5: system("cls"); baitap6a(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 6: system("cls"); baitap6b(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 7: system("cls"); baitap6c(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 8: system("cls"); baitap6d(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 9: system("cls"); baitap7(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 10: system("cls"); baitap8(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case 11: system("cls"); baitap9(); getch(); Ve_menu(x0, y0, chon, sodong, st); break; case end_index: exit(0); default: break; } ok = false; //tra lai trang thai ENTER chua duoc nhan } } while (ch != 27);//Nhan phim ESC de thoat khoi chuong trinh return 0; }
[ "toan@tabvn.com" ]
toan@tabvn.com
519ae76b4c364aab00683067774a7f98ed56c2df
c7a67905085e002d407324cbdfd37eaf5df75f7e
/TilesBag.cpp
45ff6b427c26e95ad562f7eb568f2d2beed6ac48
[]
no_license
timalbpathirana/QWIRKLE-Board-Game-RMIT-University-GP-cpp
cf7eedf0aa941bbc87c2976459d71953d40ccdf2
4a8f040968c6864667f4d9f394dc04a7a7358607
refs/heads/master
2023-05-09T22:50:46.079165
2021-05-31T03:55:43
2021-05-31T03:55:43
372,376,417
0
0
null
null
null
null
UTF-8
C++
false
false
4,372
cpp
#include "TilesBag.h" #include "TileCodes.h" #include <iostream> #include <fstream> #include <random> #define MAX_NUM_OF_TILES_IN_HAND 6 // max number of tiles in player hand // the total number of tiles in the game TilesBag::TilesBag() { tiles = new LinkedList(); } TilesBag::~TilesBag() { delete tiles; } LinkedList* TilesBag::getTiles() { return tiles; } void TilesBag::setTiles(LinkedList* tiles) { this->tiles = tiles; } void TilesBag::shuffleBag(){ LinkedList* shuffledBag = new LinkedList(); std::random_device randomSeed; int i = 0; while (i < tiles->getSize()) { // Pick a random tile from the tilesbag std::uniform_int_distribution<int> uniform_dist(0, tiles->getSize() - 1); int randIndex = uniform_dist(randomSeed); if (tiles->getIndex(randIndex) != nullptr) { // move tiles to shuffled likedlist Tile* tile = new Tile(*tiles->getIndex(randIndex)); shuffledBag->addBack(tile); tiles->deleteIndex(randIndex); } } delete tiles; tiles = shuffledBag; } bool TilesBag::readOneTile(std::ifstream& file, char* colour, int* shape) { //read colour in char formate char readColour = 'R'; bool readSuccess = true; file >> readColour; // if(readColour == 'R'){ *colour = RED; }else if (readColour == 'O'){ *colour = ORANGE; }else if (readColour == 'Y'){ *colour = YELLOW; }else if (readColour == 'G'){ *colour = GREEN; }else if (readColour == 'B'){ *colour = BLUE; }else if (readColour == 'P'){ *colour = PURPLE; }else{ readSuccess = false; std::cout << "Incorrect color try again!" << std::endl; } //read shape in number formate int readShape = 1; file >> readShape; if(readShape == 1){ *shape = CIRCLE; }else if (readShape == 2){ *shape = STAR_4; }else if (readShape == 3){ *shape = DIAMOND; }else if (readShape == 4){ *shape = SQUARE; }else if (readShape == 5) {// *shape = STAR_6; }else if (readShape == 6){ *shape = CLOVER; }else{ readSuccess = false; std::cout << "Incorrect shape try again!" << std::endl; } return readSuccess; } void TilesBag::initBag(){ std::string tilesBagFileName = "TilesBag.txt"; std::ifstream file(tilesBagFileName); int numRead = 0; while(!file.eof() && numRead < NUM_OF_TILES) { char colour = 'R'; int shape = 1; bool readSuccess = false; readSuccess = readOneTile(file, &colour, &shape); if (!file.eof() && readSuccess) { Tile* tile = new Tile(colour, shape); tiles->addBack(tile); ++numRead; } } } void TilesBag::initBagForM3(){ std::string tilesBagFileName = "advancedTilesBag.txt"; std::ifstream file(tilesBagFileName); int numRead = 0; while(!file.eof() && numRead < NUM_OF_TILES_M3) { char colour = 'R'; int shape = 1; bool readSuccess = false; readSuccess = readOneTile(file, &colour, &shape); if (!file.eof() && readSuccess) { Tile* tile = new Tile(colour, shape); tiles->addBack(tile); ++numRead; } } } LinkedList* TilesBag::moveTileFromBagToPlayerHand(int numOfTiles) { LinkedList* playerHand = new LinkedList(); for (int i = 0; i < numOfTiles; i++) { playerHand->addBack(new Tile(*tiles->getIndex(i))); } for (int i = 0; i < numOfTiles; i++) { tiles->deleteFront(); } return playerHand; } void TilesBag::printBag() { for (int i = 0; i < tiles->getSize(); i++) { std::cout << "Tiles Bag: " << tiles->getIndex(i)->getColourCode() << tiles->getIndex(i)->getShapeCode() << std::endl; } } Tile* TilesBag::getAndRemoveRandom() { std::random_device randomSeed; std::uniform_int_distribution<int> uniform_dist(0, tiles->getSize() - 1); int randIndex = uniform_dist(randomSeed); Tile* takeOut = new Tile(*tiles->getIndex(randIndex)); tiles->deleteIndex(randIndex); return takeOut; }
[ "timalbathiya1995@gmail.com" ]
timalbathiya1995@gmail.com
f065be868481fd41583e5e85e3f56778f30bb61d
07b565803873e0a391e6e005d7a3d69b0c2d12d5
/problems/day20/solve.cpp
5d3a2069d1507d0fa94992417a4aa755e44c924b
[]
no_license
Mesoptier/advent-of-code-2019
6f1fdb38edfa0dd3446159b349cfa85be1e602d2
c46083214633973a5c6b16a2621ee2ce1de2bc73
refs/heads/master
2020-09-23T07:15:41.412225
2019-12-25T09:55:07
2019-12-25T09:55:07
225,436,235
3
0
null
null
null
null
UTF-8
C++
false
false
5,110
cpp
#include <set> #include <iostream> #include "solve.h" namespace Day20 { inline bool is_portal(char c) { return 'A' <= c && c <= 'Z'; } Direction reverse(Direction direction) { switch (direction) { case North: return South; case South: return North; case West: return East; case East: return West; } } int solve1(std::istream& input) { return solve(input, false); } int solve2(std::istream& input) { return solve(input, true); } int solve(std::istream& input, bool part2) { auto grid = parse_input(input); Coord start_coord; Coord goal_coord; // Maps coordinates in front of portals with the same label std::unordered_map<Coord, Coord> portals; // Whether the coordinates are in front of a portal on the outer edge std::unordered_map<Coord, bool> is_outer_edge; { // Temporary map for storing portals for which we haven't found the second one yet std::unordered_map<std::string, Coord> portals_tmp; for (auto kv : grid) { if (!is_portal(kv.second)) { continue; } auto n1 = kv.first; for (int i = 1; i <= 4; ++i) { auto dir = static_cast<Direction>(i); auto n2 = n1.step(dir); if (!grid.count(n2) || !is_portal(grid[n2])) { continue; } auto n3 = n2.step(dir); if (!grid.count(n3) || grid[n3] != '.') { continue; } auto c1 = kv.second; auto c2 = grid[n2]; std::string label; label += (dir == South || dir == East) ? c1 : c2; label += (dir == South || dir == East) ? c2 : c1; if (label == "AA") { start_coord = n3; continue; } if (label == "ZZ") { goal_coord = n3; continue; } if (portals_tmp.count(label)) { // This is the second portal with this label, resolve them portals[n3] = portals_tmp[label]; portals[portals_tmp[label]] = n3; } else { // First portal with this label portals_tmp[label] = n3; } // Abuse the fact that labels of portals on the outer edge also lie on the edge of the grid is_outer_edge[n3] = !grid.count(n1.step(reverse(dir))); } } } // BFS using Node = std::pair<Coord, int>; std::queue<Node> queue; std::unordered_map<Node, int> cost; const Node start_node = {start_coord, 0}; const Node goal_node = {goal_coord, 0}; queue.push(start_node); cost[start_node] = 0; while (!queue.empty()) { auto current = queue.front(); queue.pop(); if (current == goal_node) { return cost[current]; } std::vector<Node> neighbors; // Neighbors from just stepping into any of the four directions for (auto n : current.first.get_neighbors()) { neighbors.emplace_back(n, current.second); } // Neighbor from stepping through a portal if (portals.count(current.first)) { int level = current.second; if (part2) { // Only change levels in Part 2 if (is_outer_edge[current.first]) { --level; } else { ++level; } } neighbors.emplace_back(portals[current.first], level); } for (auto neighbor : neighbors) { // Skip walls and labels if (grid[neighbor.first] == '#' || is_portal(grid[neighbor.first])) { continue; } if (neighbor.second < 0) { continue; } if (cost.count(neighbor)) { continue; } cost[neighbor] = cost[current] + 1; queue.push(neighbor); } } } Grid<char> parse_input(std::istream& input) { Grid<char> grid; int x = 0; int y = 0; while (input.peek() != EOF) { char c = input.get(); if (c == '\n') { ++y; x = 0; continue; } grid[{x, y}] = c; ++x; } return grid; } }
[ "koen.klaren@gmail.com" ]
koen.klaren@gmail.com
6ef80f939a63e3b61831040160cb9b037f55e5b6
04b1803adb6653ecb7cb827c4f4aa616afacf629
/device/fido/ble/fido_ble_transaction.h
53ab4786bb908e6fbc33730079c94019fa4e9fc9
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,380
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_FIDO_BLE_FIDO_BLE_TRANSACTION_H_ #define DEVICE_FIDO_BLE_FIDO_BLE_TRANSACTION_H_ #include <memory> #include <vector> #include "base/component_export.h" #include "base/containers/queue.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/timer/timer.h" #include "device/fido/ble/fido_ble_frames.h" namespace device { class FidoBleConnection; // This class encapsulates logic related to a single U2F BLE request and // response. FidoBleTransaction is owned by FidoBleDevice, which is the only // class that should make use of this class. class COMPONENT_EXPORT(DEVICE_FIDO) FidoBleTransaction { public: using FrameCallback = base::OnceCallback<void(base::Optional<FidoBleFrame>)>; FidoBleTransaction(FidoBleConnection* connection, uint16_t control_point_length); ~FidoBleTransaction(); void WriteRequestFrame(FidoBleFrame request_frame, FrameCallback callback); void OnResponseFragment(std::vector<uint8_t> data); // Cancel requests that a cancelation command be sent if possible. void Cancel(); private: void WriteRequestFragment(const FidoBleFrameFragment& fragment); void OnRequestFragmentWritten(bool success); void ProcessResponseFrame(); void StartTimeout(); void StopTimeout(); void OnError(base::Optional<FidoBleFrame> response_frame); FidoBleConnection* connection_; uint16_t control_point_length_; base::Optional<FidoBleFrame> request_frame_; FrameCallback callback_; base::queue<FidoBleFrameContinuationFragment> request_cont_fragments_; base::Optional<FidoBleFrameAssembler> response_frame_assembler_; std::vector<uint8_t> buffer_; base::OneShotTimer timer_; bool has_pending_request_fragment_write_ = false; // cancel_pending_ is true if a cancelation should be sent after the current // set of frames has finished transmitting. bool cancel_pending_ = false; // cancel_sent_ records whether a cancel message has already been sent. bool cancel_sent_ = false; base::WeakPtrFactory<FidoBleTransaction> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FidoBleTransaction); }; } // namespace device #endif // DEVICE_FIDO_BLE_FIDO_BLE_TRANSACTION_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
d91f0149eede97a823d7f19c38975bd45c9ab5e0
211fcb30d2c0068d88074c646258b31e008fd32b
/AtCoder/etc/past201912/a.cpp
bfa9b048d8376879d083c1a94a8c64c73c4fcf3a
[]
no_license
makecir/competitive-programming
2f9ae58284b37fab9aed872653518089951ff7fd
be6c7eff4baf07dd19b50eb756ec0d5dc5ec3ebf
refs/heads/master
2021-06-11T08:10:17.375410
2021-04-13T11:59:17
2021-04-13T11:59:17
155,111,372
0
0
null
null
null
null
UTF-8
C++
false
false
2,098
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; using vb=vector<bool>; using vvb=vector<vb>; using vd=vector<double>; using vvd=vector<vd>; using vi=vector<int>; using vvi=vector<vi>; using vl=vector<ll>; using vvl=vector<vl>; using pii=pair<int,int>; using pll=pair<ll,ll>; using tll=tuple<ll,ll>; using tlll=tuple<ll,ll,ll>; using vs=vector<string>; #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define rep(i,n) range(i,0,n) #define rrep(i,n) for(int i=(n)-1;i>=0;i--) #define range(i,a,n) for(int i=(a);i<(n);i++) #define LINF ((ll)1ll<<60) #define INF ((int)1<<30) #define EPS (1e-9) #define MOD (1000000007ll) #define fcout(a) cout<<setprecision(a)<<fixed #define fs first #define sc second #define PI 3.1415926535897932384 int dx[]={1,0,-1,0,1,-1,-1,1},dy[]={0,1,0,-1,1,1,-1,-1}; template<class T>bool chmax(T&a,T b){if(a<b){a=b; return true;}return false;} template<class T>bool chmin(T&a,T b){if(a>b){a=b; return true;}return false;} template<class S>S acm(vector<S>&a){return accumulate(all(a),S());} template<class S>S max(vector<S>&a){return *max_element(all(a));} template<class S>S min(vector<S>&a){return *min_element(all(a));} void YN(bool b){cout<<(b?"YES":"NO")<<"\n";} void Yn(bool b){cout<<(b?"Yes":"No")<<"\n";} void yn(bool b){cout<<(b?"yes":"no")<<"\n";} int sgn(const double&r){return (r>EPS)-(r<-EPS);} // a>0 : sgn(a)>0 int sgn(const double&a,const double&b){return sgn(a-b);} // b<=c : sgn(b,c)<=0 ll max(int a,ll b){return max((ll)a,b);} ll max(ll a,int b){return max(a,(ll)b);} template<class T>void puta(T&&t){cout<<t<<"\n";} template<class H,class...T>void puta(H&&h,T&&...t){cout<<h<<' ';puta(t...);} template<class S,class T>ostream&operator<<(ostream&os,pair<S,T>p){os<<"["<<p.first<<", "<<p.second<<"]";return os;}; template<class S>auto&operator<<(ostream&os,vector<S>t){bool a=1; for(auto s:t){os<<(a?"":" ")<<s;a=0;} return os;} int main(){ cin.tie(0); ios::sync_with_stdio(false); string s; cin>>s; rep(i,3){ if(s[i]<'0'||s[i]>'9'){ cout<<"error"<<endl; return 0; } } cout<<2*stol(s)<<endl; }
[ "konpeist@gmail.com" ]
konpeist@gmail.com
f87076aa41bd03b7e1085e11527c83259884ab41
8c003e9106f2bf8c9d9b0fbf96fd9102fc2857a7
/zircon/system/dev/lib/fake_ddk/include/lib/fake_ddk/fidl-helper.h
0ad222049299ca06b37ab22d83be04562d896b34
[ "BSD-3-Clause", "MIT" ]
permissive
Autumin/fuchsia
53df56e33e4ad76a04d76d2efe21c9db95e9fcc9
9bad38cdada4705e88c5ae19d4557dfc0cd912ef
refs/heads/master
2022-04-23T18:13:33.728043
2020-04-21T14:43:53
2020-04-21T14:43:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,943
h
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ZIRCON_SYSTEM_DEV_LIB_FAKE_DDK_INCLUDE_LIB_FAKE_DDK_FIDL_HELPER_H_ #define ZIRCON_SYSTEM_DEV_LIB_FAKE_DDK_INCLUDE_LIB_FAKE_DDK_FIDL_HELPER_H_ #include <lib/async-loop/cpp/loop.h> #include <lib/async/cpp/wait.h> #include <lib/fidl-async/bind.h> #include <lib/zx/channel.h> #include <zircon/fidl.h> #include <fbl/algorithm.h> #include "lib/async-loop/loop.h" namespace fake_ddk { typedef zx_status_t(MessageOp)(void* ctx, fidl_msg_t* msg, fidl_txn_t* txn); // Helper class to call fidl handlers in unit tests // Use in conjunction with fake ddk // // Example usage: // // After device_add call // <fidl_client_function> ( <fake_ddk>.FidlClient().get(), <args>); // // Note: It is assumed that only one device add is done per fake ddk instance // // This can also be used stand alone // Example standalone usage: // DeviceX *dev; // FidlMessenger fidl; // fidl.SetMessageOp((void *)dev, // [](void* ctx, fidl_msg_t* msg, fidl_txn_t* txn) -> // zx_status_t { // return static_cast<Device*>(ctx)->DdkMessage(msg, txn)}); // <fidl_client_function> ( <fake_ddk>.local().get(), <args>); // class FidlMessenger { public: explicit FidlMessenger() : loop_(&kAsyncLoopConfigNeverAttachToThread) {} explicit FidlMessenger(const async_loop_config_t* config) : loop_(config) {} // Local channel to send FIDL client messages zx::channel& local() { return local_; } // Set handlers to be called when FIDL message is received // Note: Message operation context |op_ctx| and |op| must outlive FidlMessenger zx_status_t SetMessageOp(void* op_ctx, MessageOp* op) { zx_status_t status; zx::channel remote; if (message_op_) { // Message op was already set return ZX_ERR_INVALID_ARGS; } message_op_ = op; if ((status = zx::channel::create(0, &local_, &remote)) < 0) { return status; } if ((status = loop_.StartThread("fake_ddk_fidl")) < 0) { return status; } auto dispatch_fn = [](void* ctx, fidl_txn_t* txn, fidl_msg_t* msg, const void* ops) -> zx_status_t { return reinterpret_cast<MessageOp*>(const_cast<void*>(ops))(ctx, msg, txn); }; status = fidl_bind(loop_.dispatcher(), remote.release(), dispatch_fn, op_ctx, reinterpret_cast<const void*>(message_op_)); if (status != ZX_OK) { return status; } return status; } private: MessageOp* message_op_ = nullptr; // Channel to mimic RPC zx::channel local_; // Dispatcher for fidl messages async::Loop loop_; }; } // namespace fake_ddk #endif // ZIRCON_SYSTEM_DEV_LIB_FAKE_DDK_INCLUDE_LIB_FAKE_DDK_FIDL_HELPER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d69c226dd1f7d85423f15d77db0b4caee0eb1672
ce64c59e1e2b6ae779f125c982e94f6de93d62f8
/tests/kbuttongrouptest.cpp
cc3fdee6d25f48bc8e6def49a8298c622e4a50d8
[]
no_license
The-Oracle/kdeui
f3e2d7cc7335bdffce9d6a02de38ab196e5cf02d
87414d061d2f7156901212a19ea01bdf85d6e53d
refs/heads/master
2021-01-20T00:51:25.654205
2017-04-24T05:14:13
2017-04-24T05:14:13
89,200,851
0
1
null
null
null
null
UTF-8
C++
false
false
5,922
cpp
/* This file is part of the KDE Libraries Copyright (C) 2006 Pino Toscano <toscano.pino@tiscali.it> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "qtest_kde.h" #include <QtTest/QTestEvent> #include <QtCore/QList> #include <QtGui/QRadioButton> #include <QtTest/QSignalSpy> #include <QtGui/QBoxLayout> #include "kbuttongrouptest.h" #include "kbuttongroup.h" KButtonGroup* kbuttongroup; QList<QRadioButton*> buttons; void KButtonGroupTest::initTestCase() { kbuttongroup = new KButtonGroup(); QVBoxLayout* lay2 = new QVBoxLayout( kbuttongroup ); for ( int i = 0; i < 8; ++i ) { QRadioButton* r = new QRadioButton( kbuttongroup ); r->setText( QString( "radio%1" ).arg( i ) ); lay2->addWidget( r ); buttons << r; } QCOMPARE( kbuttongroup->selected(), -1 ); } void KButtonGroupTest::directSelectionTestCase() { // test where setSelected is called before the // ensurePolished() is called. KButtonGroup* kbuttongroup2 = new KButtonGroup(); kbuttongroup2->setSelected( 3 ); QVBoxLayout* lay2 = new QVBoxLayout( kbuttongroup2 ); for ( int i = 0; i < 8; ++i ) { QRadioButton* r = new QRadioButton( kbuttongroup2 ); r->setText( QString( "radio%1" ).arg( i ) ); lay2->addWidget( r ); buttons << r; } QTest::qWait(250); // events should occur. QCOMPARE( kbuttongroup2->selected(), 3 ); } void KButtonGroupTest::cleanupTestCase() { kbuttongroup->deleteLater(); } void KButtonGroupTest::testClicks() { QTest::mouseClick( buttons[3], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 3 ); QTest::mouseClick( buttons[5], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 5 ); QTest::mouseClick( buttons[7], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 7 ); QTest::mouseClick( buttons[1], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 1 ); // QRadioButton's react only to LMB click events QTest::mouseClick( buttons[5], Qt::RightButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 1 ); QTest::mouseClick( buttons[5], Qt::MidButton, 0, QPoint(), 10 ); QCOMPARE( kbuttongroup->selected(), 1 ); } void KButtonGroupTest::testManualSelection() { kbuttongroup->setSelected( 3 ); QCOMPARE( kbuttongroup->selected(), 3 ); kbuttongroup->setSelected( 0 ); QCOMPARE( kbuttongroup->selected(), 0 ); kbuttongroup->setSelected( 7 ); QCOMPARE( kbuttongroup->selected(), 7 ); kbuttongroup->setSelected( 2 ); QCOMPARE( kbuttongroup->selected(), 2 ); // "bad" cases: ask for an invalid id -- the selection should not change kbuttongroup->setSelected( 10 ); QCOMPARE( kbuttongroup->selected(), 2 ); kbuttongroup->setSelected( -1 ); QCOMPARE( kbuttongroup->selected(), 2 ); } void KButtonGroupTest::testSignals() { QSignalSpy spyClicked( kbuttongroup, SIGNAL( clicked( int ) ) ); QSignalSpy spyPressed( kbuttongroup, SIGNAL( pressed( int ) ) ); QSignalSpy spyReleased( kbuttongroup, SIGNAL( released( int ) ) ); QSignalSpy spyChanged( kbuttongroup, SIGNAL( changed( int ) ) ); QTest::mouseClick( buttons[2], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( spyClicked.count(), 1 ); QCOMPARE( spyPressed.count(), 1 ); QCOMPARE( spyReleased.count(), 1 ); QCOMPARE( spyChanged.count(), 1 ); QList<QVariant> args = spyClicked.last(); QList<QVariant> args2 = spyPressed.last(); QList<QVariant> args3 = spyReleased.last(); QCOMPARE( args.first().toInt(), 2 ); QCOMPARE( args2.first().toInt(), 2 ); QCOMPARE( args3.first().toInt(), 2 ); QCOMPARE( kbuttongroup->selected(), 2 ); QTest::mouseClick( buttons[6], Qt::LeftButton, 0, QPoint(), 10 ); QCOMPARE( spyClicked.count(), 2 ); QCOMPARE( spyPressed.count(), 2 ); QCOMPARE( spyReleased.count(), 2 ); QCOMPARE( spyChanged.count(), 2 ); args = spyClicked.last(); args2 = spyPressed.last(); args3 = spyReleased.last(); QCOMPARE( args.first().toInt(), 6 ); QCOMPARE( args2.first().toInt(), 6 ); QCOMPARE( args3.first().toInt(), 6 ); QCOMPARE( kbuttongroup->selected(), 6 ); // click with RMB on a radio -> no signal QTest::mouseClick( buttons[0], Qt::RightButton, 0, QPoint(), 10 ); QCOMPARE( spyClicked.count(), 2 ); QCOMPARE( spyPressed.count(), 2 ); QCOMPARE( spyReleased.count(), 2 ); QCOMPARE( spyChanged.count(), 2 ); QCOMPARE( kbuttongroup->selected(), 6 ); // manual selections kbuttongroup->setSelected( 7 ); QCOMPARE( spyChanged.count(), 3 ); QList<QVariant> args4 = spyChanged.last(); QCOMPARE( args4.first().toInt(), 7 ); QCOMPARE( kbuttongroup->selected(), 7 ); kbuttongroup->setSelected( 2 ); QCOMPARE( spyChanged.count(), 4 ); args4 = spyChanged.last(); QCOMPARE( args4.first().toInt(), 2 ); QCOMPARE( kbuttongroup->selected(), 2 ); // "bad" cases: ask for an invalid id -- the selection should not change kbuttongroup->setSelected( 10 ); QCOMPARE( spyChanged.count(), 4 ); QCOMPARE( kbuttongroup->selected(), 2 ); kbuttongroup->setSelected( -1 ); QCOMPARE( spyChanged.count(), 4 ); QCOMPARE( kbuttongroup->selected(), 2 ); } QTEST_KDEMAIN(KButtonGroupTest, GUI) #include "kbuttongrouptest.moc"
[ "Jeremy@jbdynamics.net" ]
Jeremy@jbdynamics.net
b19c64d3694c51510e032d80ff05ee4611e5d728
bbd54df0d03b9eb858f78b75fdebb70a8993b377
/photon_prob/cuda_tools/vec3.h
653ce314e11ed7abb0ff74fc47c9207503fe744e
[]
no_license
Tshalberg/toy-mc
58cef737d8a9c65a3ed8b3cfd2261321a8408107
0315233c8c97a5e800a6f5b3b25a9f12cc33dd90
refs/heads/master
2020-07-20T07:02:35.656138
2019-10-18T13:28:59
2019-10-18T13:28:59
206,595,041
1
0
null
null
null
null
UTF-8
C++
false
false
4,325
h
#ifndef VEC3H #define VEC3H #include <math.h> #include <stdlib.h> #include <iostream> class vec3 { public: __host__ __device__ vec3() {} __host__ __device__ vec3(float e0, float e1, float e2) { e[0] = e0; e[1] = e1; e[2] = e2; } __host__ __device__ inline float x() const { return e[0]; } __host__ __device__ inline float y() const { return e[1]; } __host__ __device__ inline float z() const { return e[2]; } __host__ __device__ inline float r() const { return e[0]; } __host__ __device__ inline float g() const { return e[1]; } __host__ __device__ inline float b() const { return e[2]; } __host__ __device__ inline const vec3& operator+() const { return *this; } __host__ __device__ inline vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); } __host__ __device__ inline float operator[](int i) const { return e[i]; } __host__ __device__ inline float& operator[](int i) { return e[i]; }; __host__ __device__ inline vec3& operator+=(const vec3 &v2); __host__ __device__ inline vec3& operator-=(const vec3 &v2); __host__ __device__ inline vec3& operator*=(const vec3 &v2); __host__ __device__ inline vec3& operator/=(const vec3 &c2); __host__ __device__ inline vec3& operator*=(const float t); __host__ __device__ inline vec3& operator/=(const float t); __host__ __device__ inline float length() const { return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); } __host__ __device__ inline float squared_length() const { return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; } __host__ __device__ inline void make_unit_vector(); float e[3]; }; inline std::istream& operator>>(std::istream &is, vec3 &t) { is >> t.e[0] >> t.e[1] >> t.e[2]; return is; } inline std::ostream& operator<<(std::ostream &os, const vec3 &t) { os << t.e[0] << " " << t.e[1] << " " << t.e[2]; return os; } __host__ __device__ inline void vec3::make_unit_vector() { float k = 1.0 / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); e[0] *= k; e[1] *= k; e[2] *= k; } __host__ __device__ inline vec3 operator+(const vec3 &v1, const vec3 &v2) { return vec3(v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]); } __host__ __device__ inline vec3 operator-(const vec3 &v1, const vec3 &v2) { return vec3(v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]); } __host__ __device__ inline vec3 operator*(const vec3 &v1, const vec3 &v2) { return vec3(v1.e[0] * v2.e[0], v1.e[1] * v2.e[1], v1.e[2] * v2.e[2]); } __host__ __device__ inline vec3 operator/(const vec3 &v1, const vec3 &v2) { return vec3(v1.e[0] / v2.e[0], v1.e[1] / v2.e[1], v1.e[2] / v2.e[2]); } __host__ __device__ inline vec3 operator*(float t, const vec3 &v) { return vec3(t * v.e[0], t * v.e[1], t * v.e[2]); } __host__ __device__ inline vec3 operator*(const vec3 &v, float t) { return vec3(t * v.e[0], t * v.e[1], t * v.e[2]); } __host__ __device__ inline vec3 operator/(vec3 v, float t) { return vec3(v.e[0]/t, v.e[1]/t, v.e[2]/t); } __host__ __device__ inline float distance(const vec3 &v1, const vec3 &v2) { return sqrt(v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2]); } __host__ __device__ inline float dot(const vec3 &v1, const vec3 &v2) { return v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2]; } __host__ __device__ inline vec3 cross(const vec3 &v1, const vec3 &v2) { return vec3( (v1.e[1]*v2.e[2] - v1.e[2]*v2.e[1]), (-(v1.e[0]*v2.e[2] - v1.e[2]*v2.e[0])), (v1.e[0]*v2.e[1] - v1.e[1]*v2.e[0])); } __host__ __device__ inline vec3& vec3::operator+=(const vec3 &v){ e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator*=(const vec3 &v){ e[0] *= v.e[0]; e[1] *= v.e[1]; e[2] *= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator/=(const vec3 &v){ e[0] /= v.e[0]; e[1] /= v.e[1]; e[2] /= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator-=(const vec3 &v){ e[0] -= v.e[0]; e[1] -= v.e[1]; e[2] -= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator*=(const float t){ e[0] *= t; e[1] *= t; e[2] *= t; return *this; } __host__ __device__ inline vec3& vec3::operator/=(const float t){ float k = 1.0 / t; e[0] *= k; e[1] *= k; e[2] *= k; return *this; } __host__ __device__ inline vec3 unit_vector(vec3 v) { return v / v.length(); } #endif
[ "thomashalberg@gmail.com" ]
thomashalberg@gmail.com
4b01921ffd18964994e72e50c909a66167f1f720
5cc19dfb292136de78c4cdc2b1e620bb189a3e99
/src/ntcp2/session/listener.h
06d9e089e30aa09d535f034a5b1498c9d52f6fd0
[ "BSD-3-Clause" ]
permissive
chisa0a/tini2p
4334c50ff672c6d3331082966566ce765480e322
a9b6cb48dbbc8d667b081a95c720f0ff2a0f84f5
refs/heads/master
2020-05-01T03:36:55.840744
2019-03-22T22:11:55
2019-03-23T03:03:02
177,249,241
1
0
BSD-3-Clause
2019-03-23T05:42:13
2019-03-23T05:42:12
null
UTF-8
C++
false
false
9,576
h
/* Copyright (c) 2019, tini2p * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SRC_NTCP2_SESSION_LISTENER_H_ #define SRC_NTCP2_SESSION_LISTENER_H_ #include <unordered_map> #include <unordered_set> #include "src/ntcp2/session/key.h" namespace tini2p { namespace ntcp2 { /// @class SessionListener /// @brief Listen for incoming sessions on a given local endpoint class SessionListener { public: using info_t = data::Info; //< RouterInfo trait alias using key_t = crypto::X25519::pubkey_t; //< Session key trait alias using session_t = Session<Responder>; //< Session trait alias using sessions_t = std::vector<session_t::shared_ptr>; //< Sessions container trait alias using session_count_t = std::unordered_map<key_t, std::uint16_t, key_t::hasher_t>; //< Session count trait alias using blacklist_t = std::unordered_set<key_t, key_t::hasher_t>; //< Blacklist trait alias using pointer = SessionListener*; //< Non-owning pointer trait alias using const_pointer = const SessionListener*; //< Const non-owning pointer trait alias using unique_ptr = std::unique_ptr<SessionListener>; //< Unique pointer trait alias using const_unique_ptr = std::unique_ptr<const SessionListener>; //< Const unique pointer trait alias using shared_ptr = std::shared_ptr<SessionListener>; //< Shared pointer trait alias using const_shared_ptr = std::shared_ptr<const SessionListener>; //< Const shared pointer trait alias /// @brief Create a session listener for local router on a given local endpoint /// @param info Local router info /// @param host Local endpoint to bind the listener /// @param ctx Boost IO context for listener SessionListener( const info_t::shared_ptr info, const session_t::tcp_t::endpoint& host) : info_(info), ctx_(), acc_(ctx_, host, true), timer_(ctx_, std::chrono::milliseconds(session_t::meta_t::CleanTimeout)) { acc_.listen(); timer_.async_wait( [this](const session_t::error_c& ec) { CleanSessions(ec); }); } ~SessionListener() { Stop(); acc_.cancel(); acc_.close(); } /// @brief Start the session listener void Start() { Accept(); Run(); } /// @brief Stop the session listener void Stop() { using ms = std::chrono::milliseconds; try { { // clean up sessions std::lock_guard<std::mutex> l(sessions_mutex_); for (const auto& session : sessions_) session->Stop(); sessions_.clear(); } acc_.get_executor().context().stop(); timer_.expires_from_now(ms(session_t::meta_t::ShutdownTimeout)); if (thread_) { thread_->join(); thread_.reset(); } std::this_thread::sleep_for(ms(session_t::meta_t::ShutdownTimeout)); } catch (const std::exception& ex) { std::cerr << "SessionListener: " << __func__ << ": " << ex.what() << std::endl; } } /// @brief Get a session indexed by the remote key /// @param key Alice's static Noise key /// @return Non-const pointer to an NTCP2 session, or nullptr when no session found session_t::shared_ptr session(const key_t& key) { std::lock_guard<std::mutex> l(sessions_mutex_); const auto it = std::find_if( sessions_.begin(), sessions_.end(), [key](const sessions_t::value_type& session) { return session->key() == key; }); return it != sessions_.end() ? *it : nullptr; } /// @brief Get if a session is blacklisted /// @param key Session key to search for in the blacklist /// @return True if session key found in the blacklist bool blacklisted(const key_t& key) const { return blacklist_.find(key) != blacklist_.end(); } private: void Accept() { const exception::Exception ex{"SessionListener", __func__}; acc_.async_accept([this, ex]( const session_t::error_c& ec, session_t::tcp_t::socket socket) { if (ec) ex.throw_ex<std::runtime_error>(ec.message().c_str()); //-------------------------------------------------- { // create new session for the incoming connection std::lock_guard<std::mutex> l(sessions_mutex_); sessions_t::value_type session(new session_t(info_, std::move(socket))); session->Start(session_t::meta_t::IP::v6); // try IPv6, fallback to IPv4 // try inserting new connection, or get existing entry auto count_it = connect_count_.emplace(std::make_pair(session->connect_key(), 0)).first; const bool blacklisted = blacklist_.find(count_it->first) != blacklist_.end(); if (++count_it->second > session_t::meta_t::MaxConnections || blacklisted) { const std::string err_msg( "SessionListener: blacklisted host with connection key: " + crypto::Base64::Encode(count_it->first)); if (!blacklisted) blacklist_.emplace(std::move(count_it->first)); connect_count_.erase(count_it); ex.throw_ex<std::runtime_error>(std::move(err_msg)); } else if ( std::find_if( sessions_.begin(), sessions_.end(), [count_it](const sessions_t::value_type& session_ptr) { return session_ptr->connect_key() == count_it->first; }) != sessions_.end()) { const std::string err_msg( "SessionListener: session already exists for connection key: " + crypto::Base64::Encode(count_it->first)); if (!blacklisted) { blacklist_.emplace(std::move(count_it->first)); connect_count_.erase(count_it); } ex.throw_ex<std::runtime_error>(std::move(err_msg)); } else sessions_.emplace_back(std::move(session)); } // end session-lock scope Accept(); }); } void Run() { const auto func = __func__; thread_ = std::make_unique<std::thread>([this, func]() { try { acc_.get_io_service().run(); } catch (const std::exception& ex) { std::cerr << "SessionListener: " << func << ": " << ex.what() << std::endl; } }); } void CleanSessions(const session_t::error_c& ec) { const exception::Exception ex{"SessionListener", __func__}; if (ec && ec != boost::asio::error::eof) ex.throw_ex<std::runtime_error>(ec.message().c_str()); //------------------------------------------ { // remove failed and blacklisted sessions std::lock_guard<std::mutex> l(sessions_mutex_); std::remove_if( sessions_.begin(), sessions_.end(), [=](const decltype(sessions_)::value_type& session) { const auto& key = session->key(); const bool remove = !session->ready() || blacklist_.find(key) != blacklist_.end(); if (remove) session_count_[key]++; // increase session count if removing return remove; }); for (auto it = session_count_.begin(); it != session_count_.end(); ++it) { if (it->second > session_t::meta_t::MaxSessions) { blacklist_.emplace(std::move(it->first)); session_count_.erase(it); } } } // end session-lock scope timer_.async_wait( [this](const session_t::error_c& ec) { CleanSessions(ec); }); } info_t::shared_ptr info_; session_t::context_t ctx_; session_t::tcp_t::acceptor acc_; sessions_t sessions_; session_count_t session_count_, connect_count_; blacklist_t blacklist_; boost::asio::steady_timer timer_; std::unique_ptr<std::thread> thread_; std::mutex sessions_mutex_; }; } // namespace ntcp2 } // namespace tini2p #endif // SRC_NTCP2_SESSION_LISTENER_H_
[ "tini2p@i2pmail.org" ]
tini2p@i2pmail.org
e076b7e70d11c0819db4f52aa055f0b5ae1bdd96
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
/baselib/lib/Lsc/cxxtest/cxxtest/QtGui.h
868604d5d6d02b1426e1433a355662324f53f9bc
[]
no_license
lightchainone/lightchain
7d90338d4a4e8d31d550c07bf380c06580941334
6fc7019c76a8b60d4fd63fba58fa79858856f66b
refs/heads/master
2021-05-11T05:47:17.672527
2019-12-16T09:51:39
2019-12-16T09:51:39
117,969,593
23
6
null
null
null
null
UTF-8
C++
false
false
7,847
h
#ifndef __cxxtest__QtGui_h__ #define __cxxtest__QtGui_h__ // // The QtGui displays a simple progress bar using the Qt Toolkit. It // has been tested with versions 2.x and 3.x. // // Apart from normal Qt command-line arguments, it accepts the following options: // -minimized Start minimized, pop up on error // -keep Don't close the window at the end // -title TITLE Set the window caption // // If both are -minimized and -keep specified, GUI will only keep the // window if it's in focus. // #include <cxxtest/Gui.h> #include <qapplication.h> #include <qglobal.h> #include <qlabel.h> #include <qlayout.h> #include <qmessagebox.h> #include <qpixmap.h> #include <qprogressbar.h> #include <qstatusbar.h> namespace CxxTest { class QtGui : plclic GuiListener { plclic: void enterGui( int &argc, char **argv ) { parseCommandLine( argc, argv ); createApplication( argc, argv ); } void enterWorld( const WorldDescription &wd ) { createWindow( wd ); processEvents(); } void guiEnterSuite( const char *suiteName ) { showSuiteName( suiteName ); } void guiEnterTest( const char *suiteName, const char *testName ) { setCaption( suiteName, testName ); advanceProgressBar(); showTestName( testName ); showTestsDone( _progressBar->progress() ); processEvents(); } void yellowBar() { setColor( 255, 255, 0 ); setIcon( QMessageBox::Warning ); getTotalTests(); processEvents(); } void redBar() { if ( _startMinimized && _mainWindow->isMinimized() ) showNormal(); setColor( 255, 0, 0 ); setIcon( QMessageBox::Critical ); getTotalTests(); processEvents(); } void leaveGui() { if ( keep() ) { showSummary(); _application->exec(); } else _mainWindow->close( true ); } private: QString _title; bool _startMinimized, _keep; unsigned _numTotalTests; QString _strTotalTests; QApplication *_application; QWidget *_mainWindow; QVBoxLayout *_layout; QProgressBar *_progressBar; QStatusBar *_statusBar; QLabel *_suiteName, *_testName, *_testsDone; void parseCommandLine( int argc, char **argv ) { _startMinimized = _keep = false; _title = argv[0]; for ( int i = 1; i < argc; ++ i ) { QString arg( argv[i] ); if ( arg == "-minimized" ) _startMinimized = true; else if ( arg == "-keep" ) _keep = true; else if ( arg == "-title" && (i + 1 < argc) ) _title = argv[++i]; } } void createApplication( int &argc, char **argv ) { _application = new QApplication( argc, argv ); } void createWindow( const WorldDescription &wd ) { getTotalTests( wd ); createMainWindow(); createProgressBar(); createStatusBar(); setMainWidget(); if ( _startMinimized ) showMinimized(); else showNormal(); } void getTotalTests() { getTotalTests( tracker().world() ); } void getTotalTests( const WorldDescription &wd ) { _numTotalTests = wd.numTotalTests(); char s[WorldDescription::MAX_STRLEN_TOTAL_TESTS]; _strTotalTests = wd.strTotalTests( s ); } void createMainWindow() { _mainWindow = new QWidget(); _layout = new QVBoxLayout( _mainWindow ); } void createProgressBar() { _layout->addWidget( _progressBar = new QProgressBar( _numTotalTests, _mainWindow ) ); _progressBar->setProgress( 0 ); setColor( 0, 255, 0 ); setIcon( QMessageBox::Information ); } void createStatusBar() { _layout->addWidget( _statusBar = new QStatusBar( _mainWindow ) ); _statusBar->addWidget( _suiteName = new QLabel( _statusBar ), 2 ); _statusBar->addWidget( _testName = new QLabel( _statusBar ), 4 ); _statusBar->addWidget( _testsDone = new QLabel( _statusBar ), 1 ); } void setMainWidget() { _application->setMainWidget( _mainWindow ); } void showMinimized() { _mainWindow->showMinimized(); } void showNormal() { _mainWindow->showNormal(); centerWindow(); } void setCaption( const QString &suiteName, const QString &testName ) { _mainWindow->setCaption( _title + " - " + suiteName + "::" + testName + "()" ); } void showSuiteName( const QString &suiteName ) { _suiteName->setText( "class " + suiteName ); } void advanceProgressBar() { _progressBar->setProgress( _progressBar->progress() + 1 ); } void showTestName( const QString &testName ) { _testName->setText( testName + "()" ); } void showTestsDone( unsigned testsDone ) { _testsDone->setText( asString( testsDone ) + " of " + _strTotalTests ); } static QString asString( unsigned n ) { return QString::number( n ); } void setColor( int r, int g, int b ) { QPalette palette = _progressBar->palette(); palette.setColor( QColorGroup::Highlight, QColor( r, g, b ) ); _progressBar->setPalette( palette ); } void setIcon( QMessageBox::Icon icon ) { #if QT_VERSION >= 0x030000 _mainWindow->setIcon( QMessageBox::standardIcon( icon ) ); #else // Qt version < 3.0.0 _mainWindow->setIcon( QMessageBox::standardIcon( icon, QApplication::style().guiStyle() ) ); #endif // QT_VERSION } void processEvents() { _application->processEvents(); } void centerWindow() { QWidget *desktop = QApplication::desktop(); int xCenter = desktop->x() + (desktop->width() / 2); int yCenter = desktop->y() + (desktop->height() / 2); int windowWidth = (desktop->width() * 4) / 5; int windowHeight = _mainWindow->height(); _mainWindow->setGeometry( xCenter - (windowWidth / 2), yCenter - (windowHeight / 2), windowWidth, windowHeight ); } bool keep() { if ( !_keep ) return false; if ( !_startMinimized ) return true; return (_mainWindow == _application->activeWindow()); } void showSummary() { QString summary = _strTotalTests + (_numTotalTests == 1 ? " test" : " tests"); if ( tracker().failedTests() ) summary = "Failed " + asString( tracker().failedTests() ) + " of " + summary; else summary = summary + " passed"; _mainWindow->setCaption( _title + " - " + summary ); _statusBar->removeWidget( _suiteName ); _statusBar->removeWidget( _testName ); _testsDone->setText( summary ); } }; }; #endif // __cxxtest__QtGui_h__
[ "lightchainone@hotmail.com" ]
lightchainone@hotmail.com
688bae078b19d257af18b924e8260c805dfcadd4
c6c8bf3525698a8184fde1b5439a24744970512d
/vespalib/src/vespa/vespalib/net/tls/statistics.cpp
d11aa60266ebd59aa3a19eb37666254eba2c4d71
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
socratesone/vespa
0df03ece09de001942232300de23f8db13a38e45
7ee52b93cbae2695cf916c9b2941361b35b973f1
refs/heads/master
2023-03-16T23:35:10.953427
2021-03-17T02:41:56
2021-03-17T02:41:56
305,143,840
1
0
Apache-2.0
2021-03-17T02:41:56
2020-10-18T16:18:57
null
UTF-8
C++
false
false
2,096
cpp
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "statistics.h" namespace vespalib::net::tls { ConnectionStatistics ConnectionStatistics::client_stats = {}; ConnectionStatistics ConnectionStatistics::server_stats = {}; ConfigStatistics ConfigStatistics::instance = {}; ConnectionStatistics::Snapshot ConnectionStatistics::snapshot() const noexcept { Snapshot s; s.insecure_connections = insecure_connections.load(std::memory_order_relaxed); s.tls_connections = tls_connections.load(std::memory_order_relaxed); s.failed_tls_handshakes = failed_tls_handshakes.load(std::memory_order_relaxed); s.invalid_peer_credentials = invalid_peer_credentials.load(std::memory_order_relaxed); s.broken_tls_connections = broken_tls_connections.load(std::memory_order_relaxed); return s; } ConnectionStatistics::Snapshot ConnectionStatistics::Snapshot::subtract(const Snapshot& rhs) const noexcept { Snapshot s; s.insecure_connections = insecure_connections - rhs.insecure_connections; s.tls_connections = tls_connections - rhs.tls_connections; s.failed_tls_handshakes = failed_tls_handshakes - rhs.failed_tls_handshakes; s.invalid_peer_credentials = invalid_peer_credentials - rhs.invalid_peer_credentials; s.broken_tls_connections = broken_tls_connections - rhs.broken_tls_connections; return s; } ConfigStatistics::Snapshot ConfigStatistics::snapshot() const noexcept { Snapshot s; s.successful_config_reloads = successful_config_reloads.load(std::memory_order_relaxed); s.failed_config_reloads = failed_config_reloads.load(std::memory_order_relaxed); return s; } ConfigStatistics::Snapshot ConfigStatistics::Snapshot::subtract(const Snapshot& rhs) const noexcept { Snapshot s; s.successful_config_reloads = successful_config_reloads - rhs.successful_config_reloads; s.failed_config_reloads = failed_config_reloads - rhs.failed_config_reloads; return s; } }
[ "vekterli@oath.com" ]
vekterli@oath.com
722e593eac5a5bc3a583916e204f2bdfae6bce8e
8d5ca7e9f9b1f8c1878298a9e6876a346a5db72f
/did/src/ButtonHighlightSystem.cpp
7c855ddebc587c6d6cdd7caed648798a9e053030
[ "Zlib" ]
permissive
fallahn/osgc
102914dc740796cdc53cbc225038eee8695716ec
8a2f7745bd767e68da2b0771ecf3e7d50e59e725
refs/heads/master
2021-06-20T11:33:04.473998
2021-02-11T13:16:53
2021-02-11T13:16:53
178,931,498
23
3
null
2020-04-21T10:39:17
2019-04-01T19:18:19
C++
UTF-8
C++
false
false
2,056
cpp
/********************************************************************* Copyright 2019 Matt Marchant Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************************/ #include "ButtonHighlightSystem.hpp" #include <xyginext/ecs/components/Sprite.hpp> #include <xyginext/ecs/components/AudioEmitter.hpp> #include <SFML/Window/Joystick.hpp> namespace { const sf::Color buttonColour(80, 80, 80, 255); } ButtonHighlightSystem::ButtonHighlightSystem(xy::MessageBus& mb) : xy::System(mb, typeid(ButtonHighlightSystem)) { requireComponent<ButtonHighlight>(); requireComponent<xy::Sprite>(); requireComponent<xy::AudioEmitter>(); } //public void ButtonHighlightSystem::process(float) { auto& entities = getEntities(); for (auto entity : entities) { auto& highlight = entity.getComponent<ButtonHighlight>(); if (bool pressed = sf::Joystick::isButtonPressed(0, highlight.id); highlight.highlighted != pressed) { highlight.highlighted = pressed; if (pressed) { entity.getComponent<xy::Sprite>().setColour(buttonColour); auto& emitter = entity.getComponent<xy::AudioEmitter>(); if (emitter.getStatus() == xy::AudioEmitter::Stopped) { emitter.play(); } } else { entity.getComponent<xy::Sprite>().setColour(sf::Color::Transparent); } } } }
[ "matty_styles@hotmail.com" ]
matty_styles@hotmail.com
3d3ca84b803755200e60fedd76a4f7718672beed
74a31a9666df200ab18c44566f2227d031823b23
/myst0193g/Classes/scenes/LoadingScene.cpp
42e6dba394c684eb91cb866531077370e6225eed
[]
no_license
Crasader/Demo_Earlier_CC
448f3447fc3fb237c2346069bf2344f44bd552db
320c57f91b7d6603a6293b65a6702f76b1e035ba
refs/heads/master
2020-12-04T12:24:47.254647
2018-05-31T02:51:24
2018-05-31T02:51:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,198
cpp
// // LoadingScene.cpp // LVUP004 // // Created by Steven.Xc.Tian on 13-11-18. // // #include <string.h> #include "LoadingScene.h" #include "AppGlobal.h" #include "HomeScene.h" #include "../AppGlobal.h" #include "../FileModifiers.h" #include "../helpers/EncryptDataHelper.h" #include "../helpers/PurchaseHelper.h" #include "../utilities/CSVParse.h" #include "../widgets/STUILayer.h" #include "../utilities/STUtility.h" USING_NS_CC; using std::string; enum { tag_progress_1 = 70, tag_progress_2, }; CCScene* LoadingLayer::scene() { CCScene* pScene = CCScene::create(); if (pScene) { LoadingLayer* p_lLayer = LoadingLayer::create(); if (p_lLayer) { pScene->addChild(p_lLayer); } } return pScene; } bool LoadingLayer::init() { bool pRet = false; do { // load sprite sheet CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("load-home.plist"); CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("pop-window.plist"); CCSize winSize = CCDirector::sharedDirector()->getVisibleSize(); CCSprite *p_Bg = CCSprite::create("ui01_menu_bg.jpg"); CC_BREAK_IF(!p_Bg); p_Bg->setPosition(ccp(winSize.width / 2, winSize.height / 2)); this->addChild(p_Bg); STUILayer* uiLayer = STUILayer::create(); CC_BREAK_IF(!uiLayer); this->addChild(uiLayer); // CCSprite* progressBG = CCSprite::createWithSpriteFrameName("ui09_bar_bg.png"); progressBG->setPosition(ccp_horizontal_center(690)); progressBG->setAnchorPoint(ccp(.5, .5)); uiLayer->addChild(progressBG); CCSprite* text = CCSprite::createWithSpriteFrameName("ui09_loading.png"); text->setPosition(ccp_horizontal_center(600)); uiLayer->addChild(text); m_pProgress = CCProgressTimer::create(CCSprite::createWithSpriteFrameName("ui09_bar.png")); CC_BREAK_IF(!m_pProgress); m_pProgress->setType(kCCProgressTimerTypeBar); m_pProgress->setMidpoint(ccp(0, 1)); m_pProgress->setBarChangeRate(ccp(1, 0)); m_pProgress->setPosition(ccp(progressBG->getContentSize().width / 2, progressBG->getContentSize().height / 2)); m_pProgress->setPercentage(5); progressBG->addChild(m_pProgress); loadMapInfos(); pRet = true; } while (0); return pRet; } void LoadingLayer::onEnter() { CCLayer::onEnter(); } void LoadingLayer::onExit() { CCLayer::onExit(); } void LoadingLayer::onLoadFinish() { PurchaseHelper::isPurchased = EncryptDataHelper::getPurchaseFlag(key_iap_purchased_flag); PurchaseHelper::isAdPurchased = EncryptDataHelper::getPurchaseFlag(key_iap_ad_purchased_flag); CCScene *pScene = HomeLayer::scene(); CCDirector::sharedDirector()->replaceScene(pScene); } void LoadingLayer::load() { string stringsPath = st_strings_root; stringsPath.append(st_file_seperator); stringsPath.append(st_strings_file); // CCLOG("texts path is %s", textsPath.c_str()); // below is strings AppGlobal::stAllStrings = new CCDictionary(); CSVParse *csv = CSVParse::create(stringsPath.c_str()); if (!csv) { CCLOGERROR("Can't load CSV file: %s", stringsPath.c_str()); return; } unsigned rown = csv->getRows(); // exclude the first row which is the column's name for (int r = 1; r < rown; r++) { const char* key = csv->getDatas(r, st_disname_id); CCString* value = CCString::create(csv->getDatas(r, st_disname_Name)); // add names to dictionary AppGlobal::stAllStrings->setObject(value, key); } CCAction* action = CCSequence::create( CCProgressTo::create(.5, 85), CCDelayTime::create(0.3), CCCallFunc::create(this, callfunc_selector(LoadingLayer::loadSKU)), NULL); m_pProgress->runAction(action); } void LoadingLayer::loadMapInfos() { // play loading animation, and delay until this step over CCAction* action = CCSequence::create(CCProgressTo::create(0.1, 50), CCDelayTime::create(100), NULL); m_pProgress->runAction(action); /* load Description.csv file */ string descFilePath = st_maps_root; descFilePath.append(st_file_seperator).append(st_maps_descfile_name); // must call release() when game exit. AppGlobal::stAllLevelsInformation = CCArray::create(); AppGlobal::stAllLevelsInformation->retain(); CSVParse* desc_csv = CSVParse::create(descFilePath.c_str()); if (!desc_csv) { CCLOGERROR("Can't load CSV file: %s", descFilePath.c_str()); return; } const unsigned rown = desc_csv->getRows(); // exclude the first row which is the column's name for (int r = 1; r < rown; r++) { CCDictionary* eachLevel = CCDictionary::create(); CCString* freeFlag = CCString::create(desc_csv->getDatas(r, st_level_free)); eachLevel->setObject(freeFlag, st_level_free); CCString* location = CCString::create(desc_csv->getDatas(r, st_level_location)); eachLevel->setObject(location, st_level_location); // folder name CCString* folder_id = CCString::create(desc_csv->getDatas(r, st_level_folder_id)); eachLevel->setObject(folder_id, st_level_folder_id); // resources name CCString* res_id = CCString::create(desc_csv->getDatas(r, st_level_res_id)); eachLevel->setObject(res_id, st_level_res_id); CCString* background = CCString::create(desc_csv->getDatas(r, st_level_background)); eachLevel->setObject(background, st_level_background); CCString* thumb = CCString::create(desc_csv->getDatas(r, st_level_bg_thumb)); eachLevel->setObject(thumb, st_level_bg_thumb); AppGlobal::stAllLevelsInformation->addObject(eachLevel); } CC_SAFE_RELEASE(desc_csv); /* load MapsConfig.csv file */ AppGlobal::stMapsConfig = CCDictionary::create(); AppGlobal::stMapsConfig->retain(); string mapsConfigPath = st_maps_root; mapsConfigPath.append(st_file_seperator).append(st_maps_config_file); CSVParse* mc_csv = CSVParse::create(mapsConfigPath.c_str()); if (!mc_csv) { CCLOGERROR("Can't load MapsConfig file: %s", mapsConfigPath.c_str()); return; } CCString* version = CCString::create(mc_csv->getDatas(1, st_maps_config_version)); AppGlobal::stMapsConfig->setObject(version, st_maps_config_version); CCString* capacity = CCString::create(mc_csv->getDatas(1, st_maps_config_capacity)); AppGlobal::stMapsConfig->setObject(capacity, st_maps_config_capacity); CCString* free = CCString::create(mc_csv->getDatas(1, st_maps_config_free)); AppGlobal::stMapsConfig->setObject(free, st_maps_config_free); CC_SAFE_RELEASE(mc_csv); m_pProgress->stopAction(action); CCAction* goon = CCSequence::create( CCProgressTo::create(.5, 50), CCCallFunc::create(this, callfunc_selector(LoadingLayer::load)), NULL); m_pProgress->runAction(goon); } void LoadingLayer:: loadSKU() { CSVParse* csv = CSVParse::create("sku/sku.csv"); if (!csv) { CCLOGERROR("Can't load sku.csv"); return; } AppGlobal::stSKUInformation = CCArray::create(); CC_SAFE_RETAIN(AppGlobal::stSKUInformation); unsigned rown = csv->getRows(); // exclude the first row which is the column's name for (int r = 1; r < rown; r++) { CCDictionary *info = CCDictionary::create(); bool isStroe = namespaceST::STUtility::parseBoolean(csv->getDatas(r, st_sku_store)); info->setObject(CCBool::create(isStroe), st_sku_store); CCString* sku_ios = CCString::create(csv->getDatas(r, st_sku_ios)); info->setObject(sku_ios, st_sku_ios); CCString* sku_android = CCString::create(csv->getDatas(r, st_sku_android)); info->setObject(sku_android, st_sku_android); CCString* background = CCString::create(csv->getDatas(r, st_sku_bgname)); info->setObject(background, st_sku_bgname); AppGlobal::stSKUInformation->addObject(info); } CC_SAFE_RELEASE(csv); CCAction* action = CCSequence::create( CCProgressTo::create(.5, 100), CCDelayTime::create(0.3), CCCallFunc::create(this, callfunc_selector(LoadingLayer::onLoadFinish)), NULL); m_pProgress->runAction(action); } LoadingLayer::~LoadingLayer() { }
[ "327239185@qq.com" ]
327239185@qq.com
16ba50919f24e874c96fb68ec859b4cb9d7224fc
87f7fdd39359dcf2adfe7525241b5762fb3f7374
/8_11/GameTraining/ThingMan.cpp
3ff2cd6308c69eb24c7184f6ed986dcd96f87c0f
[]
no_license
gautruckc/Nhap_Mon_Game
a5f11888aabb1a760f5196a98bb6d9d0dc749c9d
c435503750a3e8134e6790ebeb8f5cdee5d88f7c
refs/heads/master
2021-08-08T10:36:47.450846
2017-11-10T05:34:30
2017-11-10T05:34:30
110,207,060
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
#include "ThingMan.h" ThingMan::ThingMan() { sprite = SpriteManager::getInstance()->sprites[SPR_THINGMAN]; getAnimationDelay()->setTickPerFrame(100); tm_action = TM_RUN; direction = Right; setHeight(30); setDy(0); setAy(0);//xoa trong luc } void ThingMan::update() { Enemy::update(); } void ThingMan::onCollision(FBox* other, int nx, int ny) { } void ThingMan::render() { if (sprite == 0) return; float yRender; float xRender; D3DXMATRIX flipMatrix; int frameWidth = sprite->anims[getAction()].frames[getFrameIndex()].right - sprite->anims[getAction()].frames[getFrameIndex()].left; Camera::getInstance()->Transform(x, y, xRender, yRender); xRender = (int)xRender; yRender = (int)yRender; xRender -= (frameWidth - width) / 2; if (direction != sprite->img->direction) { D3DXMatrixIdentity(&flipMatrix); flipMatrix._11 = -1; flipMatrix._41 = 2 * (xRender + frameWidth / 2); DirectXTool::getInstance()->GetSprite()->SetTransform(&flipMatrix); } sprite->render(xRender, yRender, getAction(), getFrameIndex()); if (direction != sprite->img->direction) { D3DXMatrixIdentity(&flipMatrix); DirectXTool::getInstance()->GetSprite()->SetTransform(&flipMatrix); } } void ThingMan::onLastFrameAnimation() { BaseObject::onLastFrameAnimation(); } ThingMan::~ThingMan() { }
[ "kimchung1995qn@gmail.com" ]
kimchung1995qn@gmail.com
ea9bc26eed972432ed20a24368bc415fe52d6d0d
0a9f391de53ee4efbffe420fd06a9dabe99ef8c7
/Вычислительная Математика/7/Newton.cpp
d287888543524baf9a1a78f9fa0be27be56dea66
[]
no_license
Okmorr/Sibsutis
11eba94dd7e07ed2e18646f2e23ff0f7b39e6289
1b8e2a794b9664875949427562128e1790c50a41
refs/heads/master
2023-01-30T01:56:08.242569
2020-12-14T04:26:40
2020-12-14T04:26:40
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,849
cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <math.h> using namespace std; unsigned int factorial(unsigned int index) { if (index == 0 || index == 1) { return 1; } return index * factorial(index - 1); } double multiple_q(double xx, double *X, unsigned int n) { unsigned int i; double h = X[1] - X[0]; double multiple = (xx - X[0]) / h; for (i = 1; i < n; i++) { multiple *= ((xx - X[0]) / h) - i; } return multiple; } int main() { setlocale(0, ""); double xx = 1.44; unsigned int i, j, n = 0; char *file = "file.txt"; char *buffer = new char[100]; setlocale(0, ""); ifstream f(file); f.getline(buffer, 100, '\n'); f.close(); //Вычисляем размер массивов for (i = 0; i < 100 && buffer[i] != '\0'; ++i) { if (buffer[i] == ' ') { ++n; } } delete[] buffer; double *X = new double[n]; double **Y = new double *[n]; for (j = 0; j < n; ++j) { Y[j] = new double[n - j]; } //Считываем матрицу ifstream f1(file); while (!f1.eof()) { for (i = 0; i < n; ++i) { f1 >> X[i]; } for (j = 0; j < n; ++j) { f1 >> Y[0][j]; } } f1.close(); //Вычисление dY for (i = 1; i < n; ++i) { for (j = 0; j < n - i; ++j) { Y[i][j] = Y[i - 1][j + 1] - Y[i - 1][j]; } } for (i = 0; i < n; ++i) { cout << "X[" << i << "] = " << X[i] << ", Y[0][" << i << "] = " << Y[0][i] << endl; } for (i = 1; i < n; ++i) { for (j = 0; j < n - i; ++j) { cout << "dY" << i << " = " << Y[i][j] << endl; } } double *dY = new double[n]; for (i = 0; i < n; ++i) { dY[i] = Y[i][0]; } delete[] Y; double P = dY[0]; //Метод Ньютона for (i = 1; i < n; ++i) { P += (dY[i] / factorial(i)) * multiple_q(xx, X, i); } cout << "\nP = " << P << endl; delete[] X; delete[] dY; system("pause"); return 0; }
[ "SSH002@pirogov-aleksey" ]
SSH002@pirogov-aleksey
2808783b95d63951b861a97c372df0206a9c0bd9
4f23c24cbf6cdf8ac76d847eeea66b6aea5e9567
/include/nautilus/nscr_ana.h
9a5b1167d6e515c8736d291af6393b4108634494
[]
no_license
MatthewNg3416/Episodus
be2ef0f958274de2fd91e9f6954c9a76c23977aa
fe3ed5a5e92466f98e928c2eafd48faa6eb1b165
refs/heads/master
2021-09-13T07:39:04.985158
2018-04-26T16:23:32
2018-04-26T16:23:32
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,562
h
//---------------------------------------------------------------------------- // ObjectWindows - (C) Copyright 1991, 1993 by Borland International // Tutorial application -- step12dv.cpp //---------------------------------------------------------------------------- #ifndef __NSCR_ANA_H #define __NSCR_ANA_H #include <classlib\arrays.h> #include "nautilus\nscr_anx.h" #include "partage\NTArray.h" // // Définition de NSLigneArray (Array de NSLignes(s)) // //typedef TArrayAsVector<NSLigne> NSLignesArray; typedef vector<NSLigne*> NSLignesArray; typedef NSLignesArray::iterator NSLignesArrayIter; typedef NTArray<NSLigne> NSLigneArray; /* class NSLigneArray : public NSLignesArray { public : // Constructeurs NSLigneArray() : NSLignesArray() {} NSLigneArray(NSLigneArray& rv); // Destructeur virtual ~NSLigneArray(); // Opérateur = NSLigneArray& operator=(NSLigneArray src); void vider(); }; */ // // Définition de NSRectArray (Array de TRect(s)) // //typedef TArrayAsVector<TRect> NSRectsArray; typedef vector<NS_CLASSLIB::TRect*> NSRectsArray; typedef NSRectsArray::iterator NSRectsArrayIter; typedef NTArray<NS_CLASSLIB::TRect> NSRectArray; /* class NSRectArray : public NSRectsArray { public : // Constructeurs NSRectArray() : NSRectsArray() {} NSRectArray(NSRectArray& rv); // Destructeur virtual ~NSRectArray(); // Opérateur = NSRectArray& operator=(NSRectArray src); void vider(); }; */ #endif // __NSCR_ANA_H
[ "philippe.ameline@free.fr" ]
philippe.ameline@free.fr
0de3ed7d80fe4dbf77ec3e6d71bc90541a230c4e
d7e41f16df202fe917d0d6398cb7a0185db0bbac
/src/server/service/bot/acts/act_wait_input.cpp
d6df8112f0ea8b74f8128b3b0001b7c9101c51c0
[ "MIT" ]
permissive
npangunion/wise.kernel
77a60d4e7fcecd69721d9bd106d41f0e5370282a
a44f852f5e7ade2c5f95f5d615daaf154bc69468
refs/heads/master
2020-12-28T16:17:29.077050
2020-05-18T15:42:30
2020-05-18T15:42:30
238,401,519
1
0
null
null
null
null
UHC
C++
false
false
621
cpp
#include "stdafx.h" #include "act_wait_input.hpp" #include <wise/service/bot/agent.hpp> namespace wise { act_wait_input::act_wait_input(flow& owner, config& cfg) : act(owner, cfg) { load(); } void act_wait_input::on_begin() { // 잠시 대기... 나중에 더 보고 꼭 필요할 때 작업 // 네트워크로 진행을 제어할 예정이므로 크게 의미 없을 수 있다. } void act_wait_input::load() { auto ninput = get_config()["input"]; WISE_JSON_CHECK(!ninput.is_null() && ninput.is_string()); input_ = ninput.get<std::string>(); WISE_DEBUG("act_wait_input. input: {}", input_); } } // test
[ "npangunion@gmail.com" ]
npangunion@gmail.com
77730394c76a124b8b3522ad2b81793a01c1a679
3965dbe726debbd1347ae5bf284fdcab899a1f43
/LAB01/q4.cpp
fe43692a921d529d44bc4e975d836fd9f02d4a28
[]
no_license
chamad14/Muchamad-Rizki-Fadillah_FOP2020
68c9b1135805af12baf1aa919df5ca178d279ff4
8ba6fa47c6e6ccea94d0786d836bf5ef98417715
refs/heads/master
2023-02-10T11:00:17.618604
2020-12-31T04:01:54
2020-12-31T04:01:54
294,573,818
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
#include <iostream> using namespace std; int main() { double a = 17; double b = 23; double c = 49; //calculating the average cout << "average =" << (a + b + c) / 3 << endl; return 0; }
[ "rfadillah36@gmail.com" ]
rfadillah36@gmail.com
b77246c385c01a4be436577e1ae37e083ee52d70
1330bcb8ba752801b295edcd0e22443df8d30cbe
/src/SoundManager.cpp
d9550d0d7e70a6c3ff0736672347646db75e3e0d
[]
no_license
FonzTech/SphereBall
0d4402008f43929fab203e821b94ee4d03b30ef6
6fbf338892e44f7763d0719f0356e535a86daded
refs/heads/master
2021-09-23T05:34:29.598285
2021-09-21T15:57:47
2021-09-21T15:57:47
172,249,975
2
0
null
null
null
null
UTF-8
C++
false
false
1,666
cpp
#include "SoundManager.h" std::shared_ptr<SoundManager> SoundManager::singleton = nullptr; SoundManager::SoundManager() { volumeLevels[KEY_SETTING_MUSIC] = 20.0f; volumeLevels[KEY_SETTING_SOUND] = 20.0f; } std::shared_ptr<sf::SoundBuffer> SoundManager::getSoundBuffer(const std::string& fname) { // Check if sound buffer has been already loaded const auto& iterator = soundBuffers.find(fname); if (iterator != soundBuffers.end()) { #if NDEBUG || _DEBUG printf("SoundBuffer %s has been reused\n", fname.c_str()); #endif return iterator->second; } // Otherwise load the sound buffer into memory std::shared_ptr<sf::SoundBuffer> sb = std::make_shared<sf::SoundBuffer>(); if (!sb->loadFromFile("sounds/" + fname + ".ogg")) { #if NDEBUG || _DEBUG printf("SoundBuffer %s has NOT been loaded\n", fname.c_str()); #endif return nullptr; } // Save the new loaded sound buffer, then return it return soundBuffers[fname] = sb; } std::shared_ptr<sf::Sound> SoundManager::getSound(const std::string& fname) { // Get sound buffer from its routine std::shared_ptr<sf::SoundBuffer> sb = this->getSoundBuffer(fname); // Check if sound buffer creation has encountered an error if (sb == nullptr) { #if NDEBUG || _DEBUG printf("Sound %s could NOT be created\n", fname.c_str()); #endif return std::make_shared<sf::Sound>(); } // Return the handleable sound return std::make_shared<sf::Sound>(*sb.get()); } void SoundManager::updateVolumeLevel(const bool isMusic, const f32 stepValue) { f32* value = &volumeLevels[isMusic ? KEY_SETTING_MUSIC : KEY_SETTING_SOUND]; *value = std::max(0.0f, std::min(*value + stepValue, 100.0f)); }
[ "9438351+FonzTech@users.noreply.github.com" ]
9438351+FonzTech@users.noreply.github.com
bfd2fb546ab7160ab47eec372c58db8cd15fb25b
d499dcac321e01e82d815056b17eaf977c25b668
/DigiExam-WebClient/platforms/electron/node/PreConditionTests/win/illegal_processes_test.h
b919f9f02d11fb0659a944337f2cf192e1203295
[]
no_license
zulln/Electron
c06947382244c650e4d60dfb1707d67ba05dbd2b
d825d47c933c4be75544c47d8b29727b65924c43
refs/heads/master
2021-05-31T10:06:18.068068
2016-01-02T20:55:04
2016-01-02T20:55:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,143
h
#ifndef ILLEGAL_PROCESSES_TEST_H #define ILLEGAL_PROCEAASES_TEST_H // // adminPermissionTest.h // DigiExam Solutions AB // // Created by Amar Krupalija on 2015-10-21. // Copyright (c) 2015 DigiExam Solutions AB. All rights reserved. // /*! * @brief Checks that the application is started as Administrator. */ #include "../base_precondition_test.h" #include "../test_object_factory.h" #include <tlhelp32.h> #include <algorithm> #include <vector> namespace precondition { class IllegalProcessesTest : public BasePreConditionTest { public: void startTest(Local<Function> callback); bool isFailFatal(); bool isSuccess(); std::string failTitle(); std::string failMessage(); private: bool _isSuccess = false; bool _isFailFatal = true; std::string _failTitle = "Check for processes that interfers with DigiExam."; std::string _failMessage = "Processes that interfer with DigiExam was found."; //std::string _failMessage2 = "Please close the following processes and restart DigiExam:"; void TerminateIllegalProcesses(std::string filename); bool isLegal(std::string process, int pid); void GetProcessList(); }; } #endif
[ "amc0kru@gmail.com" ]
amc0kru@gmail.com
853a122e3954b886cc8d19a2a923c8ba8ab8acea
957fc487933007b8123d1b975e6221c861b12b99
/lce-test/util/successor/binsearch.hpp
235def8d7117667bb1f50e1ace5d95e9994ce817
[ "BSD-2-Clause" ]
permissive
herlez/lce-test
8b63990f4fd3e5a8715b8b2a1f3a004ba6eaced1
b52e00a2918b0ef9e3cdbaae731fabad89ec6754
refs/heads/master
2023-05-13T16:48:31.285748
2022-08-16T09:05:01
2022-08-16T09:05:01
183,403,442
5
3
BSD-2-Clause
2023-05-07T21:26:22
2019-04-25T09:37:58
C++
UTF-8
C++
false
false
3,014
hpp
#pragma once #include "helpers/util.hpp" #include "result.hpp" namespace stash { namespace pred { // the "bs" data structure for successor queries template<typename array_t, typename item_t> class binsearch { private: const array_t* m_array; size_t m_num; item_t m_min; item_t m_max; public: inline binsearch() : m_array(nullptr), m_num(0), m_min(), m_max() { } inline binsearch(binsearch&& other) { *this = other; } inline binsearch(const binsearch& other) { *this = other; } inline binsearch(const array_t& array) : m_num(array.size()), m_min(array[0]), m_max(array[m_num-1]), m_array(&array) { assert_sorted_ascending(array); } inline binsearch& operator=(binsearch&& other) { m_array = other.m_array; m_num = other.m_num; m_min = other.m_min; m_max = other.m_max; return *this; } inline binsearch& operator=(const binsearch& other) { m_array = other.m_array; m_num = other.m_num; m_min = other.m_min; m_max = other.m_max; return *this; } // finds the greatest element less than OR equal to x inline result predecessor(const item_t x) const { if(unlikely(x < m_min)) return result { false, 0 }; if(unlikely(x >= m_max)) return result { true, m_num-1 }; size_t p = 0; size_t q = m_num - 1; while(p < q - 1) { assert(x >= (*m_array)[p]); assert(x < (*m_array)[q]); const size_t m = (p + q) >> 1ULL; const bool le = ((*m_array)[m] <= x); /* the following is a fast form of: if(le) p = m; else q = m; */ const size_t le_mask = -size_t(le); const size_t gt_mask = ~le_mask; if(le) assert(le_mask == SIZE_MAX && gt_mask == 0ULL); else assert(gt_mask == SIZE_MAX && le_mask == 0ULL); p = (le_mask & m) | (gt_mask & p); q = (gt_mask & m) | (le_mask & q); } return result { true, p }; } // finds the smallest element greater than OR equal to x inline result successor(const item_t x) const { if(unlikely(x <= m_min)) return result { true, 0 }; if(unlikely(x > m_max)) return result { false, 0 }; size_t p = 0; size_t q = m_num - 1; while(p < q - 1) { assert(x > (*m_array)[p]); assert(x <= (*m_array)[q]); const size_t m = (p + q) >> 1ULL; const bool lt = ((*m_array)[m] < x); /* the following is a fast form of: if(lt) p = m; else q = m; */ const size_t lt_mask = -size_t(lt); const size_t ge_mask = ~lt_mask; p = (lt_mask & m) | (ge_mask & p); q = (ge_mask & m) | (lt_mask & q); } return result { true, q }; } }; }}
[ "patrick.dinklage@tu-dortmund.de" ]
patrick.dinklage@tu-dortmund.de
95e28ad84f17821b43c0aab2f3261d9e88b44786
32be88dc03f0989838ca6fcd53b0e1aa579176a1
/poj/p1704/p1704.cpp
964c3550ced312a4029b67d2bc991da5585e65e6
[]
no_license
wangsenyuan/poj
ad7c09f3efc07f992e2532323a033bc55bc48462
b38c5e3bd552a3276fd6dcc95bf5912bd732994d
refs/heads/master
2021-01-23T14:57:47.961990
2015-07-05T14:27:45
2015-07-05T14:27:45
35,315,170
0
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
/* * p1704.cpp * * Created on: 2015年6月1日 * Author: senyuanwang */ #include "p1704.h" #include <iostream> #include <algorithm> using namespace std; namespace p1704 { const int MAX_N = 1000; int N, P[MAX_N]; bool solve_problem() { if (N % 2 == 1) P[N++] = 0; sort(P, P + N); int x = 0; for (int i = 0; i + 1 < N; i += 2) { x ^= (P[i + 1] - P[i] - 1); } return x == 0; } void solve() { int t; cin >> t; for(int i = 0; i < t; i++) { cin >> N; for(int j = 0; j < N; j++) { cin >> P[j]; } bool res = solve_problem(); if(res) { cout << "Bob will win" << endl; } else { cout << "Georgia will win" << endl; } } } }
[ "wang.senyuan@gmail.com" ]
wang.senyuan@gmail.com
c48a6041749760e45783ca9702f99abd777aca69
85a50ab1eef4724ee83ec19c5af708b02cb0dfc3
/externals/awesomium-1.7/include/Awesomium/JSValue.h
1056edf0d47ea3c7ddf7df17a43550462918a992
[]
no_license
mattrudder/Talon
5ca428dbcd4e5c5879978640205fb43c3074aca4
650cc522f7854bd52da308042b42a2a4bb1ca728
refs/heads/master
2021-01-21T19:35:09.831748
2012-07-26T16:01:00
2012-07-26T16:01:00
3,830,382
2
0
null
null
null
null
UTF-8
C++
false
false
3,414
h
/// /// @file JSValue.h /// /// @brief The header for the JSValue class. /// /// @author /// /// This file is a part of Awesomium, a Web UI bridge for native apps. /// /// Website: <http://www.awesomium.com> /// /// Copyright (C) 2012 Khrona. All rights reserved. Awesomium is a /// trademark of Khrona. /// #ifndef AWESOMIUM_JS_VALUE_H_ #define AWESOMIUM_JS_VALUE_H_ #pragma once #include <Awesomium/Platform.h> #include <Awesomium/WebString.h> #include <Awesomium/JSObject.h> #include <Awesomium/JSArray.h> namespace Awesomium { struct VariantValue; /// /// @brief Represents a value in JavaScript. /// class OSM_EXPORT JSValue { public: /// Create an empty JSValue ('undefined' by default). JSValue(); /// Create a JSValue initialized with a boolean. explicit JSValue(bool value); /// Create a JSValue initialized with an integer. explicit JSValue(int value); /// Create a JSValue initialized with a double. explicit JSValue(double value); /// Create a JSValue initialized with a string. JSValue(const WebString& value); /// Create a JSValue initialized with an object. JSValue(const JSObject& value); /// Create a JSValue initialized with an array. JSValue(const JSArray& value); JSValue(const JSValue& original); ~JSValue(); JSValue& operator=(const JSValue& rhs); /// Get the global Undefined JSValue instance static const JSValue& Undefined(); /// Get the global Null JSValue instance static const JSValue& Null(); /// Returns whether or not this JSValue is a boolean. bool IsBoolean() const; /// Returns whether or not this JSValue is an integer. bool IsInteger() const; /// Returns whether or not this JSValue is a double. bool IsDouble() const; /// Returns whether or not this JSValue is a number (integer or double). bool IsNumber() const; /// Returns whether or not this JSValue is a string. bool IsString() const; /// Returns whether or not this JSValue is an array. bool IsArray() const; /// Returns whether or not this JSValue is an object. bool IsObject() const; /// Returns whether or not this JSValue is null. bool IsNull() const; /// Returns whether or not this JSValue is undefined. bool IsUndefined() const; /// Returns this JSValue as a string (converting if necessary). WebString ToString() const; /// Returns this JSValue as an integer (converting if necessary). int ToInteger() const; /// Returns this JSValue as a double (converting if necessary). double ToDouble() const; /// Returns this JSValue as a boolean (converting if necessary). bool ToBoolean() const; /// /// Gets a reference to this JSValue's array value (will assert if not /// an array type) /// JSArray& ToArray(); /// /// Gets a constant reference to this JSValue's array value (will assert /// if not an array type) /// const JSArray& ToArray() const; /// /// Gets a reference to this JSValue's object value (will assert if not /// an object type) /// JSObject& ToObject(); /// /// Gets a constant reference to this JSValue's object value (will /// assert if not an object type) /// const JSObject& ToObject() const; protected: VariantValue* value_; }; } // namespace Awesomium #endif // AWESOMIUM_JS_VALUE_H_
[ "matt@mattrudder.com" ]
matt@mattrudder.com
59ba7b8bd72d3c25747fb319534f54dacdbe0906
df375ff9364e55558e9c889ed970bdc54b286ff2
/数据结构课设/停车场.cpp
e0671c55970918117862a02d249418f3a50665ab
[]
no_license
1341329029/Class_setting
e6c2bfc3e66bd0b004b709fd044901ad5e652986
270eb12e5e135d0aca1164a7d3240cc36d50e17b
refs/heads/master
2020-04-20T15:55:50.815311
2019-02-03T13:16:11
2019-02-03T13:16:11
168,945,258
1
0
null
null
null
null
GB18030
C++
false
false
7,632
cpp
#include <stdio.h> #include <malloc.h> #define N 2 /*停车场内最多的停车数*/ #define Price 2 /*每单位停车费用*/ typedef struct { int CarNo[N]; /*车牌号*/ int CarTime[N]; /*进场时间*/ int top; /*栈指针*/ } SqStack; /*定义顺序栈类型*/ /*定义链队类型*/ typedef struct qnode { int CarNo; /*车牌号*/ int CarTime; /*进场时间*/ struct qnode *next; } QNode; typedef struct { QNode *front; /*队首和队尾指针*/ QNode *rear; } LiQueue; /*顺序栈的基本运算算法*/ void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } int StackEmpty(SqStack *s)//判断栈是否为空 { return(s->top==-1); } int StackFull(SqStack *s)//判断栈是否已满(停车场是否已满) { return(s->top==N-1); } /*S中的插入新元素*/ int Push(SqStack *&s,int e1,int e2) //入栈 { if (s->top==N-1) return 0; s->top++; s->CarNo[s->top]=e1;//车牌号入栈 s->CarTime[s->top]=e2;//时间入栈 return 1; } /*删除S的栈顶元素,并用e1,e2返回其值*/ int Pop(SqStack *&s,int &e1,int &e2) { if (s->top==-1) return 0; e1=s->CarNo[s->top]; e2=s->CarTime[s->top]; s->top--; return 1; } /*输出停车场使用状况*/ void DispStack(SqStack *s) { int i; for (i=0;i<=s->top;i++) { printf(" %d\t %d\t\t\t %d\t",i+1,s->CarNo[i],s->CarTime[i]); printf("\n"); } } /*以下为链队列的基本运算算法*/ void InitQueue(LiQueue *&q) { q=(LiQueue *)malloc(sizeof(LiQueue)); q->front=q->rear=NULL; } int QueueLength(LiQueue *q) { int n=0; QNode *p=q->front; while (p!=NULL) { n++; p=p->next; } return(n); } //判断队列是否为空 int QueueEmpty(LiQueue *q) { if (q->rear==NULL) return 1; else return 0; } void enQueue(LiQueue *&q, int e,int w) { QNode *s; s=(QNode *)malloc(sizeof(QNode)); s->CarNo=e; s->CarTime=w; s->next=NULL; if (q->rear==NULL) /*若链队为空,则新结点是队首结点又是队尾结点*/ q->front=q->rear=s; else { q->rear->next=s; /*将*s结点链到队尾,rear指向它*/ q->rear=s; } } int deQueue(LiQueue *&q,int &e,int &w) { QNode *t; if (q->rear==NULL) /*队列为空*/ return 0; if (q->front==q->rear) /*队列中只有一个结点时*/ { t=q->front; q->front=q->rear=NULL; } else /*队列中有多个结点时*/ { t=q->front; q->front=q->front->next; } e=t->CarNo; w=t->CarTime; free(t); return 1; } /*输出便道使用情况*/ void DisplayQueue(LiQueue *q) { int i=1; QNode *p=q->front; while (p!=NULL) { printf(" %d\t %d\t\t\t %d\t",i,p->CarNo,p->CarTime); printf("\n"); p=p->next ; i++; } } int main() { char choose; /*用于选择命令*/ int no,e1,time,e2,kind; /*用于存放车牌号、当前停车时刻*/ int i,j; SqStack *St,*St1; /*临时栈St1,当停车场中间的车要推出去时,用于倒车*/ LiQueue *Qu; InitStack(St); InitStack(St1); InitQueue(Qu); puts("\n 欢迎使用停车场管理系统 "); puts("\n "); puts("\n【输入提示】:汽车状态由A、D、E 表示。其中,A:表示汽车到达 D:表示汽车离去, "); puts("\n C:表示显示停车场便道情况E:表示输出结束。每次输入的数据由三项构成,即:( "); puts("\n 汽车状态,车牌号,当前时刻)数据项之间以逗号分开。 例如输入示范:A,1,5 "); puts("\n正在读取汽车信息...\n"); do { printf("\n*****************************************************************"); printf("\n请分别输入汽车状态(A/D/C/E)、车牌号和当前时刻(数据之间以逗号分开):\n"); scanf(" %c,%d,%d",&choose,&no,&time); switch(choose) { /*************************** 汽车到达 ******************************/ case 'A': case 'a': if (!StackFull(St)) /*停车场不满*/ { Push(St,no,time); printf("该车在停车场中的位置是:%d\n",St->top+1); printf( "车牌号:\t\t%d\n", no ); printf( "进入时间:\t%d\n",time ); puts( "是否收费:\t是" ); } else /*停车场满*/ { enQueue(Qu,no,time); printf("\n停车场已满,该车进入便道,在便道中的位置是:%d\n",QueueLength(Qu)); printf( "车牌号:\t\t%d\n", no ); printf( "进入时间:\t%d\n",time ); puts( "是否收费:\t否" ); } break; /************************* 汽车离开 ********************************/ case 'D': case 'd': printf("\n请输入车的类别【车的类别:1.代表小汽车 2.代表客车 3.代表卡车】:\n"); scanf("%d",&kind); for (i=0;i<=St->top && St->CarNo[i]!=no;i++); if (i>St->top) /*要离开的汽车在便道上*/ { /*汽车可以直接从便道上开走,此时排在它前面的汽车要先开走让路,然后再依次排到队尾*/ while (Qu->front->CarNo!=no ) { enQueue(Qu,Qu->front->CarNo,Qu->front->CarTime ); // deQueue(Qu,Qu->front->CarNo ); Qu->front = Qu->front->next ; } deQueue(Qu,no,time); printf("\n便道上车牌号为%d的汽车已离开!\n",no); puts( "[便道使用情况]\n" ); puts( "[车位]\t[车牌号]\t[进入(开始计费)时间]\n"); DisplayQueue(Qu); printf("\n"); } else /*要离开的汽车在停车场中*/ { for (j=i;j<=St->top;j++) { Pop(St,e1,e2); /*e1,e2用来返回被删元素的车牌号和停车时刻*/ Push(St1,e1,e2); /*倒车到临时栈St1中,将e1,e2插入到临时栈中*/ } Pop(St,e1,e2); /*该汽车离开*/ printf("\n车牌号为%d的汽车停车时间为:%d。停车费用为:%d\n",no,time-e2,(time-e2)*Price*kind); /*对小汽车而言:当前时刻 减去 该车当时停车的时刻,再乘以价格就是费用,而对于客车和卡车而言,就要乘以kind倍小汽车的价格*/ while (!StackEmpty(St1)) /*将临时栈St1重新回到St中*/ { Pop(St1,e1,e2); Push(St,e1,e2); } if (!QueueEmpty(Qu)) /*队不空时,将队头进栈St*/ { deQueue(Qu,e1,time); Push(St,e1,time); /*以当前时间开始计费*/ } printf("\n当前停车场中的车辆的车牌号分别是:"); puts( "[停车场使用情况]\n" ); puts( "[车位]\t[车牌号]\t[进入(开始计费)时间]\n"); //输出停车场中的车辆 DispStack(St); } break; /************************ 查看停车场 *********************************/ case 'C': case 'c': if (!StackEmpty(St)) //显示停车场情况 { puts( "[停车场使用情况]\n" ); puts( "[车位]\t[车牌号]\t[进入(开始计费)时间]\n"); //输出停车场中的车辆 DispStack(St); printf("\n"); } else printf("\n当前停车场中无车辆\n\n"); if (!QueueEmpty(Qu)) { puts( "[便道使用情况]\n" ); puts( "[车位]\t[车牌号]\t[进入(开始计费)时间]\n"); DisplayQueue(Qu); } else printf("\n当前便车道中无车辆\n\n"); break; /************************ 结束 *********************************/ case 'E': case 'e': printf("\n正在退出系统...\n"); break; /************************ 结束 *********************************/ default: /*其他情况*/ printf("输入的命令错误!\n"); break; } } while(choose!='E'&&choose!='e'); }
[ "1158806590@qq.com" ]
1158806590@qq.com
2317bbae75a0c87bd7361eb6c64c0fe4c335ae99
a5e43e88b4c93c396d33585837975cbf7188d08c
/GenericDBFile.cc
14e3e4f644de3efacfb9706482c046673ad2fca2
[]
no_license
vaibs28/Database-System-Implementation
4d919d325679af0cd81e71f91414df24a138d72c
09c3c6381bb3c8268833b199ca501ea42f58d460
refs/heads/master
2022-07-03T21:39:43.164570
2020-05-10T08:27:02
2020-05-10T08:27:02
236,252,186
1
0
null
null
null
null
UTF-8
C++
false
false
243
cc
// // Created by Vaibhav Sahay on 25/02/20. // #include "GenericDBFile.h" //initializing the static variables to false. Will be used in load method to check if the page is being read by other users. bool GenericDBFile::isBeingRead = false;
[ "vsahay28@gmail.com" ]
vsahay28@gmail.com
5a97045b3504a666897ef176ac2be1d6d7981c25
4434dd8bf1d177c155300860d77fb77c3d6c65dd
/watchman/test/InMemoryViewTest.cpp
078ea6b1b6665873ff227e29aad35bed2bf7807d
[ "MIT" ]
permissive
facebook/watchman
528fc282642d29ea4effcc9f7bb9cd04547e1248
0f6c285a58df680c5586593b87c779907aa4a0ac
refs/heads/main
2023-08-31T21:32:14.180520
2023-08-31T01:07:08
2023-08-31T01:07:08
6,930,489
10,583
1,063
MIT
2023-08-16T18:35:09
2012-11-29T23:35:52
C++
UTF-8
C++
false
false
17,002
cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "watchman/InMemoryView.h" #include <folly/executors/ManualExecutor.h> #include <folly/portability/GTest.h> #include "watchman/fs/FSDetect.h" #include "watchman/query/GlobTree.h" #include "watchman/query/Query.h" #include "watchman/query/QueryContext.h" #include "watchman/root/Root.h" #include "watchman/test/lib/FakeFileSystem.h" #include "watchman/test/lib/FakeWatcher.h" #include "watchman/watcher/Watcher.h" #include "watchman/watchman_dir.h" #include "watchman/watchman_file.h" namespace { using namespace watchman; Configuration getConfiguration(bool usePwalk) { json_ref json = json_object(); json_object_set(json, "enable_parallel_crawl", json_boolean(usePwalk)); return Configuration{std::move(json)}; } class InMemoryViewTest : public testing::TestWithParam<bool /* pwalk */> { public: using Continue = InMemoryView::Continue; const w_string root_path{FAKEFS_ROOT "root"}; FakeFileSystem fs; Configuration config = getConfiguration(GetParam()); std::shared_ptr<FakeWatcher> watcher = std::make_shared<FakeWatcher>(fs); std::shared_ptr<InMemoryView> view = std::make_shared<InMemoryView>(fs, root_path, config, watcher); PendingCollection& pending = view->unsafeAccessPendingFromWatcher(); InMemoryViewTest() { pending.lock()->ping(); } }; TEST_P(InMemoryViewTest, can_construct) { fs.defineContents({ FAKEFS_ROOT "root", }); Root root{ fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}}; } TEST_P(InMemoryViewTest, drive_initial_crawl) { fs.defineContents({FAKEFS_ROOT "root/dir/file.txt"}); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); InMemoryView::IoThreadState state{std::chrono::minutes(5)}; // This will perform the initial crawl. EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); Query query; query.fieldList.add("name"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"", 1}); QueryContext ctx{&query, root, false}; view->pathGenerator(&query, &ctx); EXPECT_EQ(2, ctx.resultsArray.size()); EXPECT_STREQ("dir", ctx.resultsArray.at(0).asCString()); EXPECT_STREQ("dir/file.txt", ctx.resultsArray.at(1).asCString()); } TEST_P(InMemoryViewTest, respond_to_watcher_events) { getLog().setStdErrLoggingLevel(DBG); fs.defineContents({FAKEFS_ROOT "root/dir/file.txt"}); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"", 1}); QueryContext ctx1{&query, root, false}; view->pathGenerator(&query, &ctx1); EXPECT_EQ(2, ctx1.resultsArray.size()); auto one = ctx1.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); auto two = ctx1.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(0, two.get("size").asInt()); // Update filesystem and ensure the query results don't update. fs.updateMetadata(FAKEFS_ROOT "root/dir/file.txt", [&](FileInformation& fi) { fi.size = 100; }); pending.lock()->ping(); EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); QueryContext ctx2{&query, root, false}; view->pathGenerator(&query, &ctx2); one = ctx2.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); two = ctx2.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(0, two.get("size").asInt()); // Now notify the iothread of the change, process events, and assert the view // updates. pending.lock()->add( FAKEFS_ROOT "root/dir/file.txt", {}, W_PENDING_VIA_NOTIFY); pending.lock()->ping(); EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); QueryContext ctx3{&query, root, false}; view->pathGenerator(&query, &ctx3); one = ctx3.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); two = ctx3.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(100, two.get("size").asInt()); } TEST_P(InMemoryViewTest, wait_for_respond_to_watcher_events) { getLog().setStdErrLoggingLevel(DBG); fs.defineContents({FAKEFS_ROOT "root/dir/file.txt"}); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"", 1}); QueryContext ctx1{&query, root, false}; view->pathGenerator(&query, &ctx1); EXPECT_EQ(2, ctx1.resultsArray.size()); auto one = ctx1.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); auto two = ctx1.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(0, two.get("size").asInt()); // Update filesystem and ensure the query results don't update. fs.updateMetadata(FAKEFS_ROOT "root/dir/file.txt", [&](FileInformation& fi) { fi.size = 100; }); pending.lock()->ping(); EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); QueryContext ctx2{&query, root, false}; view->pathGenerator(&query, &ctx2); one = ctx2.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); two = ctx2.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(0, two.get("size").asInt()); // Now notify the iothread of the change, process events, and assert the view // updates. pending.lock()->add( FAKEFS_ROOT "root/dir/file.txt", {}, W_PENDING_VIA_NOTIFY); pending.lock()->ping(); EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); QueryContext ctx3{&query, root, false}; view->pathGenerator(&query, &ctx3); one = ctx3.resultsArray.at(0); EXPECT_STREQ("dir", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); two = ctx3.resultsArray.at(1); EXPECT_STREQ("dir/file.txt", two.get("name").asCString()); EXPECT_EQ(100, two.get("size").asInt()); } TEST_P( InMemoryViewTest, syncToNow_does_not_return_until_cookie_dir_is_crawled) { getLog().setStdErrLoggingLevel(DBG); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"file.txt", 1}); fs.defineContents({FAKEFS_ROOT "root/file.txt"}); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); // Initial crawl InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); // Somebody has updated a file. fs.updateMetadata( FAKEFS_ROOT "root/file.txt", [&](FileInformation& fi) { fi.size = 100; }); // We have not seen the new size, so the size should be zero. { QueryContext ctx{&query, root, false}; view->pathGenerator(&query, &ctx); EXPECT_EQ(1, ctx.resultsArray.size()); auto one = ctx.resultsArray.at(0); EXPECT_STREQ("file.txt", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); } // A query starts, but the watcher has not notified us. auto executor = folly::ManualExecutor{}; // Query, to synchronize, writes a cookie to the filesystem. auto syncFuture1 = root->cookies.sync().via(folly::Executor::getKeepAliveToken(executor)); // But we want to know exactly when it unblocks: auto syncFuture = std::move(syncFuture1).thenValue([&](auto) { // We are running in the iothread, so it is unsafe to access // InMemoryView, but this test is trying to simulate another query's thread // being unblocked too early. Access the ViewDatabase unsafely because the // iothread currently has it locked. That's okay because this test is // single-threaded. const auto& viewdb = view->unsafeAccessViewDatabase(); auto* dir = viewdb.resolveDir(FAKEFS_ROOT "root"); auto* file = dir->getChildFile("file.txt"); return file->stat.size; }); // Have Watcher publish change to "/root" but this watcher does not have // per-file notifications. pending.lock()->add( FAKEFS_ROOT "root", {}, W_PENDING_VIA_NOTIFY | W_PENDING_NONRECURSIVE_SCAN); executor.drain(); EXPECT_FALSE(syncFuture.isReady()); // This will notice the cookie and unblock. EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); executor.drain(); EXPECT_TRUE(syncFuture.isReady()); EXPECT_EQ(100, std::move(syncFuture).get()); } TEST_P( InMemoryViewTest, syncToNow_does_not_return_until_all_pending_events_are_processed) { getLog().setStdErrLoggingLevel(DBG); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"dir/file.txt", 1}); fs.defineContents({FAKEFS_ROOT "root/dir/file.txt"}); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); // Initial crawl InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); // Somebody has updated a file. fs.updateMetadata(FAKEFS_ROOT "root/dir/file.txt", [&](FileInformation& fi) { fi.size = 100; }); // We have not seen the new size, so the size should be zero. { QueryContext ctx{&query, root, false}; view->pathGenerator(&query, &ctx); EXPECT_EQ(1, ctx.resultsArray.size()); auto one = ctx.resultsArray.at(0); EXPECT_STREQ("dir/file.txt", one.get("name").asCString()); EXPECT_EQ(0, one.get("size").asInt()); } // A query starts, but the watcher has not notified us. auto executor = folly::ManualExecutor{}; // Query, to synchronize, writes a cookie to the filesystem. auto syncFuture1 = root->cookies.sync().via(folly::Executor::getKeepAliveToken(executor)); // But we want to know exactly when it unblocks: auto syncFuture = std::move(syncFuture1).thenValue([&](auto) { // We are running in the iothread, so it is unsafe to access // InMemoryView, but this test is trying to simulate another query's thread // being unblocked too early. Access the ViewDatabase unsafely because the // iothread currently has it locked. That's okay because this test is // single-threaded. const auto& viewdb = view->unsafeAccessViewDatabase(); auto* dir = viewdb.resolveDir(FAKEFS_ROOT "root/dir"); auto* file = dir->getChildFile("file.txt"); return file->stat.size; }); // Have Watcher publish its change events but this watcher does not have // per-file notifications. // The Watcher event from the modified file, which was sequenced before the // cookie write. pending.lock()->add( FAKEFS_ROOT "root/dir", {}, W_PENDING_VIA_NOTIFY | W_PENDING_NONRECURSIVE_SCAN); // The Watcher event from the cookie. pending.lock()->add( FAKEFS_ROOT "root", {}, W_PENDING_VIA_NOTIFY | W_PENDING_NONRECURSIVE_SCAN); // This will notice the cookie and unblock. EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); executor.drain(); EXPECT_TRUE(syncFuture.isReady()); EXPECT_EQ(100, std::move(syncFuture).get()); } TEST_P( InMemoryViewTest, syncToNow_does_not_return_until_initial_crawl_completes) { getLog().setStdErrLoggingLevel(DBG); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"dir/file.txt", 1}); fs.defineContents({ FAKEFS_ROOT "root/dir/file.txt", }); // TODO: add a mode for defining FileInformation with the hierarchy fs.updateMetadata(FAKEFS_ROOT "root/dir/file.txt", [&](FileInformation& fi) { fi.size = 100; }); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); auto executor = folly::ManualExecutor{}; // A query is immediately issued. To synchronize, a cookie is written. auto syncFuture1 = root->cookies.sync().via(folly::Executor::getKeepAliveToken(executor)); // But we want to know exactly when it unblocks: auto syncFuture = std::move(syncFuture1).thenValue([&](auto) { // We are running in the iothread, so it is unsafe to access // InMemoryView, but this test is trying to simulate another query's thread // being unblocked too early. Access the ViewDatabase unsafely because the // iothread currently has it locked. That's okay because this test is // single-threaded. const auto& viewdb = view->unsafeAccessViewDatabase(); auto* dir = viewdb.resolveDir(FAKEFS_ROOT "root/dir"); auto* file = dir->getChildFile("file.txt"); EXPECT_EQ(100, file->stat.size); }); executor.drain(); EXPECT_FALSE(syncFuture.isReady()); // Initial crawl... InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); executor.drain(); // ... should unblock the cookie when it's done. EXPECT_TRUE(syncFuture.isReady()); std::move(syncFuture).get(); } TEST_P(InMemoryViewTest, waitUntilReadyToQuery_waits_for_initial_crawl) { getLog().setStdErrLoggingLevel(DBG); Query query; query.fieldList.add("name"); query.fieldList.add("size"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"dir/file.txt", 1}); fs.defineContents({ FAKEFS_ROOT "root/dir/file.txt", }); // TODO: add a mode for defining FileInformation with the hierarchy fs.updateMetadata(FAKEFS_ROOT "root/dir/file.txt", [&](FileInformation& fi) { fi.size = 100; }); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); auto syncFuture = view->waitUntilReadyToQuery(); EXPECT_FALSE(syncFuture.isReady()); // Initial crawl... InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); // Unblocks! std::move(syncFuture).get(); } TEST_P(InMemoryViewTest, directory_removal_does_not_report_parent) { getLog().setStdErrLoggingLevel(DBG); fs.defineContents({ FAKEFS_ROOT "root/dir/foo/file.txt", }); auto root = std::make_shared<Root>( fs, root_path, "fs_type", w_string_to_json("{}"), config, view, [] {}); auto beforeFirstStep = view->getMostRecentRootNumberAndTickValue(); InMemoryView::IoThreadState state{std::chrono::minutes(5)}; EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); Query query; query.fieldList.add("name"); query.paths.emplace(); query.paths->emplace_back(QueryPath{"", 1}); QueryContext ctx1{&query, root, false}; ctx1.since = QuerySince::Clock{false, beforeFirstStep.ticks}; view->timeGenerator(&query, &ctx1); ASSERT_EQ(3, ctx1.resultsArray.size()); auto one = ctx1.resultsArray.at(0); EXPECT_EQ("dir/foo/file.txt", ctx1.resultsArray.at(0).asString()); EXPECT_EQ("dir/foo", ctx1.resultsArray.at(1).asString()); EXPECT_EQ("dir", ctx1.resultsArray.at(2).asString()); auto beforeChanges = view->getMostRecentRootNumberAndTickValue(); // Now remove all of foo/ and notify the iothread of the change as if we are // the FSEvents watcher. fs.removeRecursively(FAKEFS_ROOT "root/dir/foo"); pending.lock()->add( FAKEFS_ROOT "root/dir/foo", {}, W_PENDING_VIA_NOTIFY | W_PENDING_NONRECURSIVE_SCAN); pending.lock()->ping(); EXPECT_EQ(Continue::Continue, view->stepIoThread(root, state, pending)); QueryContext ctx2{&query, root, false}; ctx2.since = QuerySince::Clock{false, beforeChanges.ticks}; view->timeGenerator(&query, &ctx2); ASSERT_EQ(2, ctx2.resultsArray.size()); EXPECT_EQ("dir/foo", ctx2.resultsArray.at(0).asString()); EXPECT_EQ("dir/foo/file.txt", ctx2.resultsArray.at(1).asString()); // iothread will not update the view for dir/ until it sees an actual // notification from the watcher for that directory. } INSTANTIATE_TEST_CASE_P( InMemoryViewTests, InMemoryViewTest, testing::Values(false, true)); } // namespace
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
24b9c68a9f1fb28f7d8c53f144351b2736e8f574
0ae9207f86761b24137eabd2e60298e4a437f564
/lib/robot/device/collider/Collider.h
3102bfe07809ba3487d395c9cdf40aa8328abc0e
[]
no_license
allen8807/RobotLib
eb63aadbf8383005121210bcba29ce0c012b6c7a
606acd32973c13c7e4db876c628e54257ff40985
refs/heads/master
2021-01-01T18:23:31.289277
2013-12-10T01:30:06
2013-12-10T01:30:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,183
h
/*************************************************************************** * SEU RoboCup Simulation Team * ------------------------------------------------- * Copyright (c) Southeast University , Nanjing, China. * All rights reserved. * * $Id$ * ****************************************************************************/ #ifndef _ROBOT_DEVICE_COLLIDER_COLLIDER_H_ #define _ROBOT_DEVICE_COLLIDER_COLLIDER_H_ #include "../Device.h" namespace robot { namespace device { namespace collider { class Collider : public Device { public: Collider() { mLocalMat.identity(); } void addNotCollideWithColliderName(const std::string& name,bool isAdd) { if ( isAdd ){ mNotCollideWithSet.insert(name); } else{ mNotCollideWithSet.erase(name); } } void setLocalPosition(const Vector3f& p) { mLocalMat.p() = p; } void setRotation(const Vector3f& r) { mLocalMat.rotationX(r.x()); mLocalMat.rotateLocalY(r.y()); mLocalMat.rotateLocalZ(r.z()); } /** * return ZERO, the size function should depend on * inherited collider * * @return the size of the collider */ virtual Vector3f size() const { return Vector3f(0,0,0); } protected: set<string> mNotCollideWithSet; TransMatrixf mLocalMat; }; } /* namespace collider */ } /* namespace device */ } /* namespace robot */ #endif /* _ROBOT_DEVICE_COLLIDER_COLLIDER_H_ */
[ "egret8807@126.com" ]
egret8807@126.com
ea73807c5f80ae21150c18a04d0ea684dd6e691c
bb8bf492a53ef1620ee70b41a79db4b7f0bd22a1
/src/BBoxRt/bbox/rt/net/AdapterInfo.cpp
521f49b0cd9259e1c30745ceab5b3c07c052bf2b
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kezenator/camplight
b2dd974771284df9491a238c07c278411538caae
3ee0697912f5f0c000bdfe306070b35c9a24a1bd
refs/heads/master
2021-08-16T11:52:31.549141
2021-01-19T10:11:06
2021-01-19T10:11:06
71,421,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
/** * @file * * Source for the bbox::rt::net::AdapterInfo struct. * * THIS FILE IS AUTOMATICALLY GENERATED BY THE IDL COMPILER FROM * IDL SOURCE FILE "bbox_rt_net.bbidl" */ #include <bbox/rt/net/AdapterInfo.h> namespace bbox { namespace rt { namespace net { void AdapterInfo::ToBinary(bbox::enc::ToBinary &m) const { m.Write(system_name); m.Write(user_name); m.Write(description); m.Write(mac_address); m.Write(ip_addresses); } void AdapterInfo::FromBinary(bbox::enc::FromBinary &m) { m.Read(system_name); m.Read(user_name); m.Read(description); m.Read(mac_address); m.Read(ip_addresses); } void AdapterInfo::ToTextFormat(bbox::enc::ToTextFormat &m) const { m.StartStructure(); m.AddNamedValue("system_name", system_name); m.AddNamedValue("user_name", user_name); m.AddNamedValue("description", description); m.AddNamedValue("mac_address", mac_address); m.AddNamedValue("ip_addresses", ip_addresses); m.CompleteStructure(); } void AdapterInfo::FromTextFormat(bbox::enc::FromTextFormat &m) { m.StartStructure(); m.DecodeNamedValue("system_name", system_name); m.DecodeNamedValue("user_name", user_name); m.DecodeNamedValue("description", description); m.DecodeNamedValue("mac_address", mac_address); m.DecodeNamedValue("ip_addresses", ip_addresses); m.CompleteStructure(); } } // namespace net } // namespace rt } // namespace bbox
[ "github@kezenator.com" ]
github@kezenator.com
ed1437c07ab6e2a9518ca808db2aa226c9eb6bf0
b8884ab8fdfd94c48f91d6e74faefe7de32fc990
/Source/Billiard/Billiard.h
3c83ae6e77101294d66565ac947dae8087f4970c
[]
no_license
MihaiAlexandru1606/EGC---Billiard-3D
a77d406239078ea4bebc27da5d4ced8178e526b9
2b9ab5abbd3d1bfb4db7551718539fe62757254c
refs/heads/master
2020-04-22T21:00:01.552732
2019-02-15T12:47:09
2019-02-15T12:47:09
170,656,412
0
0
null
null
null
null
UTF-8
C++
false
false
3,279
h
#pragma once #include <iostream> #include <vector> #include <Component/SimpleScene.h> #include <Core/Engine.h> #include "camera/Camera.h" #include "transform3D/Transform3D.h" #include "table/BilliardTable.h" #include "ball/Ball.h" #include "ball/WhiteBall.h" #include "tac/Tac.h" #include "collision/Collision.h" class Billiard : public SimpleScene { public: Billiard(); ~Billiard(); void Init() override; private: /* stare 0 : in care mutam bila, se trece in stare 1 cand se citeste "space" stare 1 : in care puteam muta tac-ul stare 2 : in care se depleaza tac-ul stare 3 : pila este lovita stare 4 : desfasureare lovituri */ int mod; bool first = true; bool sw = false; bool mv = true; void printRules(); MyCamera::Camera *camera; glm::mat4 projectionMatrix; float clock; int isTacActive; // pentru retinerea texturilor std::unordered_map<std::string, Texture2D*> mapTextures; void initTextures(); void initShaders(); void initMesh(); void initBall(); void FrameStart() override; void Update(float deltaTimeSeconds) override; void FrameEnd() override; void RenderMeshGeneric(Mesh * mesh, Shader * shader, const glm::mat4 & modelMatrix, glm::vec3 color, int isTac, Texture2D* texture = NULL); void RenderMeshTexture(Mesh * mesh, Shader * shader, const glm::mat4 & modelMatrix, Texture2D* texture); void RenderMeshColor(Mesh * mesh, Shader * shader, const glm::mat4 & modelMatrix, glm::vec3 color); void RenderTac(Shader * shader, const glm::mat4 & modelMatrix); void OnInputUpdate(float deltaTime, int mods) override; void OnKeyPress(int key, int mods) override; void OnKeyRelease(int key, int mods) override; void OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) override; void OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) override; void OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) override; void OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) override; void OnWindowResize(int width, int height) override; BilliardTable billiardTable; void drawBilliardTable(); void drawBall(); void drawTac(float deltaTimeSeconds); // bilele : WhiteBall * whiteBall; std::vector<Ball> redBall; std::vector<Ball> yellowBall; Ball * blackBall; void moveWhiteBall(float deltaX, float deltaZ); void moveWhiteBall2(float deltaX, float deltaZ); // tacul Tac tac; float angleTac; void generateClock(float deltaTime); // functie initializare vitezei: void initSpeedWhiteBall(); void updateBall(float acceleration, float deltaTime); const float init_v = 4.0f; const float G = 0; int turn; /* 0 -> nimeni nu a ales 1 -> player 1 red, player 2 yellow 2 -> player 2 red, player 1 yellow */ int typeBall; bool fault = true; int nr_fault[2] = { 0, 0 }; int fault0 = 0; int fault1 = 0; void checkCollision(); void collisionManta(); void collisonBall(); void collisionHole(); void cameraSystem(); glm::vec3 getPosition(); void checkCondition(); void nextTurn(); void removeOutBall(); void lose(); void win(); int outRedTotal = 0; int outYellowTotal = 0; int outRedTurn = 0; int outYellowTurn = 0; glm::vec3 lightPosition; glm::vec3 lightDirection; unsigned int materialShininess; float materialKd; float materialKs; };
[ "mihai.alexandru1606@gmail.com" ]
mihai.alexandru1606@gmail.com
bb87b4a4df49f7904117982d7e464dd7d4ddc5d1
53c76fc4418de33a27231c6b83819021b7ee18d1
/Pods/gRPC-Core/src/core/lib/iomgr/tcp_server_posix.cc.back
6fed13c6c75a9878743c35f901b036211efdf59b
[ "Apache-2.0", "MIT" ]
permissive
nfloo/Quuio-MessageKit-Firebase
ab3d194fa0bef30df16a308d3b1730a23dd4f467
8bd97d2e65d43878e98673c36176306a6d44867e
refs/heads/master
2023-03-18T02:05:54.751703
2021-03-11T02:15:10
2021-03-11T02:15:10
344,838,928
1
1
MIT
2021-03-11T02:15:11
2021-03-05T14:39:38
null
UTF-8
C++
false
false
18,420
back
/* * * Copyright 2015 gRPC authors. * * 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. * */ /* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "src/core/lib/iomgr/port.h" #ifdef GRPC_POSIX_SOCKET #include "src/core/lib/iomgr/tcp_server.h" #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/sync.h> #include <grpc/support/time.h> #include <grpc/support/useful.h> #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/iomgr/socket_utils_posix.h" #include "src/core/lib/iomgr/tcp_posix.h" #include "src/core/lib/iomgr/tcp_server_utils_posix.h" #include "src/core/lib/iomgr/unix_sockets_posix.h" #include "src/core/lib/support/string.h" static gpr_once check_init = GPR_ONCE_INIT; static bool has_so_reuseport = false; static void init(void) { #ifndef GPR_MANYLINUX1 int s = socket(AF_INET, SOCK_STREAM, 0); if (s >= 0) { has_so_reuseport = GRPC_LOG_IF_ERROR("check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1)); close(s); } #endif } grpc_error* grpc_tcp_server_create(grpc_exec_ctx* exec_ctx, grpc_closure* shutdown_complete, const grpc_channel_args* args, grpc_tcp_server** server) { gpr_once_init(&check_init, init); grpc_tcp_server* s = (grpc_tcp_server*)gpr_zalloc(sizeof(grpc_tcp_server)); s->so_reuseport = has_so_reuseport; s->expand_wildcard_addrs = false; for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) { if (0 == strcmp(GRPC_ARG_ALLOW_REUSEPORT, args->args[i].key)) { if (args->args[i].type == GRPC_ARG_INTEGER) { s->so_reuseport = has_so_reuseport && (args->args[i].value.integer != 0); } else { gpr_free(s); return GRPC_ERROR_CREATE_FROM_STATIC_STRING(GRPC_ARG_ALLOW_REUSEPORT " must be an integer"); } } else if (0 == strcmp(GRPC_ARG_EXPAND_WILDCARD_ADDRS, args->args[i].key)) { if (args->args[i].type == GRPC_ARG_INTEGER) { s->expand_wildcard_addrs = (args->args[i].value.integer != 0); } else { gpr_free(s); return GRPC_ERROR_CREATE_FROM_STATIC_STRING( GRPC_ARG_EXPAND_WILDCARD_ADDRS " must be an integer"); } } } gpr_ref_init(&s->refs, 1); gpr_mu_init(&s->mu); s->active_ports = 0; s->destroyed_ports = 0; s->shutdown = false; s->shutdown_starting.head = nullptr; s->shutdown_starting.tail = nullptr; s->shutdown_complete = shutdown_complete; s->on_accept_cb = nullptr; s->on_accept_cb_arg = nullptr; s->head = nullptr; s->tail = nullptr; s->nports = 0; s->channel_args = grpc_channel_args_copy(args); gpr_atm_no_barrier_store(&s->next_pollset_to_assign, 0); *server = s; return GRPC_ERROR_NONE; } static void finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { gpr_mu_lock(&s->mu); GPR_ASSERT(s->shutdown); gpr_mu_unlock(&s->mu); if (s->shutdown_complete != nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, s->shutdown_complete, GRPC_ERROR_NONE); } gpr_mu_destroy(&s->mu); while (s->head) { grpc_tcp_listener* sp = s->head; s->head = sp->next; gpr_free(sp); } grpc_channel_args_destroy(exec_ctx, s->channel_args); gpr_free(s); } static void destroyed_port(grpc_exec_ctx* exec_ctx, void* server, grpc_error* error) { grpc_tcp_server* s = (grpc_tcp_server*)server; gpr_mu_lock(&s->mu); s->destroyed_ports++; if (s->destroyed_ports == s->nports) { gpr_mu_unlock(&s->mu); finish_shutdown(exec_ctx, s); } else { GPR_ASSERT(s->destroyed_ports < s->nports); gpr_mu_unlock(&s->mu); } } /* called when all listening endpoints have been shutdown, so no further events will be received on them - at this point it's safe to destroy things */ static void deactivated_all_ports(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { /* delete ALL the things */ gpr_mu_lock(&s->mu); GPR_ASSERT(s->shutdown); if (s->head) { grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_unlink_if_unix_domain_socket(&sp->addr); GRPC_CLOSURE_INIT(&sp->destroyed_closure, destroyed_port, s, grpc_schedule_on_exec_ctx); grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure, nullptr, false /* already_closed */, "tcp_listener_shutdown"); } gpr_mu_unlock(&s->mu); } else { gpr_mu_unlock(&s->mu); finish_shutdown(exec_ctx, s); } } static void tcp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { gpr_mu_lock(&s->mu); GPR_ASSERT(!s->shutdown); s->shutdown = true; /* shutdown all fd's */ if (s->active_ports) { grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_fd_shutdown( exec_ctx, sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server destroyed")); } gpr_mu_unlock(&s->mu); } else { gpr_mu_unlock(&s->mu); deactivated_all_ports(exec_ctx, s); } } /* event manager callback when reads are ready */ static void on_read(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* err) { grpc_tcp_listener* sp = (grpc_tcp_listener*)arg; grpc_pollset* read_notifier_pollset; if (err != GRPC_ERROR_NONE) { goto error; } read_notifier_pollset = sp->server->pollsets[(size_t)gpr_atm_no_barrier_fetch_add( &sp->server->next_pollset_to_assign, 1) % sp->server->pollset_count]; /* loop until accept4 returns EAGAIN, and then re-arm notification */ for (;;) { grpc_resolved_address addr; char* addr_str; char* name; addr.len = sizeof(struct sockaddr_storage); /* Note: If we ever decide to return this address to the user, remember to strip off the ::ffff:0.0.0.0/96 prefix first. */ int fd = grpc_accept4(sp->fd, &addr, 1, 1); if (fd < 0) { switch (errno) { case EINTR: continue; case EAGAIN: grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); return; default: gpr_mu_lock(&sp->server->mu); if (!sp->server->shutdown_listeners) { gpr_log(GPR_ERROR, "Failed accept4: %s", strerror(errno)); } else { /* if we have shutdown listeners, accept4 could fail, and we needn't notify users */ } gpr_mu_unlock(&sp->server->mu); goto error; } } grpc_set_socket_no_sigpipe_if_possible(fd); addr_str = grpc_sockaddr_to_uri(&addr); gpr_asprintf(&name, "tcp-server-connection:%s", addr_str); if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "SERVER_CONNECT: incoming connection: %s", addr_str); } grpc_fd* fdobj = grpc_fd_create(fd, name); grpc_pollset_add_fd(exec_ctx, read_notifier_pollset, fdobj); // Create acceptor. grpc_tcp_server_acceptor* acceptor = (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor)); acceptor->from_server = sp->server; acceptor->port_index = sp->port_index; acceptor->fd_index = sp->fd_index; sp->server->on_accept_cb( exec_ctx, sp->server->on_accept_cb_arg, grpc_tcp_create(exec_ctx, fdobj, sp->server->channel_args, addr_str), read_notifier_pollset, acceptor); gpr_free(name); gpr_free(addr_str); } GPR_UNREACHABLE_CODE(return ); error: gpr_mu_lock(&sp->server->mu); if (0 == --sp->server->active_ports && sp->server->shutdown) { gpr_mu_unlock(&sp->server->mu); deactivated_all_ports(exec_ctx, sp->server); } else { gpr_mu_unlock(&sp->server->mu); } } /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */ static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s, unsigned port_index, int requested_port, int* out_port) { grpc_resolved_address wild4; grpc_resolved_address wild6; unsigned fd_index = 0; grpc_dualstack_mode dsmode; grpc_tcp_listener* sp = nullptr; grpc_tcp_listener* sp2 = nullptr; grpc_error* v6_err = GRPC_ERROR_NONE; grpc_error* v4_err = GRPC_ERROR_NONE; *out_port = -1; if (grpc_tcp_server_have_ifaddrs() && s->expand_wildcard_addrs) { return grpc_tcp_server_add_all_local_addrs(s, port_index, requested_port, out_port); } grpc_sockaddr_make_wildcards(requested_port, &wild4, &wild6); /* Try listening on IPv6 first. */ if ((v6_err = grpc_tcp_server_add_addr(s, &wild6, port_index, fd_index, &dsmode, &sp)) == GRPC_ERROR_NONE) { ++fd_index; requested_port = *out_port = sp->port; if (dsmode == GRPC_DSMODE_DUALSTACK || dsmode == GRPC_DSMODE_IPV4) { return GRPC_ERROR_NONE; } } /* If we got a v6-only socket or nothing, try adding 0.0.0.0. */ grpc_sockaddr_set_port(&wild4, requested_port); if ((v4_err = grpc_tcp_server_add_addr(s, &wild4, port_index, fd_index, &dsmode, &sp2)) == GRPC_ERROR_NONE) { *out_port = sp2->port; if (sp != nullptr) { sp2->is_sibling = 1; sp->sibling = sp2; } } if (*out_port > 0) { if (v6_err != GRPC_ERROR_NONE) { gpr_log(GPR_INFO, "Failed to add :: listener, " "the environment may not support IPv6: %s", grpc_error_string(v6_err)); GRPC_ERROR_UNREF(v6_err); } if (v4_err != GRPC_ERROR_NONE) { gpr_log(GPR_INFO, "Failed to add 0.0.0.0 listener, " "the environment may not support IPv4: %s", grpc_error_string(v4_err)); GRPC_ERROR_UNREF(v4_err); } return GRPC_ERROR_NONE; } else { grpc_error* root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to add any wildcard listeners"); GPR_ASSERT(v6_err != GRPC_ERROR_NONE && v4_err != GRPC_ERROR_NONE); root_err = grpc_error_add_child(root_err, v6_err); root_err = grpc_error_add_child(root_err, v4_err); return root_err; } } static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) { grpc_tcp_listener* sp = nullptr; char* addr_str; char* name; grpc_error* err; for (grpc_tcp_listener* l = listener->next; l && l->is_sibling; l = l->next) { l->fd_index += count; } for (unsigned i = 0; i < count; i++) { int fd = -1; int port = -1; grpc_dualstack_mode dsmode; err = grpc_create_dualstack_socket(&listener->addr, SOCK_STREAM, 0, &dsmode, &fd); if (err != GRPC_ERROR_NONE) return err; err = grpc_tcp_server_prepare_socket(fd, &listener->addr, true, &port); if (err != GRPC_ERROR_NONE) return err; listener->server->nports++; grpc_sockaddr_to_string(&addr_str, &listener->addr, 1); gpr_asprintf(&name, "tcp-server-listener:%s/clone-%d", addr_str, i); sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener)); sp->next = listener->next; listener->next = sp; /* sp (the new listener) is a sibling of 'listener' (the original listener). */ sp->is_sibling = 1; sp->sibling = listener->sibling; listener->sibling = sp; sp->server = listener->server; sp->fd = fd; sp->emfd = grpc_fd_create(fd, name); memcpy(&sp->addr, &listener->addr, sizeof(grpc_resolved_address)); sp->port = port; sp->port_index = listener->port_index; sp->fd_index = listener->fd_index + count - i; GPR_ASSERT(sp->emfd); while (listener->server->tail->next != nullptr) { listener->server->tail = listener->server->tail->next; } gpr_free(addr_str); gpr_free(name); } return GRPC_ERROR_NONE; } grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s, const grpc_resolved_address* addr, int* out_port) { grpc_tcp_listener* sp; grpc_resolved_address sockname_temp; grpc_resolved_address addr6_v4mapped; int requested_port = grpc_sockaddr_get_port(addr); unsigned port_index = 0; grpc_dualstack_mode dsmode; grpc_error* err; *out_port = -1; if (s->tail != nullptr) { port_index = s->tail->port_index + 1; } grpc_unlink_if_unix_domain_socket(addr); /* Check if this is a wildcard port, and if so, try to keep the port the same as some previously created listener. */ if (requested_port == 0) { for (sp = s->head; sp; sp = sp->next) { sockname_temp.len = sizeof(struct sockaddr_storage); if (0 == getsockname(sp->fd, (struct sockaddr*)&sockname_temp.addr, (socklen_t*)&sockname_temp.len)) { int used_port = grpc_sockaddr_get_port(&sockname_temp); if (used_port > 0) { memcpy(&sockname_temp, addr, sizeof(grpc_resolved_address)); grpc_sockaddr_set_port(&sockname_temp, used_port); requested_port = used_port; addr = &sockname_temp; break; } } } } if (grpc_sockaddr_is_wildcard(addr, &requested_port)) { return add_wildcard_addrs_to_server(s, port_index, requested_port, out_port); } if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) { addr = &addr6_v4mapped; } if ((err = grpc_tcp_server_add_addr(s, addr, port_index, 0, &dsmode, &sp)) == GRPC_ERROR_NONE) { *out_port = sp->port; } return err; } /* Return listener at port_index or NULL. Should only be called with s->mu locked. */ static grpc_tcp_listener* get_port_index(grpc_tcp_server* s, unsigned port_index) { unsigned num_ports = 0; grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { if (!sp->is_sibling) { if (++num_ports > port_index) { return sp; } } } return nullptr; } unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index) { unsigned num_fds = 0; gpr_mu_lock(&s->mu); grpc_tcp_listener* sp = get_port_index(s, port_index); for (; sp; sp = sp->sibling) { ++num_fds; } gpr_mu_unlock(&s->mu); return num_fds; } int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index, unsigned fd_index) { gpr_mu_lock(&s->mu); grpc_tcp_listener* sp = get_port_index(s, port_index); for (; sp; sp = sp->sibling, --fd_index) { if (fd_index == 0) { gpr_mu_unlock(&s->mu); return sp->fd; } } gpr_mu_unlock(&s->mu); return -1; } void grpc_tcp_server_start(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s, grpc_pollset** pollsets, size_t pollset_count, grpc_tcp_server_cb on_accept_cb, void* on_accept_cb_arg) { size_t i; grpc_tcp_listener* sp; GPR_ASSERT(on_accept_cb); gpr_mu_lock(&s->mu); GPR_ASSERT(!s->on_accept_cb); GPR_ASSERT(s->active_ports == 0); s->on_accept_cb = on_accept_cb; s->on_accept_cb_arg = on_accept_cb_arg; s->pollsets = pollsets; s->pollset_count = pollset_count; sp = s->head; while (sp != nullptr) { if (s->so_reuseport && !grpc_is_unix_socket(&sp->addr) && pollset_count > 1) { GPR_ASSERT(GRPC_LOG_IF_ERROR( "clone_port", clone_port(sp, (unsigned)(pollset_count - 1)))); for (i = 0; i < pollset_count; i++) { grpc_pollset_add_fd(exec_ctx, pollsets[i], sp->emfd); GRPC_CLOSURE_INIT(&sp->read_closure, on_read, sp, grpc_schedule_on_exec_ctx); grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); s->active_ports++; sp = sp->next; } } else { for (i = 0; i < pollset_count; i++) { grpc_pollset_add_fd(exec_ctx, pollsets[i], sp->emfd); } GRPC_CLOSURE_INIT(&sp->read_closure, on_read, sp, grpc_schedule_on_exec_ctx); grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); s->active_ports++; sp = sp->next; } } gpr_mu_unlock(&s->mu); } grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) { gpr_ref_non_zero(&s->refs); return s; } void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s, grpc_closure* shutdown_starting) { gpr_mu_lock(&s->mu); grpc_closure_list_append(&s->shutdown_starting, shutdown_starting, GRPC_ERROR_NONE); gpr_mu_unlock(&s->mu); } void grpc_tcp_server_unref(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { if (gpr_unref(&s->refs)) { grpc_tcp_server_shutdown_listeners(exec_ctx, s); gpr_mu_lock(&s->mu); GRPC_CLOSURE_LIST_SCHED(exec_ctx, &s->shutdown_starting); gpr_mu_unlock(&s->mu); tcp_server_destroy(exec_ctx, s); } } void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { gpr_mu_lock(&s->mu); s->shutdown_listeners = true; /* shutdown all fd's */ if (s->active_ports) { grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_fd_shutdown(exec_ctx, sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server shutdown")); } } gpr_mu_unlock(&s->mu); } #endif
[ "sdehmi@gmail.com" ]
sdehmi@gmail.com
c71720544fe65ca636cadba9366975d8b1c89e51
e2802cb1bbeaff5b28b803397c42769b54f1177e
/nower_coder/Multi_University_Training_Contest/2018/nine/E.cpp
e62a66716d6c51689cbbc54f336f6296002ea701
[]
no_license
LanceDai/code
db034a739f4f8c08a8677e5df5700b3de44865ab
183ada9c38521de73021c5675855119f6e6e1951
refs/heads/master
2020-03-23T18:04:48.586019
2018-08-16T09:57:39
2018-08-16T09:57:39
141,888,427
0
0
null
null
null
null
UTF-8
C++
false
false
1,764
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i, a, n) for (int i=a;i<n;i++) #define per(i, a, n) for (int i=n-1;i>=a;i--) #define cls(x) memset((x),0,sizeof((x))) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef vector<int> VI; typedef long long LL; typedef pair<int, int> PII; LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } const int MOD = 1000000007; const int MAXN = 1005; LL fac[MAXN], inv[MAXN]; inline LL quick_mod(LL x, LL n, LL MOD) { LL ret = 1; while (n) { if (n & 1)ret = ret * x % MOD; x = x * x % MOD; n >>= 1; } return ret; } //预处理阶乘和阶乘逆元和块 inline void init(int n) { fac[0] = fac[1] = inv[0] = inv[1] = 1; //阶乘 for (int i = 2; i <= n; i++) fac[i] = fac[i - 1] * i % MOD; inv[n] = quick_mod(fac[n], MOD - 2, MOD); //阶乘逆元 //逆元的逆元为本身 //(n-1)!的逆元等于(n!/n)的逆元,等于n!的逆元×n的逆元的逆元,即n!的逆元×n for (int i = n; i > 1; i--) inv[i - 1] = inv[i] * i % MOD; } //求组合数 inline LL C(LL n, LL m) { return fac[n] * inv[m] % MOD * inv[n - m] % MOD; } LL f[MAXN][MAXN]; int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(nullptr); cls(f); int n, m; cin >> n >> m; vector<int> p(static_cast<unsigned long>(n)); rep(i, 1, n + 1) { cin >> p[i]; rep(j, 1, n + 1){ rep(k, 0, j + 1){ f[j][] = C(j, k) * f[j - 1] * p[i]; f[j][] } } } return 0; }
[ "603842325@qq.com" ]
603842325@qq.com
5f01767c2c41f1ac9fce779862a6bf4336adc30a
1b9bef9d2c1f7896c254a3d7d271ae9a968695a9
/ege/event/tests/main.cpp
8da5ada0e2051d649991fe4d5822a2612f8e31fa
[ "MIT" ]
permissive
sysfce2/SFML_Hexagon-Engine_ege
1ca194e19b7f6377846bc091c95756c306441479
a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020
refs/heads/master
2023-07-17T04:08:36.077672
2021-08-28T16:24:22
2021-08-28T16:24:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,801
cpp
/* * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * ,---- ,---- ,---- * | | | * |---- | --, |---- * | | | | * '---- '---' '---- * * Framework Library for Hexagon * * Copyright (c) Sppmacd 2020 - 2021 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * */ #include <testsuite/Tests.h> #include <ege/core/MainLoop.h> #include <ege/debug/Logger.h> #include <ege/event/SystemEvent.h> #include <ege/event/DefaultSystemEventHandler.h> #include <ege/event/SystemWindow.h> class MyGameLoop : public EGE::MainLoop { EGE::SharedPtr<EGE::SFMLSystemWindow> m_window; public: virtual EGE::EventResult onLoad() override; virtual void onTick() override { //DEBUG_PRINT("onTick"); m_window->callEvents(*this); if(!m_window->isOpen()) exit(); m_window->clear(); m_window->display(); } }; class MySystemEventHandler : public EGE::DefaultSystemEventHandler { public: MySystemEventHandler(EGE::SFMLSystemWindow& window) : EGE::DefaultSystemEventHandler(window) {} virtual void onMouseEnter() { ege_log.info() << "onMouseEnter"; } virtual void onMouseLeave() { ege_log.info() << "onMouseLeave"; } }; EGE::EventResult MyGameLoop::onLoad() { m_window = make<EGE::SFMLSystemWindow>(); events<EGE::SystemEvent>().addHandler<MySystemEventHandler>(*m_window); m_window->create(sf::VideoMode(256, 256), "EGE Test"); return EGE::EventResult::Success; } MyGameLoop loop; TESTCASE(createWindow) { return loop.run(); } RUN_TESTS(syswindow)
[ "sppmacd@pm.me" ]
sppmacd@pm.me
6a860a88ed9b2b4a49cea146b2ae65c4498481b4
8e2255dc427111b93cd97683ca1b1b99366fe928
/Stacks and Queues/Practice/Balanced Parantheses.cpp
fc560f0558c0805f0e76646c5c7a31f03e2bad8f
[]
no_license
pareenj/Coding
c9141b09e7c9bab69869f517407586cbf4dc12ed
f56dddefa4d681138df628a79fcab3940bf2f055
refs/heads/master
2020-04-06T23:29:18.497866
2018-11-16T13:46:49
2018-11-16T13:46:49
157,871,255
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
/* C++ Program to check for balanced parentheses in an expression using stack. Given an expression as string comprising of opening and closing characters of parentheses - (), curly braces - {} and square brackets - [], we need to check whether symbols are balanced or not. */ #include<iostream> #include<stack> #include<string> using namespace std; // Function to check whether two characters are opening // and closing of same type. bool ArePair(char opening, char closing) { if(opening == '(' && closing == ')') return true; else if(opening == '{' && closing == '}') return true; else if(opening == '[' && closing == ']') return true; return false; } bool AreParanthesesBalanced(string exp) { stack<char> S; int n = exp.length(); for(int i = 0; i < n; i++) { if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[') S.push(exp[i]); else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']') { if(S.empty() || !ArePair(S.top(), exp[i])) return false; else S.pop(); } } return S.empty() ? true:false; } int main() { /*Code to test the function AreParanthesesBalanced*/ string expression; cout<<"Enter an expression: "; // input expression from STDIN/Console cin>>expression; if(AreParanthesesBalanced(expression)) cout<<"Balanced\n"; else cout<<"Not Balanced\n"; }
[ "noreply@github.com" ]
noreply@github.com
fa141ae373f18b9cb19707106607032eb550726a
46cbd8ca773c1481bb147b54765985c636627d29
/Ubuntu/practice/AdminPersona-2.h
9d51e1c3523d2c2e9b591ed93641c98ed45cbbb9
[]
no_license
ator89/Cpp
e7ddb1ccd59ffa5083fced14c4d54403160f2ca7
9d6bd29e7d97022703548cbef78719536bc149fe
refs/heads/master
2021-06-01T13:14:27.508828
2020-10-21T05:15:52
2020-10-21T05:15:52
150,691,862
0
0
null
null
null
null
UTF-8
C++
false
false
515
h
#ifndef ADMINPERSONA_H #define ADMINPERSONA_H #include "Usuario.h" #include <vector> using std::vector; #include <string> using std::string; class AdminPersona{ private: vector<Usuario*> listaUsuarios; public: //AdminPersona(); ~AdminPersona(); bool login(string,string); //int posUsuario(std::string); void addUsuario(Usuario*); //void setListaUsuarios(std::vector<Usuario*>); std::vector<Usuario*> getListaUsuarios(); }; #endif
[ "ator89@outlook.com" ]
ator89@outlook.com
399a66f3a514d939973ac944f498ae8c84b65075
c759cda63788838f1bde32d82f8f2ee2aa2cae95
/adamantine/Stats.cpp
6bf784504e0940e363719375cc1e40ce11810016
[]
no_license
mbellman/adamantine
fce6c5aeb34ad6f059abfe12b7182bb1f6cc0c70
0f224a05f249785e2a2f58634da7c0fff2daba9f
refs/heads/master
2020-11-23T18:29:17.184489
2020-08-09T00:55:55
2020-08-09T00:55:55
227,764,141
0
0
null
null
null
null
UTF-8
C++
false
false
311
cpp
#include "Stats.h" #include "SDL.h" int Stats::getFPS() { int delta = frame.end - frame.start; return delta == 0 ? 1000 : (int)(1000.0f / (frame.end - frame.start)); } void Stats::trackFrameStart() { frame.start = SDL_GetTicks(); } void Stats::trackFrameEnd() { frame.end = SDL_GetTicks(); }
[ "mbellman@nwe.com" ]
mbellman@nwe.com
ba92ec4716613a379e5d9ff49231464b6d3cd986
2cd9911b83bf4a2cfe6ff8df6083f3d26af8a7ae
/Headers/Placer/placer.h
f7909ba9be8e1a1d8bbb94486e504caa890217ae
[]
no_license
abhinandmenon/MFSimStaticAStar
784361b18f3dd9c245996bdd12443a6f77b5de59
775adc5c6620fb9d4dc0a3e947be236e1e4256ac
refs/heads/master
2021-01-20T08:57:26.439644
2015-01-23T23:36:22
2015-01-23T23:36:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,747
h
/*------------------------------------------------------------------------------* * (c)2014, All Rights Reserved. * * ___ ___ ___ * * /__/\ / /\ / /\ * * \ \:\ / /:/ / /::\ * * \ \:\ / /:/ / /:/\:\ * * ___ \ \:\ / /:/ ___ / /:/~/:/ * * /__/\ \__\:\ /__/:/ / /\ /__/:/ /:/___ UCR DMFB Synthesis Framework * * \ \:\ / /:/ \ \:\ / /:/ \ \:\/:::::/ www.microfluidics.cs.ucr.edu * * \ \:\ /:/ \ \:\ /:/ \ \::/~~~~ * * \ \:\/:/ \ \:\/:/ \ \:\ * * \ \::/ \ \::/ \ \:\ * * \__\/ \__\/ \__\/ * *-----------------------------------------------------------------------------*/ /*------------------------------Algorithm Details-------------------------------* * Type: Placer * * Name: General Base Placer * * * * Not inferred or detailed in any publications * * * * Details: This is a base placer class which contains some basic members * * and functions useful to all placers. It must be inherited from when * * creating a new placer in order to keep the structure of the simulator * * and to keep the code clean and modular. * *-----------------------------------------------------------------------------*/ #ifndef PLACER_H_ #define PLACER_H_ #include "../Models/dmfb_arch.h" #include "../Testing/claim.h" class DAG; class Placer { public: // Constructors Placer(); virtual ~Placer(); // Methods virtual void place(DmfbArch *arch, DAG *dag, vector<ReconfigModule *> *rModules); // Getters/Setters int getMaxStoragePerModule() { return maxStoragePerModule; } // Not sure what class this info should really belong to, will hard-code for now void setMaxStoragePerModule(int drops) { maxStoragePerModule = drops; } int getHCellsBetweenModIR() { return hCellsBetweenModIR; } void setHCellsBetweenModIR(int cells) { hCellsBetweenModIR = cells; } int getVCellsBetweenModIR() { return vCellsBetweenModIR; } void setVCellsBetweenModIR(int cells) { vCellsBetweenModIR = cells; } SchedulerType getPastSchedType() { return pastSchedType; } PlacerType getType() { return type; } void setPastSchedType(SchedulerType st) { pastSchedType = st; } void setType(PlacerType pt) { type = pt; } bool hasExecutableSynthMethod() { return hasExecutableSyntesisMethod; } void setHasExecutableSynthMethod(bool hasMethod) { hasExecutableSyntesisMethod = hasMethod; } protected: // Members int maxStoragePerModule; // Number of droplets a single module is able to store int hCellsBetweenModIR; // # of cells, on x-axis, between module interference regions; should be non-negative int vCellsBetweenModIR; // # of cells, on y-axis, between module interference regions; should be non-negative vector<IoResource*> *dispRes; // Dispense reservoir resources vector<IoResource*> *outRes; // Output reservoir resources vector<FixedModule *> availRes[RES_TYPE_MAX+1]; // Tells the module resource availability (not dispense/output info) SchedulerType pastSchedType; PlacerType type; bool hasExecutableSyntesisMethod; // Tells if method contains code to execute, or if it is just a shell // Methods void resetIoResources(DmfbArch *arch); void getAvailResources(DmfbArch *arch); void bindInputsLE(list<AssayNode *> *inputNodes); void bindOutputsLE(list<AssayNode *> *outputNodes); }; #endif /* PLACER_H_ */
[ "mohiuddin.a.qader@gmail.com" ]
mohiuddin.a.qader@gmail.com
da630127dfdfbc42cebf6a44887cc47a6e02fee2
76a6de92f225c0ed8c552d280647b8289d556f8b
/Twitter_by_Andre/datetime.cpp
bfb85a575df7e55ac03abe734f4809cf20713dcd
[]
no_license
apirjani/Exercises
21e48b3c003ea7e5e781659a88ed4862c8bb1fd4
75ce7821a55daf5102db69fd5826ca9f1be6a9d2
refs/heads/main
2023-09-04T19:29:23.836165
2021-11-10T03:27:59
2021-11-10T03:27:59
426,454,295
0
0
null
null
null
null
UTF-8
C++
false
false
5,315
cpp
#include <iostream> #include <ctime> #include <string> #include <sstream> #include "datetime.h" #include <iomanip> using namespace std; DateTime::DateTime() { time_t rawtime; //struct that will store the current local time variabls (hour, min, sec, etc.) struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); //after setting localtime variables into struct, extract information from struct //data members of datetime object hour = timeinfo->tm_hour; min = timeinfo->tm_min; sec = timeinfo->tm_sec; year = 1900 + timeinfo->tm_year; month = 1 + timeinfo->tm_mon; day = timeinfo->tm_mday; } DateTime::DateTime(int hh, int mm, int ss, int year, int month, int day) { hour = hh; min = mm; sec = ss; this->year = year; this->month = month; this->day = day; } //checks whether this object came before other object //comparing from year all the way down to second bool DateTime::operator<(const DateTime& other) const { if (year < other.year) { return true; } else if (year > other.year) { return false; } else { if (month < other.month) { return true; } else if (month > other.month) { return false; } else { if (day < other.day) { return true; } else if (day > other.day) { return false; } else { if (hour < other.hour) { return true; } else if (hour > other.hour) { return false; } else { if (min < other.min) { return true; } else if (min > other.min) { return false; } else { if (sec < other.sec) { return true; } else { return false; } } } } } } } ostream& operator<<(ostream& os, const DateTime& other) { os << other.year << '-' << setfill('0') << setw(2) << other.month << '-' << setfill('0') << setw(2) << other.day << ' ' << setfill('0') << setw(2) << other.hour << ':' << setfill('0') << setw(2) << other.min << ':' << setfill('0') << setw(2) << other.sec; return os; } //expecting YYYY-MM-DD HH:MM:SS format, extract necessary information and //update data members istream& operator>>(istream& is, DateTime& dt) { //create datetime object with current time DateTime temp; string date_extract; stringstream ss_temp; //use getline to store year in date_extract getline(is, date_extract, '-'); //if extraction fails, update dt to current time and return is if (is.fail()) { dt = temp; return is; } //create stringstream with year ss_temp.str(date_extract); //pull in year as int from stringstream ss_temp >> dt.year; //if extraction fails, update dt to current time and return is if (ss_temp.fail()) { dt = temp; return is; } //make sure ss_temp is empty for reuse ss_temp.clear(); ss_temp.str(""); //same process but for month getline(is, date_extract, '-'); if (is.fail()) { dt = temp; return is; } ss_temp.str(date_extract); ss_temp >> dt.month; if (ss_temp.fail()) { dt = temp; return is; } ss_temp.clear(); ss_temp.str(""); //same process but for day (don't need to use getline since day //is at end of string and is stops at empty space is >> date_extract; if (is.fail()) { dt = temp; return is; } ss_temp.str(date_extract); ss_temp >> dt.day; if (ss_temp.fail()) { dt = temp; return is; } ss_temp.clear(); ss_temp.str(""); string time_extract; //same process but for hour getline(is, time_extract, ':'); if (is.fail()) { dt = temp; return is; } ss_temp.str(time_extract); ss_temp >> dt.hour; if (ss_temp.fail()) { dt = temp; return is; } ss_temp.clear(); ss_temp.str(""); //same process but for min getline(is, time_extract, ':'); if (is.fail()) { dt = temp; return is; } ss_temp.str(time_extract); ss_temp >> dt.min; if (ss_temp.fail()) { dt = temp; return is; } ss_temp.clear(); ss_temp.str(""); //same process but for sec is >> time_extract; if (is.fail()) { dt = temp; return is; } ss_temp.str(time_extract); ss_temp >> dt.sec; if (ss_temp.fail()) { dt = temp; return is; } ss_temp.clear(); ss_temp.str(""); return is; }
[ "noreply@github.com" ]
noreply@github.com
63865b9fe833997eac4ebebaf6ce961cbc92fb0c
9f0ea5ca7434763c9ac871c82915f727f49dd3ef
/Atelier reparatii.cpp
4174eb8cb2f343177b2f34c53970e5bbebf0531b
[]
no_license
FlorinP2602/Probleme-ECCPR-
031a09deb63507b2dd7fad71b0b58164a067366d
fce94a6e67cc427439dc7a801e61f1ac607728b0
refs/heads/master
2023-03-16T21:37:17.110812
2020-05-04T19:21:26
2020-05-04T19:21:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ vector<int>vec; int n,c; for(int i=0;i<7;i++){ cin>>c; vec.push_back(c); } cin>>n; for(int i=0;i<n;i++){ for(int j=0;j<7;j++){ cin>>c; vec[j]+=c; } } sort(vec.begin(),vec.end()); if(vec[0]<n){ cout<<vec[0]; }else{ cout<<n; } }
[ "noreply@github.com" ]
noreply@github.com
0ed0e9ef34932ec9112d7ebc43d6713532deb621
a874968924177a8a9c9089002d564045e0d37088
/src/rpcdump.cpp
59394e90dc2aa81d6f411e8ce0557b31c8b50049
[ "MIT" ]
permissive
pawelwludyka1981/BCM-Lab
2e9ee99cdfbce1f4a99b72f4ae3c81859952f014
77cd39b4a8ae5d84d98a5baabdcc83183563cc03
refs/heads/master
2020-06-22T20:03:38.900207
2019-07-23T08:22:36
2019-07-23T08:22:36
198,385,072
1
1
null
2019-07-23T08:18:58
2019-07-23T08:18:57
null
UTF-8
C++
false
false
11,298
cpp
// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include <fstream> #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/variant/get.hpp> #include <boost/algorithm/string.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); namespace bt = boost::posix_time; // Extended DecodeDumpTime implementation, see this page for details: // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")), std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; const size_t formats_n = sizeof(formats)/sizeof(formats[0]); std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); bt::time_duration diff = pt - timet_start; return diff.ticks()/bt::time_duration::rep_type::ticks_per_second; } int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; for(size_t i=0; i<formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if(pt != bt::ptime()) break; } return pt_to_time_t(pt); } std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } class CTxDump { public: CBlockIndex *pindex; int64_t nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <BitcoinMetalprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet <filename>\n" "Imports keys from a wallet dump file (see dumpwallet)."); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = pindexBest->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; bool fCompressed; CKey key; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID keyid = key.GetPubKey().GetID(); if (pwalletMain->HaveKey(keyid)) { printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str()); if (!pwalletMain->AddKey(key)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBookName(keyid, strLabel); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = pindexBest; while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->ReacceptWalletTransactions(); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <BitcoinMetaladdress>\n" "Reveals the private key corresponding to <BitcoinMetaladdress>."); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BitcoinMetal address"); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet <filename>\n" "Dumps all wallet keys in a human-readable format."); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by BitcoinMetal %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str()); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str()); file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str()); file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str()); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); bool IsCompressed; CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str()); } else if (setKeyPool.count(keyid)) { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } else { CSecret secret = key.GetSecret(IsCompressed); file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str()); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; }
[ "user@gmail.com" ]
user@gmail.com
f8c8035cfecd830b7704bf712becf6f2ae5f669a
407ed5dc2450b643815f1eb8576d598149d83f5c
/CodeRed/DirectX12/DirectX12PipelineState/DirectX12ShaderState.cpp
47a07487d15ed67658b2e5498a151fb3f3da035c
[ "MIT" ]
permissive
LinkClinton/Code-Red
dee097aed61e82d025ae3e8b8d54b5b746c05eaa
491621144aba559f068c7f91d71e3d0d7c87761e
refs/heads/master
2020-07-24T02:19:55.756759
2020-05-03T01:45:03
2020-05-03T01:45:03
207,771,096
42
6
null
null
null
null
UTF-8
C++
false
false
433
cpp
#include "DirectX12ShaderState.hpp" #ifdef __ENABLE__DIRECTX12__ using namespace CodeRed::DirectX12; CodeRed::DirectX12ShaderState::DirectX12ShaderState( const std::shared_ptr<GpuLogicalDevice>& device, const ShaderType type, const std::vector<Byte>& code, const std::string& name) : GpuShaderState(device, type, code, name) { mShaderCode.BytecodeLength = mCode.size(); mShaderCode.pShaderBytecode = mCode.data(); } #endif
[ "LinkClinton@outlook.com" ]
LinkClinton@outlook.com
1fab0a09abf8eac34a46b0f31f1048466e6f78a9
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/InnerDetector/InDetSimUtils/TRT_PAI_Process/TRT_PAI_Process/ITRT_PAITool.h
ca8f9402904cb37ec5365062bbb5f64ef1c2a748
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
766
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef ITRT_PAITOOL_H #define ITRT_PAITOOL_H 1 // Include files #include "GaudiKernel/IAlgTool.h" /** @class ITRT_PAITool ITRT_PAITool.h * Give and AlgTool interface to the PAI model * * @author Davide Costanzo */ class ITRT_PAITool : virtual public IAlgTool { public: // Declaration of the interface ID (interface id, major version, minor version) DeclareInterfaceID(ITRT_PAITool, 1 , 0); /// GetMeanFreePath virtual double GetMeanFreePath(double scaledKineticEnergy, double squaredCharge) const =0; /// GetEnergyTransfer virtual double GetEnergyTransfer(double scaledKineticEnergy) const =0; }; #endif // ITRT_PAITOOL_H
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
108396311b42c524cd2f2c3a0a96494fb6cf04ef
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/web_applications/web_app_icon_manager.h
8949150900cd9489fa91507862679177b23682ce
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
11,032
h
// Copyright 2018 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_BROWSER_WEB_APPLICATIONS_WEB_APP_ICON_MANAGER_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_ICON_MANAGER_H_ #include <stddef.h> #include <stdint.h> #include <map> #include <memory> #include <string> #include <vector> #include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "chrome/browser/web_applications/web_app_id.h" #include "chrome/browser/web_applications/web_app_install_info.h" #include "chrome/browser/web_applications/web_app_install_manager_observer.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image_skia.h" #include "web_app_install_info.h" class Profile; namespace base { class SequencedTaskRunner; class Time; } // namespace base namespace web_app { class FileUtilsWrapper; class WebAppInstallManager; class WebAppRegistrar; using HomeTabIconBitmaps = std::vector<SkBitmap>; using SquareSizeDip = int; // Exclusively used from the UI thread. class WebAppIconManager : public WebAppInstallManagerObserver { public: using FaviconReadCallback = base::RepeatingCallback<void(const AppId& app_id)>; using ReadImageSkiaCallback = base::OnceCallback<void(gfx::ImageSkia image_skia)>; WebAppIconManager(Profile* profile, scoped_refptr<FileUtilsWrapper> utils); WebAppIconManager(const WebAppIconManager&) = delete; WebAppIconManager& operator=(const WebAppIconManager&) = delete; ~WebAppIconManager() override; void SetSubsystems(WebAppRegistrar* registrar, WebAppInstallManager* install_manager); using WriteDataCallback = base::OnceCallback<void(bool success)>; // Writes all data (icons) for an app. void WriteData(AppId app_id, IconBitmaps icon_bitmaps, ShortcutsMenuIconBitmaps shortcuts_menu_icons, IconsMap other_icons_map, WriteDataCallback callback); void DeleteData(AppId app_id, WriteDataCallback callback); void Start(); void Shutdown(); // Returns false if any icon in |icon_sizes_in_px| is missing from downloaded // icons for a given app and |purpose|. bool HasIcons(const AppId& app_id, IconPurpose purpose, const SortedSizesPx& icon_sizes) const; struct IconSizeAndPurpose { SquareSizePx size_px = 0; IconPurpose purpose = IconPurpose::ANY; }; // For each of |purposes|, in the given order, looks for an icon with size at // least |min_icon_size|. Returns information on the first icon found. absl::optional<IconSizeAndPurpose> FindIconMatchBigger( const AppId& app_id, const std::vector<IconPurpose>& purposes, SquareSizePx min_size) const; // Returns whether there is a downloaded icon of at least |min_size| for any // of the given |purposes|. bool HasSmallestIcon(const AppId& app_id, const std::vector<IconPurpose>& purposes, SquareSizePx min_size) const; using ReadIconsCallback = base::OnceCallback<void(std::map<SquareSizePx, SkBitmap> icon_bitmaps)>; // Reads specified icon bitmaps for an app and |purpose|. Returns empty map in // |callback| if IO error. void ReadIcons(const AppId& app_id, IconPurpose purpose, const SortedSizesPx& icon_sizes, ReadIconsCallback callback); // Mimics WebAppShortcutsMenuItemInfo but stores timestamps instead of icons // for os integration. using ShortcutMenuIconTimes = base::flat_map<IconPurpose, base::flat_map<SquareSizePx, base::Time>>; using ShortcutIconDataVector = std::vector<ShortcutMenuIconTimes>; using ShortcutIconDataCallback = base::OnceCallback<void(ShortcutIconDataVector)>; void ReadAllShortcutMenuIconsWithTimestamp(const AppId& app_id, ShortcutIconDataCallback callback); using ReadIconsUpdateTimeCallback = base::OnceCallback<void( base::flat_map<SquareSizePx, base::Time> time_map)>; // Reads all the last updated time for all icons in the app. Returns empty map // in |callback| if IO error. void ReadIconsLastUpdateTime(const AppId& app_id, ReadIconsUpdateTimeCallback callback); // TODO (crbug.com/1102701): Callback with const ref instead of value. using ReadIconBitmapsCallback = base::OnceCallback<void(IconBitmaps icon_bitmaps)>; // Reads all icon bitmaps for an app. Returns empty |icon_bitmaps| in // |callback| if IO error. void ReadAllIcons(const AppId& app_id, ReadIconBitmapsCallback callback); using ReadShortcutsMenuIconsCallback = base::OnceCallback<void( ShortcutsMenuIconBitmaps shortcuts_menu_icon_bitmaps)>; // Reads bitmaps for all shortcuts menu icons for an app. Returns a vector of // map<SquareSizePx, SkBitmap>. The index of a map in the vector is the same // as that of its corresponding shortcut in the manifest's shortcuts vector. // Returns empty vector in |callback| if we hit any error. void ReadAllShortcutsMenuIcons(const AppId& app_id, ReadShortcutsMenuIconsCallback callback); using ReadHomeTabIconsCallback = base::OnceCallback<void(SkBitmap home_tab_icon_bitmap)>; // Reads bitmap for the home tab icon. Returns a SkBitmap // in |callback| if the icon exists. Otherwise, if it doesn't // exist, the SkBitmap is empty. void ReadBestHomeTabIcon( const AppId& app_id, const std::vector<blink::Manifest::ImageResource>& icons, const SquareSizePx min_home_tab_icon_size_px, ReadHomeTabIconsCallback callback); using ReadIconWithPurposeCallback = base::OnceCallback<void(IconPurpose, SkBitmap)>; // For each of |purposes|, in the given order, looks for an icon with size at // least |min_icon_size|. Returns the first icon found, as a bitmap. Returns // an empty SkBitmap in |callback| if IO error. void ReadSmallestIcon(const AppId& app_id, const std::vector<IconPurpose>& purposes, SquareSizePx min_size_in_px, ReadIconWithPurposeCallback callback); using ReadCompressedIconWithPurposeCallback = base::OnceCallback<void(IconPurpose, std::vector<uint8_t> data)>; // For each of |purposes|, in the given order, looks for an icon with size at // least |min_icon_size|. Returns the first icon found, compressed as PNG. // Returns empty |data| in |callback| if IO error. void ReadSmallestCompressedIcon( const AppId& app_id, const std::vector<IconPurpose>& purposes, SquareSizePx min_size_in_px, ReadCompressedIconWithPurposeCallback callback); // Returns a square icon of gfx::kFaviconSize px, or an empty bitmap if not // found. SkBitmap GetFavicon(const AppId& app_id) const; gfx::ImageSkia GetFaviconImageSkia(const AppId& app_id) const; gfx::ImageSkia GetMonochromeFavicon(const AppId& app_id) const; // WebAppInstallManagerObserver: void OnWebAppInstalled(const AppId& app_id) override; void OnWebAppInstallManagerDestroyed() override; // Calls back with an icon of the |desired_icon_size| and |purpose|, resizing // an icon of a different size if necessary. If no icons were available, calls // back with an empty map. Prefers resizing a large icon smaller over resizing // a small icon larger. void ReadIconAndResize(const AppId& app_id, IconPurpose purpose, SquareSizePx desired_icon_size, ReadIconsCallback callback); // Reads multiple densities of the icon for each supported UI scale factor. // See ui/base/layout.h. Returns null image in |callback| if no icons found // for all supported UI scale factors (matches only bigger icons, no // upscaling). void ReadUiScaleFactorsIcons(const AppId& app_id, IconPurpose purpose, SquareSizeDip size_in_dip, ReadImageSkiaCallback callback); struct IconFilesCheck { size_t empty = 0; size_t missing = 0; }; void CheckForEmptyOrMissingIconFiles( const AppId& app_id, base::OnceCallback<void(IconFilesCheck)> callback) const; void SetFaviconReadCallbackForTesting(FaviconReadCallback callback); void SetFaviconMonochromeReadCallbackForTesting(FaviconReadCallback callback); base::FilePath GetIconFilePathForTesting(const AppId& app_id, IconPurpose purpose, SquareSizePx size); // Collects icon read/write errors (unbounded) if the |kRecordWebAppDebugInfo| // flag is enabled to be used by: chrome://web-app-internals const std::vector<std::string>* error_log() const { return error_log_.get(); } std::vector<std::string>* error_log() { return error_log_.get(); } private: base::WeakPtr<const WebAppIconManager> GetWeakPtr() const; base::WeakPtr<WebAppIconManager> GetWeakPtr(); absl::optional<IconSizeAndPurpose> FindIconMatchSmaller( const AppId& app_id, const std::vector<IconPurpose>& purposes, SquareSizePx max_size) const; void OnReadUiScaleFactorsIcons(SquareSizeDip size_in_dip, ReadImageSkiaCallback callback, std::map<SquareSizePx, SkBitmap> icon_bitmaps); void ReadFavicon(const AppId& app_id); void OnReadFavicon(const AppId& app_id, gfx::ImageSkia image_skia); void ReadMonochromeFavicon(const AppId& app_id); void OnReadMonochromeFavicon(const AppId& app_id, gfx::ImageSkia manifest_monochrome_image); void OnMonochromeIconConverted(const AppId& app_id, gfx::ImageSkia converted_image); raw_ptr<WebAppRegistrar, DanglingUntriaged> registrar_; raw_ptr<WebAppInstallManager, DanglingUntriaged> install_manager_; base::FilePath web_apps_directory_; scoped_refptr<FileUtilsWrapper> utils_; scoped_refptr<base::SequencedTaskRunner> icon_task_runner_; base::ScopedObservation<WebAppInstallManager, WebAppInstallManagerObserver> install_manager_observation_{this}; // We cache different densities for high-DPI displays per each app. std::map<AppId, gfx::ImageSkia> favicon_cache_; std::map<AppId, gfx::ImageSkia> favicon_monochrome_cache_; FaviconReadCallback favicon_read_callback_; FaviconReadCallback favicon_monochrome_read_callback_; std::unique_ptr<std::vector<std::string>> error_log_; base::WeakPtrFactory<WebAppIconManager> weak_ptr_factory_{this}; }; } // namespace web_app #endif // CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_ICON_MANAGER_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
eaac686ab3dd48fd95712fc7955b6bd02ba5790c
8cc6ba38a349d095823152c2e030b267b4146677
/sengi-project/lib/pid_controller/pid.cpp
048992c6b45e4907c729538c96f0bfdae097b0e0
[ "MIT" ]
permissive
gbr1/sengi-firmware
bf3213343462a6e6390fd8d9d97d69159ae0d65d
194d91ec780a5fc4c7f52a5174afdf00452d500b
refs/heads/master
2020-05-18T17:32:42.630632
2019-11-10T09:35:17
2019-11-10T09:35:17
184,558,134
1
0
null
null
null
null
UTF-8
C++
false
false
1,743
cpp
/* * The MIT License * * Copyright (c) 2019 Giovanni di Dio Bruno https://gbr1.github.io * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "pid.h" Pid::Pid(float _kp, float _ki, float _kd){ kp=_kp; ki=_ki; kd=_kd; c_ref=0; c_in=0; c_out=0; error=0; p_error=0; c_i=0; c_d=0; maxv=MAXVALUE; minv=-MAXVALUE; } float Pid::compute(){ error=c_ref-c_in; c_i=c_i+(ki*error); c_i=checkMaxMin(c_i, minv, maxv); c_d=kd*(error-p_error); c_out=kp*error+c_i+c_d; c_out=checkMaxMin(c_out, minv, maxv); p_error=error; return c_out; } float Pid::checkMaxMin(float v, float min, float max){ if (v>max){ return max; } if (v<min){ return min; } return v; }
[ "giovannididio.bruno@gmail.com" ]
giovannididio.bruno@gmail.com