hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
82accb65fbdf09a8d5c26b07d2810af4a2641473
563
cpp
C++
UVA/vol-008/824.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
3
2017-05-12T14:45:37.000Z
2020-01-18T16:51:25.000Z
UVA/vol-008/824.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
UVA/vol-008/824.cpp
arash16/prays
0fe6bb2fa008b8fc46c80b01729f68308114020d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> using namespace std; int xx[] = {0, -1, -1, -1, 0, 1, 1, 1}, yy[] = {1, 1, 0, -1, -1, -1, 0, 1}, M[3][3]; int nextDir(int d) { for (int i=0; i<8; i++) { int nd = (d+6+i)%8; if (M[xx[nd]+1][yy[nd]+1]) return nd; } return d; } int main() { int x, y, d, xi, yi, si; while (cin>>x>>y>>d && (x>=0 && y>=0 && d>=0)) { for (int i=0; i<8; i++) { cin>>xi>>yi>>si; M[xi-x+1][yi-y+1] = si; } cout << nextDir(d) << endl; } }
20.107143
52
0.383659
arash16
82aed8787b07aa0e66a9df492b4112c609361edf
27,599
cpp
C++
implementations/ugene/src/corelibs/U2Lang/src/model/QDScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Lang/src/model/QDScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Lang/src/model/QDScheme.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * 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. */ #include "QDScheme.h" #include <U2Core/DNASequenceObject.h> #include <U2Core/Log.h> #include <U2Lang/SupportClass.h> #include "ConfigurationEditor.h" #include "QDConstraint.h" namespace U2 { void QDParameters::setParameter(const QString &name, const QVariant &val) { Configuration::setParameter(name, val); emit si_modified(); } //QDActor ////////////////////////////////////////////////////////////////////////// const int QDActor::DEFAULT_MAX_RESULT_LENGTH(10000); QDActor::QDActor(QDActorPrototype const *_proto) : scheme(NULL), proto(_proto), strand(QDStrand_Both), simmetric(false) { cfg = new QDActorParameters; foreach (Attribute *a, proto->getParameters()) { cfg->addParameter(a->getId(), a->clone()); } ConfigurationEditor *ed = proto->getEditor(); if (ed) { cfg->setEditor(ed); } const QMap<QString, Attribute *> &attrs = cfg->getParameters(); QMapIterator<QString, Attribute *> it(attrs); while (it.hasNext()) { it.next(); defaultCfg[it.key()] = it.value()->getAttributePureValue(); } } QDActor::~QDActor() { qDeleteAll(paramConstraints); delete cfg; } void QDActor::reset() { const QMap<QString, Attribute *> &attrs = cfg->getParameters(); foreach (const QString &key, attrs.keys()) { Attribute *a = attrs[key]; a->setAttributeValue(defaultCfg.value(key)); } } bool contains(const QDResultUnit &res, const QVector<U2Region> &location) { foreach (const U2Region &r, location) { if (r.contains(res->region)) { return true; } } return false; } void QDActor::filterResults(const QVector<U2Region> &) { /*QList<QDResultGroup*> res = results; foreach(QDResultGroup* grp, res) { foreach(const QDResultUnit& ru, grp->getResultsList()) { if (!contains(ru, location)) { results.removeOne(grp); break; } } }*/ } QList<QDResultGroup *> QDActor::popResults() { QList<QDResultGroup *> res = results; results.clear(); return res; } static const QString KEY_ATTR = "key"; QList<QPair<QString, QString>> QDActor::saveConfiguration() const { QList<QPair<QString, QString>> res; QMapIterator<QString, Attribute *> it(cfg->getParameters()); QString annKey = cfg->getAnnotationKey(); if (annKey.contains(' ')) { annKey = "\"" + annKey + "\""; } res.append(qMakePair(KEY_ATTR, annKey)); while (it.hasNext()) { it.next(); Attribute *a = it.value(); if (a->getAttributePureValue() == defaultCfg.value(it.key())) { continue; } //QString displayName = QDAttributeNameConverter::convertAttrName(a->getDisplayName()); QString displayName = a->getId(); QPair<QString, QString> newAttr = qMakePair(displayName, a->getAttributePureValue().toString()); res.append(newAttr); } return res; } void QDActor::loadConfiguration(const QList<QPair<QString, QString>> &strMap) { foreach (const StringAttribute &attr, strMap) { if (attr.first == KEY_ATTR) { cfg->setAnnotationKey(attr.second); } QMapIterator<QString, Attribute *> paramsIterator(cfg->getParameters()); while (paramsIterator.hasNext()) { paramsIterator.next(); Attribute *a = paramsIterator.value(); if (QDAttributeNameConverter::convertAttrName(a->getId()) == attr.first) { QVariant val = QDAttributeValueMapper::stringToAttributeValue(attr.second); cfg->setParameter(a->getId(), val); break; } } } } QDStrandOption QDActor::getStrandToRun() const { QDStrandOption schemaStrand = scheme->getStrand(); QDStrandOption strand2run = QDStrand_Both; if (schemaStrand != QDStrand_Both) { if (schemaStrand == QDStrand_DirectOnly) { strand2run = strand; } if (schemaStrand == QDStrand_ComplementOnly) { if (strand == QDStrand_DirectOnly) { strand2run = QDStrand_ComplementOnly; } if (strand == QDStrand_ComplementOnly) { strand2run = QDStrand_DirectOnly; } } } return strand2run; } QDStrandOption QDActor::getStrand() const { if (hasStrand()) { return strand; } //return QDStrand_DirectOnly; return QDStrand_Both; } void QDActor::setStrand(QDStrandOption stOp) { strand = stOp; emit si_strandChanged(strand); } QList<QDConstraint *> QDActor::getConstraints() const { QList<QDConstraint *> res; foreach (QDSchemeUnit *su, units) { res << su->getConstraints(); } return res; } //QDSchemeUnit ////////////////////////////////////////////////////////////////////////// QString QDSchemeUnit::getPersonalName() const { const QList<QDSchemeUnit *> &units = actor->getSchemeUnits(); if (units.size() == 1) { return actor->getParameters()->getLabel(); } QDSchemeUnit *s = const_cast<QDSchemeUnit *>(this); assert(units.contains(s)); int idx = units.indexOf(s) + 1; QString result = QString("%1_%2") .arg(actor->getParameters()->getLabel()) .arg(QString::number(idx)); return result; } QList<QDDistanceConstraint *> QDSchemeUnit::getDistanceConstraints() const { QList<QDDistanceConstraint *> res; foreach (QDConstraint *c, schemeConstraints) { QDDistanceConstraint *dc = static_cast<QDDistanceConstraint *>(c); if (dc) { res.append(dc); } } return res; } //QDScheme ////////////////////////////////////////////////////////////////////////// QDScheme::~QDScheme() { foreach (QDActor *a, actors) { removeActor(a); } } void QDScheme::addActor(QDActor *a) { assert(!actors.contains(a)); assert(a->scheme == NULL); foreach (QDSchemeUnit *su, a->getSchemeUnits()) { assert(su->getConstraints().isEmpty()); Q_UNUSED(su); } a->scheme = this; actors.append(a); emit si_schemeChanged(); } bool QDScheme::removeActor(QDActor *a) { if (actors.contains(a)) { foreach (QDSchemeUnit *su, a->getSchemeUnits()) { foreach (QDConstraint *c, su->getConstraints()) { removeConstraint(c); } } actors.removeOne(a); const QString &ag = getActorGroup(a); if (!ag.isEmpty()) { actorGroups[ag].removeOne(a); } delete a; emit si_schemeChanged(); return true; } return false; } void QDScheme::addConstraint(QDConstraint *constraint) { foreach (QDSchemeUnit *su, constraint->getSchemeUnits()) { assert(actors.contains(su->getActor())); su->schemeConstraints.append(constraint); } emit si_schemeChanged(); } void QDScheme::removeConstraint(QDConstraint *constraint) { const QList<QDSchemeUnit *> &constraintUnits = constraint->getSchemeUnits(); foreach (QDSchemeUnit *su, constraintUnits) { QDActor *actor = su->getActor(); Q_UNUSED(actor); assert(actors.contains(actor)); assert(su->getConstraints().contains(constraint)); su->schemeConstraints.removeOne(constraint); } delete constraint; emit si_schemeChanged(); } QList<QDConstraint *> QDScheme::getConstraints() const { QList<QDConstraint *> res; foreach (QDActor *actor, actors) { foreach (QDSchemeUnit *su, actor->getSchemeUnits()) { foreach (QDConstraint *c, su->getConstraints()) { if (!res.contains(c)) { res.append(c); } } } } return res; } QList<QDConstraint *> QDScheme::getConstraints(QDSchemeUnit const *su1, QDSchemeUnit const *su2) const { QList<QDConstraint *> sharedConstraints; const QList<QDConstraint *> &su1Cons = su1->getConstraints(); const QList<QDConstraint *> &su2Cons = su2->getConstraints(); foreach (QDConstraint *con, su1Cons) { if (su2Cons.contains(con)) { sharedConstraints.append(con); } } return sharedConstraints; } void QDScheme::clear() { //delete dna; dna = DNASequence(); foreach (QDActor *a, actors) { removeActor(a); } actorGroups.clear(); emit si_schemeChanged(); } QList<QDSchemeUnit *> currentRoute; QList<QList<QDSchemeUnit *>> routes; QDSchemeUnit *routeDst = NULL; QList<QDPath *> QDScheme::findPaths(QDSchemeUnit *src, QDSchemeUnit *dst) { assert(currentRoute.isEmpty()); assert(routes.isEmpty()); assert(!routeDst); routeDst = dst; currentRoute.append(src); findRoute(src); QList<QDPath *> res; foreach (const QList<QDSchemeUnit *> &route, routes) { QList<QDPath *> paths; for (int i = 0, m = route.size() - 1; i < m; i++) { QDSchemeUnit *src = route.at(i); QDSchemeUnit *dst = route.at(i + 1); QList<QDConstraint *> joint = getConstraints(src, dst); //include "parameter" constraints foreach (QDConstraint *con, src->getActor()->getParamConstraints()) { if (con->getSchemeUnits().contains(src) && con->getSchemeUnits().contains(dst)) { joint.append(con); } } QList<QDDistanceConstraint *> jointCons; foreach (QDConstraint *con, joint) { QDDistanceConstraint *dc = static_cast<QDDistanceConstraint *>(con); if (dc) { jointCons.append(dc); } } assert(!jointCons.isEmpty()); if (paths.isEmpty()) { foreach (QDDistanceConstraint *dc, jointCons) { QDPath *newPath = new QDPath; bool ok = newPath->addConstraint(dc); assert(ok); Q_UNUSED(ok); paths << newPath; } } else { QList<QDPath *> newPaths; for (int i = 1, n = jointCons.size(); i < n; i++) { foreach (QDPath *path, paths) { QDPath *newPath = path->clone(); bool ok = newPath->addConstraint(jointCons.at(i)); assert(ok); Q_UNUSED(ok); newPaths.append(newPath); } } foreach (QDPath *path, paths) { bool ok = path->addConstraint(jointCons.at(0)); assert(ok); Q_UNUSED(ok); } paths << newPaths; } } res.append(paths); } currentRoute.clear(); routes.clear(); routeDst = NULL; return res; } void QDScheme::findRoute(QDSchemeUnit *curSu) { if (curSu == routeDst) { routes.append(currentRoute); } else { //build list of adjacent vertexes QList<QDSchemeUnit *> adjacentList; QList<QDDistanceConstraint *> dcList = curSu->getDistanceConstraints(); //include "parameter" constraints foreach (QDConstraint *con, curSu->getActor()->getParamConstraints()) { if (con->constraintType() == QDConstraintTypes::DISTANCE) { QDDistanceConstraint *dc = static_cast<QDDistanceConstraint *>(con); if (dc->getSchemeUnits().contains(curSu)) { dcList.append(dc); } } } foreach (QDDistanceConstraint *dc, dcList) { QDSchemeUnit *adj = NULL; QDSchemeUnit *dcSrc = dc->getSource(); QDSchemeUnit *dcDst = dc->getDestination(); if (curSu == dcSrc) { adj = dcDst; } else { assert(curSu == dcDst); adj = dcSrc; } if (!adjacentList.contains(adj)) { adjacentList.append(adj); } } foreach (QDSchemeUnit *adj, adjacentList) { if (!currentRoute.contains(adj)) { currentRoute.append(adj); findRoute(adj); currentRoute.removeOne(adj); } } } } //QDPath ////////////////////////////////////////////////////////////////////////// QDPath::~QDPath() { delete overallConstraint; } QDPath *QDPath::clone() const { QDPath *cln = new QDPath; cln->constraints = constraints; cln->pathSrc = pathSrc; cln->pathDst = pathDst; return cln; } bool QDPath::addConstraint(QDDistanceConstraint *dc) { assert(!constraints.contains(dc)); QDSchemeUnit *dcSrc = dc->getSource(); QDSchemeUnit *dcDst = dc->getDestination(); if (!pathSrc) { assert(!pathDst); pathSrc = dcSrc; pathDst = dcDst; constraints.append(dc); schemeUnits << pathSrc << pathDst; } else if (pathDst == dcSrc) { pathDst = dcDst; constraints.append(dc); schemeUnits << pathDst; } else if (pathDst == dcDst) { pathDst = dcSrc; constraints.append(dc); schemeUnits << pathDst; } else if (pathSrc == dcSrc) { pathSrc = dcDst; constraints.prepend(dc); schemeUnits << pathSrc; } else if (pathSrc == dcDst) { pathSrc = dcSrc; constraints.prepend(dc); schemeUnits << pathSrc; } else { return false; } return true; } QDDistanceConstraint *QDPath::toConstraint() { if (constraints.isEmpty()) { return NULL; } delete overallConstraint; int minDist = 0, maxDist = 0; QDSchemeUnit *curSu = pathSrc; for (int i = 0, n = constraints.size(); i < n; i++) { QDDistanceConstraint *curDc = constraints.at(i); QDDistanceConstraint *nextDc = NULL; if (i + 1 < n) { nextDc = constraints.at(i + 1); } QDSchemeUnit *curDcSrc = curDc->getSource(); QDSchemeUnit *curDcDst = curDc->getDestination(); if (curSu == curDcSrc) { curSu = curDcDst; minDist += curDc->getMin(); maxDist += curDc->getMax(); if (!nextDc) { continue; } QDSchemeUnit *nextDcSrc = nextDc->getSource(); QDSchemeUnit *nextDcDst = nextDc->getDestination(); if (nextDcSrc == curSu) { if (curDc->distanceType() == S2S || curDc->distanceType() == E2S) { if (nextDc->distanceType() == E2S || nextDc->distanceType() == E2E) { minDist += curSu->getActor()->getMinResultLen(); maxDist += curSu->getActor()->getMaxResultLen(); } } else { // S2E || E2E if (nextDc->distanceType() == S2S || nextDc->distanceType() == S2E) { minDist -= curSu->getActor()->getMaxResultLen(); maxDist -= curSu->getActor()->getMinResultLen(); } } } else { assert(nextDcDst == curSu); Q_UNUSED(nextDcDst); if (curDc->distanceType() == E2S || curDc->distanceType() == S2S) { if (nextDc->distanceType() == S2E || nextDc->distanceType() == E2E) { minDist += curSu->getActor()->getMinResultLen(); maxDist += curSu->getActor()->getMaxResultLen(); } } else { // S2E || E2E if (nextDc->distanceType() == S2S || nextDc->distanceType() == E2S) { minDist -= curSu->getActor()->getMaxResultLen(); maxDist -= curSu->getActor()->getMinResultLen(); } } } } else { assert(curSu == curDcDst); curSu = curDcSrc; minDist -= curDc->getMax(); maxDist -= curDc->getMin(); if (!nextDc) { continue; } QDSchemeUnit *nextDcSrc = nextDc->getSource(); QDSchemeUnit *nextDcDst = nextDc->getDestination(); if (nextDcSrc == curSu) { if (curDc->distanceType() == S2S || curDc->distanceType() == S2E) { if (nextDc->distanceType() == E2S || nextDc->distanceType() == E2E) { minDist += curSu->getActor()->getMinResultLen(); maxDist += curSu->getActor()->getMaxResultLen(); } } else { // E2S || E2E if (nextDc->distanceType() == S2S || nextDc->distanceType() == S2E) { minDist -= curSu->getActor()->getMaxResultLen(); maxDist -= curSu->getActor()->getMinResultLen(); } } } else { assert(nextDcDst == curSu); Q_UNUSED(nextDcDst); if (curDc->distanceType() == E2S || curDc->distanceType() == E2E) { if (nextDc->distanceType() == S2S || nextDc->distanceType() == E2S) { minDist -= curSu->getActor()->getMaxResultLen(); maxDist -= curSu->getActor()->getMinResultLen(); } } else { // S2E || S2S if (nextDc->distanceType() == S2E || nextDc->distanceType() == E2E) { minDist += curSu->getActor()->getMinResultLen(); maxDist += curSu->getActor()->getMaxResultLen(); } } } } } if (maxDist < minDist) { return NULL; } QDDistanceConstraint *firstDc = constraints.first(); QDDistanceConstraint *lastDc = constraints.last(); QList<QDSchemeUnit *> units; units << pathSrc << pathDst; QDDistanceType distType = E2S; if (pathSrc == firstDc->getSource()) { if (pathDst == lastDc->getSource()) { if (firstDc->distanceType() == S2S || firstDc->distanceType() == S2E) { if (lastDc->distanceType() == S2S || lastDc->distanceType() == S2E) { distType = S2S; } else { // E2S || E2E distType = S2E; } } else { // E2S || E2E if (lastDc->distanceType() == S2S || lastDc->distanceType() == S2E) { distType = E2S; } else { // E2S || E2E distType = E2E; } } } else { assert(pathDst == lastDc->getDestination()); if (firstDc->distanceType() == S2S || firstDc->distanceType() == S2E) { if (lastDc->distanceType() == S2S || lastDc->distanceType() == E2S) { distType = S2S; } else { // S2E || E2E distType = S2E; } } else { // E2S || E2E if (lastDc->distanceType() == S2S || lastDc->distanceType() == E2S) { distType = E2S; } else { // S2E || E2E distType = E2E; } } } } else { assert(pathSrc == firstDc->getDestination()); if (pathDst == lastDc->getSource()) { if (firstDc->distanceType() == S2S || firstDc->distanceType() == E2S) { if (lastDc->distanceType() == S2S || lastDc->distanceType() == S2E) { distType = S2S; } else { // E2S || E2E distType = S2E; } } else { // S2E || E2E if (lastDc->distanceType() == E2S || lastDc->distanceType() == E2E) { distType = E2E; } else { // S2S || S2E distType = E2S; } } } else { assert(pathDst == lastDc->getDestination()); if (firstDc->distanceType() == S2S || firstDc->distanceType() == E2S) { if (lastDc->distanceType() == S2S || lastDc->distanceType() == E2S) { distType = S2S; } else { // S2E || E2E distType = S2E; } } else { // S2E || E2E if (lastDc->distanceType() == S2S || lastDc->distanceType() == E2S) { distType = E2S; } else { // S2E || E2E distType = E2E; } } } } overallConstraint = new QDDistanceConstraint(units, distType, minDist, maxDist); return overallConstraint; } void QDScheme::setOrder(QDActor *a, int serialNum) { assert(actors.contains(a)); int aIdx = actors.indexOf(a); if (serialNum < 0) { actors.move(aIdx, 0); return; } if (serialNum >= actors.size()) { actors.move(aIdx, actors.size() - 1); return; } actors.move(aIdx, serialNum); } bool QDScheme::isValid() const { bool res = true; foreach (QDActor *actor, getActors()) { QDActorParameters *cfg = actor->getParameters(); NotificationsList notificationList; if (!cfg->validate(notificationList)) { res = false; foreach (const WorkflowNotification &notification, notificationList) { coreLog.error(QObject::tr("%1. %2").arg(cfg->getLabel()).arg(notification.message)); } } } foreach (QDConstraint *con, getConstraints()) { if (con->constraintType() == QDConstraintTypes::DISTANCE) { QDDistanceConstraint *dc = static_cast<QDDistanceConstraint *>(con); if (dc->getMin() > dc->getMax()) { coreLog.error(QObject::tr("Invalid distance values")); res = false; } QDActor *src = dc->getSource()->getActor(); QDActor *dst = dc->getDestination()->getActor(); QString group = getActorGroup(src); if (!group.isEmpty() && getActors(group).contains(dst)) { coreLog.error(QObject::tr("Constraints can not be placed between elements of the same group")); res = false; } } } return res; } QDActor *QDScheme::getActorByLabel(const QString &label) const { foreach (QDActor *a, actors) { if (a->getParameters()->getLabel() == label) { return a; } } return NULL; } void QDScheme::addActorToGroup(QDActor *a, const QString &group) { assert(actors.contains(a)); assert(getActorGroup(a).isEmpty()); assert(actorGroups.keys().contains(group)); actorGroups[group].append(a); emit si_schemeChanged(); } bool QDScheme::removeActorFromGroup(QDActor *a) { const QString &group = getActorGroup(a); if (!group.isEmpty()) { bool res = actorGroups[group].removeOne(a); if (res) { emit si_schemeChanged(); } } return false; } void QDScheme::createActorGroup(const QString &name) { assert(validateGroupName(name)); assert(!actorGroups.keys().contains(name)); actorGroups.insert(name, QList<QDActor *>()); actorGroupReqNum[name] = 1; emit si_schemeChanged(); } bool QDScheme::removeActorGroup(const QString &name) { bool res = actorGroups.remove(name); emit si_schemeChanged(); return res; } QString QDScheme::getActorGroup(QDActor *a) const { QMapIterator<QString, QList<QDActor *>> i(actorGroups); while (i.hasNext()) { i.next(); if (i.value().contains(a)) { return i.key(); } } return QString(); } bool QDScheme::validateGroupName(const QString &name) const { if (name.isEmpty()) { return false; } return true; } void QDScheme::setRequiredNum(const QString &group, int num) { assert(actorGroups.keys().contains(group)); const QList<QDActor *> &grpMembrs = actorGroups.value(group); Q_UNUSED(grpMembrs); assert(num <= grpMembrs.size()); actorGroupReqNum[group] = num; emit si_schemeChanged(); } void QDScheme::adaptActorsOrder() { QList<QDActor *> actorsQueue; foreach (QDActor *a, actors) { QString group = getActorGroup(a); if (group.isEmpty()) { assert(!actorsQueue.contains(a)); actorsQueue.append(a); } else if (!actorsQueue.contains(a)) { const QList<QDActor *> &groupActors = getActors(group); actorsQueue.append(groupActors); } } actors = actorsQueue; } //QDResultGroup ////////////////////////////////////////////////////////////////////////// void QDResultGroup::add(const QDResultUnit &res) { if (results.isEmpty()) { startPos = res->region.startPos; endPos = res->region.endPos(); } else { if (res->region.startPos < startPos) { startPos = res->region.startPos; } if (res->region.endPos() > endPos) { endPos = res->region.endPos(); } } results.append(res); } void QDResultGroup::add(const QList<QDResultUnit> &res) { foreach (const QDResultUnit &r, res) { add(r); } } void QDResultGroup::buildGroupFromSingleResult(const QDResultUnit &ru, QList<QDResultGroup *> &results) { QDStrandOption groupStrand = ru->strand == U2Strand::Direct ? QDStrand_DirectOnly : QDStrand_ComplementOnly; QDResultGroup *g = new QDResultGroup(groupStrand); g->add(ru); results.append(g); } //AttributeValueMapper ////////////////////////////////////////////////////////////////////////// const QMap<QString, bool> QDAttributeValueMapper::BOOLEAN_MAP = initBooleanMap(); QMap<QString, bool> QDAttributeValueMapper::initBooleanMap() { QMap<QString, bool> map; map.insertMulti("true", true); map.insertMulti("yes", true); map.insertMulti("1", true); map.insertMulti("false", false); map.insertMulti("no", false); map.insertMulti("0", false); return map; } QVariant QDAttributeValueMapper::stringToAttributeValue(const QString &str) { if (getType(str) == BOOLEAN_TYPE) { return qVariantFromValue(BOOLEAN_MAP.value(str)); } return qVariantFromValue(str); } QDAttributeValueMapper::ValueType QDAttributeValueMapper::getType(const QString &val) { if (BOOLEAN_MAP.keys().contains(val)) { return BOOLEAN_TYPE; } else { return UNKNOWN_TYPE; } } QDActorPrototype::~QDActorPrototype() { qDeleteAll(attributes); delete editor; } } // namespace U2
33.132053
112
0.542701
r-barnes
82aefa5aedb5b6aabd5779e6299924032700efa5
12,903
cpp
C++
src/programs/mdrun/tests/freeenergy.cpp
HITS-MBM/gromacs-developments
2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
src/programs/mdrun/tests/freeenergy.cpp
HITS-MBM/gromacs-developments
2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c
[ "BSD-2-Clause" ]
9
2015-04-07T20:48:00.000Z
2022-01-24T21:29:26.000Z
src/programs/mdrun/tests/freeenergy.cpp
HITS-MBM/gromacs-developments
2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Tests to compare free energy simulations to reference * * \author Pascal Merz <pascal.merz@me.com> * \ingroup module_mdrun_integration_tests */ #include "gmxpre.h" #include "config.h" #include "gromacs/topology/ifunc.h" #include "gromacs/utility/filestream.h" #include "gromacs/utility/path.h" #include "gromacs/utility/stringutil.h" #include "testutils/mpitest.h" #include "testutils/refdata.h" #include "testutils/setenv.h" #include "testutils/simulationdatabase.h" #include "testutils/xvgtest.h" #include "moduletest.h" #include "simulatorcomparison.h" namespace gmx::test { namespace { /*! \brief Test fixture base for free energy calculations * * This test ensures that selected free energy perturbation calculations produce * results identical to an earlier version. The results of this earlier version * have been verified manually to ensure physical correctness. */ using MaxNumWarnings = int; using ListOfInteractionsToTest = std::vector<int>; using FreeEnergyReferenceTestParams = std::tuple<std::string, MaxNumWarnings, ListOfInteractionsToTest>; class FreeEnergyReferenceTest : public MdrunTestFixture, public ::testing::WithParamInterface<FreeEnergyReferenceTestParams> { public: struct PrintParametersToString { template<class ParamType> std::string operator()(const testing::TestParamInfo<ParamType>& parameter) const { auto simulationName = std::get<0>(parameter.param); std::replace(simulationName.begin(), simulationName.end(), '-', '_'); return simulationName + (GMX_DOUBLE ? "_d" : "_s"); } }; }; TEST_P(FreeEnergyReferenceTest, WithinTolerances) { const auto& simulationName = std::get<0>(GetParam()); const auto maxNumWarnings = std::get<1>(GetParam()); const auto& interactionsList = std::get<2>(GetParam()); // As these tests check reproducibility, we restrict the maximum number // of ranks to allow us to keep the tolerances tight. See also #3741. const int numRanksAvailable = getNumberOfTestMpiRanks(); constexpr int maxNumRanks = 8; if (numRanksAvailable > maxNumRanks) { fprintf(stdout, "The FEP tests cannot run with %d ranks.\n" "The maximum number of ranks supported is %d.", numRanksAvailable, maxNumRanks); return; } SCOPED_TRACE(formatString("Comparing FEP simulation '%s' to reference", simulationName.c_str())); // Tolerance set to pass with identical code version and a range of different test setups for most tests const auto defaultEnergyTolerance = relativeToleranceAsFloatingPoint(50.0, GMX_DOUBLE ? 1e-5 : 1e-4); // Some simulations are significantly longer, so they need a larger tolerance const auto longEnergyTolerance = relativeToleranceAsFloatingPoint(50.0, GMX_DOUBLE ? 1e-4 : 1e-3); const bool isLongSimulation = (simulationName == "expanded"); const auto energyTolerance = isLongSimulation ? longEnergyTolerance : defaultEnergyTolerance; EnergyTermsToCompare energyTermsToCompare{ { interaction_function[F_EPOT].longname, energyTolerance } }; for (const auto& interaction : interactionsList) { energyTermsToCompare.emplace(interaction_function[interaction].longname, defaultEnergyTolerance); } // Specify how trajectory frame matching must work (only testing forces). TrajectoryFrameMatchSettings trajectoryMatchSettings{ false, false, false, ComparisonConditions::NoComparison, ComparisonConditions::NoComparison, ComparisonConditions::MustCompare }; TrajectoryTolerances trajectoryTolerances = TrajectoryComparison::s_defaultTrajectoryTolerances; trajectoryTolerances.forces = relativeToleranceAsFloatingPoint(100.0, GMX_DOUBLE ? 5.0e-5 : 5.0e-4); // Build the functor that will compare reference and test // trajectory frames in the chosen way. TrajectoryComparison trajectoryComparison{ trajectoryMatchSettings, trajectoryTolerances }; // Set simulation file names auto simulationTrajectoryFileName = fileManager_.getTemporaryFilePath("trajectory.trr"); auto simulationEdrFileName = fileManager_.getTemporaryFilePath("energy.edr"); auto simulationDhdlFileName = fileManager_.getTemporaryFilePath("dhdl.xvg"); // Run grompp runner_.tprFileName_ = fileManager_.getTemporaryFilePath("sim.tpr"); runner_.useTopGroAndMdpFromFepTestDatabase(simulationName); runGrompp(&runner_, { SimulationOptionTuple("-maxwarn", std::to_string(maxNumWarnings)) }); // Do mdrun runner_.fullPrecisionTrajectoryFileName_ = simulationTrajectoryFileName; runner_.edrFileName_ = simulationEdrFileName; runner_.dhdlFileName_ = simulationDhdlFileName; runMdrun(&runner_); /* Currently used tests write trajectory (x/v/f) frames every 20 steps. * Except for the expanded ensemble test, all tests run for 20 steps total. * As the tolerances are relatively strict, we need to restrict the number of * force frames we can expect to match. * Testing more than the first force frame is only feasible in double precision * using a single rank. * Testing one force frame is only feasible in double precision. * Note that this only concerns trajectory frames, energy frames are checked * in all cases. */ const bool testTwoTrajectoryFrames = (GMX_DOUBLE && (getNumberOfTestMpiRanks() == 1)); const bool testOneTrajectoryFrame = GMX_DOUBLE; // Compare simulation results TestReferenceData refData; TestReferenceChecker rootChecker(refData.rootChecker()); // Check that the energies agree with the refdata within tolerance. checkEnergiesAgainstReferenceData(simulationEdrFileName, energyTermsToCompare, &rootChecker); // Check that the trajectories agree with the refdata within tolerance. if (testTwoTrajectoryFrames) { checkTrajectoryAgainstReferenceData( simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(2)); } else if (testOneTrajectoryFrame) { checkTrajectoryAgainstReferenceData( simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(1)); } else { checkTrajectoryAgainstReferenceData( simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(0)); } if (File::exists(simulationDhdlFileName, File::returnFalseOnError)) { TextInputFile dhdlFile(simulationDhdlFileName); auto settings = XvgMatchSettings(); settings.tolerance = defaultEnergyTolerance; checkXvgFile(&dhdlFile, &rootChecker, settings); } } // TODO: The time for OpenCL kernel compilation means these tests time // out. Once that compilation is cached for the whole process, these // tests can run in such configurations. #if !GMX_GPU_OPENCL INSTANTIATE_TEST_SUITE_P( FreeEnergyCalculationsAreEquivalentToReference, FreeEnergyReferenceTest, ::testing::Values( FreeEnergyReferenceTestParams{ "coulandvdwsequential_coul", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, FreeEnergyReferenceTestParams{ "coulandvdwsequential_vdw", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, FreeEnergyReferenceTestParams{ "coulandvdwtogether", MaxNumWarnings(0), { F_DVDL } }, FreeEnergyReferenceTestParams{ "expanded", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, // Tolerated warnings: No default bonded interaction types for perturbed atoms (10x) FreeEnergyReferenceTestParams{ "relative", MaxNumWarnings(10), { F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED } }, // Tolerated warnings: No default bonded interaction types for perturbed atoms (10x) FreeEnergyReferenceTestParams{ "relative-position-restraints", MaxNumWarnings(10), { F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED, F_DVDL_RESTRAINT } }, FreeEnergyReferenceTestParams{ "restraints", MaxNumWarnings(0), { F_DVDL_RESTRAINT } }, FreeEnergyReferenceTestParams{ "simtemp", MaxNumWarnings(0), {} }, FreeEnergyReferenceTestParams{ "transformAtoB", MaxNumWarnings(0), { F_DVDL } }, FreeEnergyReferenceTestParams{ "vdwalone", MaxNumWarnings(0), { F_DVDL } }), FreeEnergyReferenceTest::PrintParametersToString()); #else INSTANTIATE_TEST_SUITE_P( DISABLED_FreeEnergyCalculationsAreEquivalentToReference, FreeEnergyReferenceTest, ::testing::Values( FreeEnergyReferenceTestParams{ "coulandvdwsequential_coul", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, FreeEnergyReferenceTestParams{ "coulandvdwsequential_vdw", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, FreeEnergyReferenceTestParams{ "coulandvdwtogether", MaxNumWarnings(0), { F_DVDL } }, FreeEnergyReferenceTestParams{ "expanded", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } }, // Tolerated warnings: No default bonded interaction types for perturbed atoms (10x) FreeEnergyReferenceTestParams{ "relative", MaxNumWarnings(10), { F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED } }, // Tolerated warnings: No default bonded interaction types for perturbed atoms (10x) FreeEnergyReferenceTestParams{ "relative-position-restraints", MaxNumWarnings(10), { F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED, F_DVDL_RESTRAINT } }, FreeEnergyReferenceTestParams{ "restraints", MaxNumWarnings(0), { F_DVDL_RESTRAINT } }, FreeEnergyReferenceTestParams{ "simtemp", MaxNumWarnings(0), {} }, FreeEnergyReferenceTestParams{ "transformAtoB", MaxNumWarnings(0), { F_DVDL } }, FreeEnergyReferenceTestParams{ "vdwalone", MaxNumWarnings(0), { F_DVDL } }), FreeEnergyReferenceTest::PrintParametersToString()); #endif } // namespace } // namespace gmx::test
49.626923
108
0.663179
HITS-MBM
82b1726633c4e99570f12e8e0181b124cb80872e
454
hpp
C++
pbxbuild/build_file.hpp
GuardianEngine/pbxbuild
90af1e5b963137766d486a918eaedab7c8b21c1a
[ "MIT" ]
1
2017-06-09T15:58:55.000Z
2017-06-09T15:58:55.000Z
pbxbuild/build_file.hpp
GuardianEngine/pbxbuild
90af1e5b963137766d486a918eaedab7c8b21c1a
[ "MIT" ]
null
null
null
pbxbuild/build_file.hpp
GuardianEngine/pbxbuild
90af1e5b963137766d486a918eaedab7c8b21c1a
[ "MIT" ]
2
2017-06-09T15:58:59.000Z
2020-08-15T05:37:19.000Z
#pragma once #include "base_object.hpp" #include "file_element.hpp" #include "project.hpp" #include "../libpbxparser/value.hpp" #include <string> namespace pbx { class BuildFile : public pbx::BaseObject { std::string _file_ref; pbx::Dictionary _settings; public: BuildFile(const std::shared_ptr<pbx::Project>& project, const std::string& uid, const pbx::Dictionary& data); std::shared_ptr<const pbx::FileReference> file() const; }; }
20.636364
111
0.720264
GuardianEngine
a1121af0b14432210bb859cef5e2658a503cc9be
381
cpp
C++
src/string/MANACHER.cpp
hec12/nocow_library
1993006627bc0f1d1e9d4678a00685ca6bd5e611
[ "MIT" ]
null
null
null
src/string/MANACHER.cpp
hec12/nocow_library
1993006627bc0f1d1e9d4678a00685ca6bd5e611
[ "MIT" ]
null
null
null
src/string/MANACHER.cpp
hec12/nocow_library
1993006627bc0f1d1e9d4678a00685ca6bd5e611
[ "MIT" ]
null
null
null
auto manacher(const string &in) { int n = in.size(); string s(2 * n - 1, '#'); rep(i, n) s[2 * i] = in[i]; n = 2 * n - 1; vector<int> r(n); int i = 0, j = 0, k; while (i < n) { while (0 <= i - j && i + j < n && s[i - j] == s[i + j])j++; r[i] = j, k = 1; while (0 <= i - k && i + k < n && k + r[i - k] < r[i])r[i + k] = r[i - k], k++; i += k, j -= k; } return r; }
23.8125
81
0.377953
hec12
a118c8301d42d8ae5e9ad21692072e403101c104
9,012
cc
C++
mysqlshdk/libs/mysql/async_replication.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
mysqlshdk/libs/mysql/async_replication.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
1
2021-09-12T22:07:06.000Z
2021-09-12T22:07:06.000Z
mysqlshdk/libs/mysql/async_replication.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, Oracle and/or its affiliates. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mysqlshdk/libs/mysql/async_replication.h" #include <tuple> #include "mysqlshdk/libs/mysql/group_replication.h" #include "mysqlshdk/libs/mysql/utils.h" #include "mysqlshdk/libs/utils/logger.h" namespace mysqlshdk { namespace mysql { void change_master(mysqlshdk::mysql::IInstance *instance, const std::string &master_host, int master_port, const std::string &channel_name, const Auth_options &credentials, const mysqlshdk::utils::nullable<int> master_connect_retry, const mysqlshdk::utils::nullable<int> master_retry_count, const mysqlshdk::utils::nullable<int> master_delay) { log_info( "Setting up async source for channel '%s' of %s to %s:%i (user " "%s)", channel_name.c_str(), instance->descr().c_str(), master_host.c_str(), master_port, (credentials.user.empty() ? "unchanged" : "'" + credentials.user + "'") .c_str()); try { std::string source_term_cmd = mysqlshdk::mysql::get_replication_source_keyword( instance->get_version(), true); std::string source_term = mysqlshdk::mysql::get_replication_source_keyword( instance->get_version()); std::string options; if (!master_retry_count.is_null()) options.append(", " + source_term + "_RETRY_COUNT=" + std::to_string(*master_retry_count)); if (!master_connect_retry.is_null()) options.append(", " + source_term + "_CONNECT_RETRY=" + std::to_string(*master_connect_retry)); if (!master_delay.is_null()) options.append(", " + source_term + "_DELAY=" + std::to_string(*master_delay)); instance->executef("CHANGE " + source_term_cmd + " TO /*!80011 get_master_public_key=1, */" " " + source_term + "_HOST=/*(*/ ? /*)*/, " + source_term + "_PORT=/*(*/ ? /*)*/," " " + source_term + "_USER=?, " + source_term + "_PASSWORD=/*((*/ ? /*))*/" + options + ", " + source_term + "_AUTO_POSITION=1" " FOR CHANNEL ?", master_host, master_port, credentials.user, *credentials.password, channel_name); } catch (const std::exception &e) { log_error("Error setting up async replication: %s", e.what()); throw; } } void change_master_host_port(mysqlshdk::mysql::IInstance *instance, const std::string &master_host, int master_port, const std::string &channel_name) { log_info("Changing source address for channel '%s' of %s to %s:%i", channel_name.c_str(), instance->descr().c_str(), master_host.c_str(), master_port); std::string source_term_cmd = mysqlshdk::mysql::get_replication_source_keyword(instance->get_version(), true); std::string source_term = mysqlshdk::mysql::get_replication_source_keyword(instance->get_version()); try { instance->executef("CHANGE " + source_term_cmd + " TO " + source_term + "_HOST=/*(*/ ? /*)*/, " + source_term + "_PORT=/*(*/ ? /*)*/ " "FOR CHANNEL ?", master_host, master_port, channel_name); } catch (const std::exception &e) { log_error("Error setting up async replication: %s", e.what()); throw; } } void reset_slave(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name, bool reset_credentials) { log_debug("Resetting replica%s channel '%s' for %s...", reset_credentials ? " ALL" : "", channel_name.c_str(), instance->descr().c_str()); std::string replica_term = mysqlshdk::mysql::get_replica_keyword(instance->get_version()); if (reset_credentials) { instance->executef("RESET " + replica_term + " ALL FOR CHANNEL ?", channel_name); } else { instance->executef("RESET " + replica_term + " FOR CHANNEL ?", channel_name); } } void start_replication(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Starting replica channel %s for %s...", channel_name.c_str(), instance->descr().c_str()); std::string replica_term = mysqlshdk::mysql::get_replica_keyword(instance->get_version()); instance->executef("START " + replica_term + " FOR CHANNEL ?", channel_name); } void stop_replication(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Stopping replica channel %s for %s...", channel_name.c_str(), instance->descr().c_str()); std::string replica_term = mysqlshdk::mysql::get_replica_keyword(instance->get_version()); instance->executef("STOP " + replica_term + " FOR CHANNEL ?", channel_name); } bool stop_replication_safe(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name, int timeout_sec) { log_debug("Stopping replica channel %s for %s...", channel_name.c_str(), instance->descr().c_str()); std::string replica_term = mysqlshdk::mysql::get_replica_keyword(instance->get_version()); while (timeout_sec-- >= 0) { instance->executef("STOP " + replica_term + " FOR CHANNEL ?", channel_name); auto n = instance->queryf_one_string( 1, "0", "SHOW STATUS LIKE 'Slave_open_temp_tables'"); if (n == "0") return true; log_warning( "Slave_open_tables has unexpected value %s at %s (unsupported SBR in " "use?)", n.c_str(), instance->descr().c_str()); instance->executef("START " + replica_term + " FOR CHANNEL ?", channel_name); shcore::sleep_ms(1000); } return false; } void start_replication_receiver(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Starting replica io_thread %s for %s...", channel_name.c_str(), instance->descr().c_str()); instance->executef( "START " + mysqlshdk::mysql::get_replica_keyword(instance->get_version()) + " IO_THREAD FOR CHANNEL ?", channel_name); } void stop_replication_receiver(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Stopping replica io_thread %s for %s...", channel_name.c_str(), instance->descr().c_str()); instance->executef( "STOP " + mysqlshdk::mysql::get_replica_keyword(instance->get_version()) + " IO_THREAD FOR CHANNEL ?", channel_name); } void start_replication_applier(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Starting replica sql_thread %s for %s...", channel_name.c_str(), instance->descr().c_str()); instance->executef( "START " + mysqlshdk::mysql::get_replica_keyword(instance->get_version()) + " SQL_THREAD FOR CHANNEL ?", channel_name); } void stop_replication_applier(mysqlshdk::mysql::IInstance *instance, const std::string &channel_name) { log_debug("Stopping replica sql_thread %s for %s...", channel_name.c_str(), instance->descr().c_str()); instance->executef( "STOP " + mysqlshdk::mysql::get_replica_keyword(instance->get_version()) + " SQL_THREAD FOR CHANNEL ?", channel_name); } } // namespace mysql } // namespace mysqlshdk
40.778281
80
0.609521
mueller
a119af717649001bca7689721bc5eb5e52d8bd4b
772
cpp
C++
source/polyvec/utils/color.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
source/polyvec/utils/color.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
source/polyvec/utils/color.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
#include <polyvec/utils/color.hpp> #include <polyvec/utils/num.hpp> NAMESPACE_BEGIN(polyfit) NAMESPACE_BEGIN(Color) const vec3 COLOR_MIN(22. / 255, 64. / 255, 229. / 255); const vec3 COLOR_MID(30. / 255, 255. / 255, 97. / 255); const vec3 COLOR_MAX(255. / 255, 45. / 255, 30. / 255); // Returns some kind of interpolated color // <= t_min -> blue // .5 (t_min + t_max) -> green // > t_max -> red // requires t_min < t_max vec3 error(double t_min, double t_max, double t) { const double t_mid = polyvec::Num::lerp(t_min, t_max, .5); if (t <= t_mid) { return polyvec::Num::lerp(COLOR_MIN, COLOR_MID, t / t_mid); } else { return polyvec::Num::lerp(COLOR_MID, COLOR_MAX, polyvec::Num::saturate((t - t_mid) / t_mid)); } } NAMESPACE_END(Color) NAMESPACE_END(polyfit)
29.692308
95
0.67487
ShnitzelKiller
a11c62ca958a645c8e8bec7d57e8065665ffa874
3,029
cc
C++
crypto/cipher/rc4.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
3
2017-04-24T07:00:59.000Z
2020-04-13T04:53:06.000Z
crypto/cipher/rc4.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2017-01-10T04:23:55.000Z
2017-01-10T04:23:55.000Z
crypto/cipher/rc4.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2020-04-13T04:53:07.000Z
2020-04-13T04:53:07.000Z
// Copyright © 2017 by Donald King <chronos@chronos-tachyon.net> // Available under the MIT License. See LICENSE for details. #include "crypto/cipher/rc4.h" #include "base/logging.h" #include "crypto/primitives.h" #include "crypto/security.h" namespace crypto { namespace cipher { inline namespace implementation { struct RC4State { uint8_t state[256]; uint8_t i; uint8_t j; void rekey(const uint8_t* key, uint32_t len); void encrypt(uint8_t* dst, const uint8_t* src, std::size_t len); }; void RC4State::rekey(const uint8_t* key, uint32_t len) { unsigned int x, y; for (x = 0; x < 256; ++x) { state[x] = x; } y = 0; for (x = 0; x < 256; ++x) { y = (y + state[x] + key[x % len]) & 0xff; std::swap(state[x], state[y]); } i = j = 0; } void RC4State::encrypt(uint8_t* dst, const uint8_t* src, std::size_t len) { for (std::size_t x = 0; x < len; x++) { i += 1; j += state[i]; std::swap(state[i], state[j]); dst[x] = src[x] ^ state[(state[i] + state[j]) & 0xff]; } } class RC4Crypter : public Crypter { public: RC4Crypter(base::Bytes key, base::Bytes nonce); bool is_streaming() const noexcept override { return true; } bool is_seekable() const noexcept override { return false; } uint16_t block_size() const noexcept override { return RC4_BLOCKSIZE; } void encrypt(base::MutableBytes dst, base::Bytes src) noexcept override; void decrypt(base::MutableBytes dst, base::Bytes src) noexcept override; private: void set_counter(uint64_t value) noexcept; void set_position(uint64_t value) noexcept; uint64_t fetch_counter() const noexcept; uint64_t fetch_position() const noexcept; void next(); crypto::subtle::SecureMemory<RC4State> state_; }; RC4Crypter::RC4Crypter(base::Bytes key, base::Bytes nonce) { if (key.size() < 1 || key.size() > 256) { throw std::invalid_argument("key size not supported for RC4"); } if (nonce.size() != 0) { throw std::invalid_argument("nonce size not supported for RC4"); } state_->rekey(key.data(), key.size()); } void RC4Crypter::encrypt(base::MutableBytes dst, base::Bytes src) noexcept { CHECK_GE(dst.size(), src.size()); state_->encrypt(dst.data(), src.data(), src.size()); } void RC4Crypter::decrypt(base::MutableBytes dst, base::Bytes src) noexcept { encrypt(dst, src); } } // inline namespace implementation std::unique_ptr<Crypter> new_rc4(base::Bytes key, base::Bytes nonce) { return base::backport::make_unique<RC4Crypter>(key, nonce); } } // namespace cipher } // namespace crypto static const crypto::StreamCipher RC4 = { crypto::cipher::RC4_BLOCKSIZE, // block_size crypto::cipher::RC4_KEYSIZE, // key_size crypto::cipher::RC4_NONCESIZE, // nonce_size crypto::Security::weak, // security 0, // flags "RC4", // name crypto::cipher::new_rc4, // newfn }; static void init() __attribute__((constructor)); static void init() { crypto::register_stream_cipher(&RC4); }
28.847619
76
0.657643
chronos-tachyon
a11f5bc3bebbbae05fd0ca7a47ecce47da3b6ee7
20,045
cpp
C++
KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
13
2019-10-19T17:41:19.000Z
2021-11-04T18:50:03.000Z
KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
3
2019-12-09T06:22:43.000Z
2020-05-28T09:33:44.000Z
KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
null
null
null
#include "KVulkanHeapAllocator.h" #include "KVulkanGlobal.h" #include "KVulkanHelper.h" #include "KBase/Publish/KNumerical.h" #include "KBase/Interface/IKLog.h" #include <algorithm> #include <mutex> #define KVUALKAN_HEAP_TRUELY_ALLOC //#define KVUALKAN_HEAP_BRUTE_CHECK namespace KVulkanHeapAllocator { struct BlockInfo; struct PageInfo; struct MemoryHeap; static VkDevice DEVICE = nullptr; static VkPhysicalDevice PHYSICAL_DEVICE = nullptr; static uint32_t MEMORY_TYPE_COUNT = 0; static std::vector<VkDeviceSize> MIN_PAGE_SIZE; static std::vector<VkDeviceSize> HEAP_REMAIN_SIZE; static std::vector<MemoryHeap*> MEMORY_TYPE_TO_HEAP; static VkDeviceSize ALLOC_FACTOR = 1024; static VkDeviceSize MAX_ALLOC_COUNT = 0; static VkDeviceSize BLOCK_SIZE_FACTOR = 4; static std::mutex ALLOC_FREE_LOCK; enum MemoryAllocateType { MAT_DEFAULT, MAT_ACCELERATION_STRUCTURE, MAT_DEVICE_ADDRESS, MAT_COUNT }; struct MemoryAllocateTypeProperty { bool needDeviceAddress; }; static MemoryAllocateTypeProperty MEMORY_ALLOCATE_TYPE_PROPERITES[MAT_COUNT] = { // MAT_DEFAULT { false }, // MAT_ACCELERATION_STRUCTURE { true }, // MAT_DEVICE_ADDRESS { true }, }; struct BlockInfo { // 本block在page的偏移量 VkDeviceSize offset; // 本block大小 VkDeviceSize size; int isFree; BlockInfo* pNext; BlockInfo* pPre; // 额外信息 用于释放时索引 PageInfo* pParent; BlockInfo(PageInfo* _pParent) { assert(_pParent); isFree = true; offset = 0; size = 0; pNext = pPre = nullptr; pParent = _pParent; } }; struct MemoryHeap; struct PageInfo { VkDevice vkDevice; #ifdef KVUALKAN_HEAP_TRUELY_ALLOC VkDeviceMemory vkMemroy; #else void* vkMemroy; #endif VkDeviceSize size; MemoryAllocateType type; uint32_t memoryTypeIndex; uint32_t memoryHeapIndex; BlockInfo* pHead; PageInfo* pPre; PageInfo* pNext; // 额外信息 用于释放时索引 MemoryHeap* pParent; int noShare; PageInfo(MemoryHeap* _pParent, VkDevice _vkDevice, VkDeviceSize _size, MemoryAllocateType _type, uint32_t _memoryTypeIndex, uint32_t _memoryHeapIndex, int _noShare) { vkDevice = _vkDevice; size = _size; type = _type; memoryTypeIndex = _memoryTypeIndex; memoryHeapIndex = _memoryHeapIndex; vkMemroy = VK_NULL_HANDLE; pHead = nullptr; pPre = pNext = nullptr; pParent = _pParent; noShare = _noShare; } ~PageInfo() { assert(vkMemroy == VK_NULL_HANDLE); } void Check() { #ifdef KVUALKAN_HEAP_BRUTE_CHECK if(pHead) { VkDeviceSize sum = 0; for(BlockInfo* p = pHead; p; p = p->pNext) { sum += p->size; } assert(sum == size); } #endif } BlockInfo* Alloc(VkDeviceSize sizeToFit, VkDeviceSize alignment) { if(sizeToFit > size) { return nullptr; } if(vkMemroy == VK_NULL_HANDLE) { assert(pHead == nullptr); #ifdef KVUALKAN_HEAP_TRUELY_ALLOC { VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = size; allocInfo.pNext = nullptr; allocInfo.memoryTypeIndex = memoryTypeIndex; if (MEMORY_ALLOCATE_TYPE_PROPERITES[type].needDeviceAddress) { // If the buffer has VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT set we also need to enable the appropriate flag during allocation VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = {}; allocFlagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR; allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; allocInfo.pNext = &allocFlagsInfo; } VK_ASSERT_RESULT(vkAllocateMemory(DEVICE, &allocInfo, nullptr, &vkMemroy)); HEAP_REMAIN_SIZE[memoryHeapIndex] -= size; } #else { vkMemroy = malloc((size_t)size); } #endif pHead = KNEW BlockInfo(this); pHead->isFree = true; pHead->offset = 0; pHead->pPre = pHead->pNext = nullptr; pHead->size = size; pHead->pParent = this; // 把多余的空间分裂出来 Split(pHead, 0, sizeToFit); // 已被占用 pHead->isFree = false; Check(); return pHead; } else { assert(pHead); VkDeviceSize offset = 0; VkDeviceSize extraSize = 0; BlockInfo* pTemp = Find(sizeToFit, alignment, &offset, &extraSize); if(pTemp) { // 把多余的空间分裂出来 Split(pTemp, offset, sizeToFit); // 已被占用 pTemp->isFree = false; Check(); return pTemp; } Check(); return nullptr; } } void Free(BlockInfo* pBlock) { assert(pBlock->pParent == this); assert(!pBlock->isFree); assert(pHead); // 已被释放 pBlock->isFree = true; // 与前后的freeblock合并 Trim(pBlock); // 只剩下最后一个节点 释放内存 if(pHead->pNext == nullptr) { SAFE_DELETE(pHead); assert(vkMemroy != VK_NULL_HANDLE); #ifdef KVUALKAN_HEAP_TRUELY_ALLOC vkFreeMemory(vkDevice, vkMemroy, nullptr); HEAP_REMAIN_SIZE[memoryHeapIndex] += size; #else free(vkMemroy); #endif vkMemroy = VK_NULL_HANDLE; } } // 释放掉freeblock void Trim() { BlockInfo* pTemp = pHead; while(pTemp) { Trim(pTemp); pTemp = pTemp->pNext; } } void Clear() { if(vkMemroy) { #ifdef KVUALKAN_HEAP_TRUELY_ALLOC vkFreeMemory(vkDevice, vkMemroy, nullptr); HEAP_REMAIN_SIZE[memoryHeapIndex] += size; #else free(vkMemroy); #endif vkMemroy = VK_NULL_HANDLE; } for(BlockInfo* p = pHead; p != nullptr;) { BlockInfo* pNext = p->pNext; SAFE_DELETE(p); p = pNext; } pHead = nullptr; } BlockInfo* Find(VkDeviceSize sizeToFit, VkDeviceSize alignment, VkDeviceSize* pOffset, VkDeviceSize* pExtraSize) { BlockInfo* pTemp = pHead; while(pTemp) { if(pTemp->isFree && pTemp->size >= sizeToFit) { VkDeviceSize offset = (pTemp->offset % size) ? pTemp->offset + alignment - (pTemp->offset % alignment) : pTemp->offset; VkDeviceSize extraSize = offset - pTemp->offset + sizeToFit; assert(offset % alignment == 0); if(extraSize <= pTemp->size) { if(pOffset) { *pOffset = offset; } if(pExtraSize) { *pExtraSize = extraSize; } return pTemp; } } pTemp = pTemp->pNext; } return nullptr; } bool HasSpace(VkDeviceSize sizeToFit, VkDeviceSize alignment) { if(pHead) { return Find(sizeToFit, alignment, nullptr, nullptr) != nullptr; } else { return sizeToFit <= size; } } static void Split(BlockInfo* pBlock, VkDeviceSize offset, VkDeviceSize sizeToFit) { assert(pBlock->isFree && pBlock->size >= sizeToFit); if(pBlock->isFree && pBlock->size >= sizeToFit) { if(offset > 0) { BlockInfo* pPre = KNEW BlockInfo(pBlock->pParent); pPre->pPre = pBlock->pPre; if(pPre->pPre) pPre->pPre->pNext = pPre; pPre->pNext = pBlock; pBlock->pPre = pPre; if(pBlock == pBlock->pParent->pHead) { pBlock->pParent->pHead = pPre; } pPre->isFree = true; pPre->offset = pBlock->offset; pPre->size = offset - pBlock->offset; pBlock->offset += pPre->size; pBlock->size -= pPre->size; } VkDeviceSize remainSize = pBlock->size - sizeToFit; BlockInfo* pNext = pBlock->pNext; // 如果下一个block可以拿掉剩余空间 if(pNext && pNext->isFree) { pNext->offset -= remainSize; pNext->size += remainSize; } // 否则分裂多一个block来记录剩余空间 else if(remainSize > 0) { // 把剩余的空间分配到新节点上 BlockInfo* pNewBlock = KNEW BlockInfo(pBlock->pParent); pNewBlock->isFree = true; pNewBlock->size = remainSize; pNewBlock->offset = pBlock->offset + sizeToFit; pNewBlock->pNext = pNext; pNewBlock->pPre = pBlock; if(pNext) pNext->pPre = pNewBlock; pBlock->pNext = pNewBlock; } // 重新分配本block空间 pBlock->size = sizeToFit; } } static void Trim(BlockInfo* pBlock) { assert(pBlock->isFree); BlockInfo* pTemp = nullptr; if(pBlock->isFree) { // 与后面的freeblock合并 while(pBlock->pNext && pBlock->pNext->isFree) { pBlock->size += pBlock->pNext->size; pTemp = pBlock->pNext; pBlock->pNext = pTemp->pNext; if(pTemp->pNext) { pTemp->pNext->pPre = pBlock; } SAFE_DELETE(pTemp); } // 与前面的freeblock合并 while(pBlock->pPre && pBlock->pPre->isFree) { pBlock->size += pBlock->pPre->size; pBlock->offset = pBlock->pPre->offset; pTemp = pBlock->pPre; pBlock->pPre = pTemp->pPre; if(pTemp->pPre) { pTemp->pPre->pNext = pBlock; } SAFE_DELETE(pTemp); } // 成为头结点 if(pBlock->pPre == nullptr) { assert(pBlock->pParent); pBlock->pParent->pHead = pBlock; } } } }; struct MemoryHeap { VkDevice vkDevice; uint32_t memoryTypeIndex; uint32_t memoryHeapIndex; PageInfo* pHead[MAT_COUNT]; PageInfo* pNoShareHead[MAT_COUNT]; VkDeviceSize lastPageSize[MAT_COUNT]; VkDeviceSize totalPageSize[MAT_COUNT]; MemoryHeap(VkDevice _device, uint32_t _memoryTypeIndex, uint32_t _memoryHeapIndex) { vkDevice = _device; memoryTypeIndex = _memoryTypeIndex; memoryHeapIndex = _memoryHeapIndex; for (uint32_t i = 0; i < MAT_COUNT; ++i) { pHead[i] = nullptr; pNoShareHead[i] = nullptr; lastPageSize[i] = 0; totalPageSize[i] = 0; } } void Check() { #ifdef KVUALKAN_HEAP_BRUTE_CHECK for (uint32_t i = 0; i < MAT_COUNT; ++i) { if (pHead[i]) { VkDeviceSize sum = 0; for (PageInfo* p = pHead[i]; p; p = p->pNext) { p->Check(); sum += p->size; } assert(sum == totalPageSize[i]); } } #endif } void Clear() { PageInfo* pTemp = nullptr; for (uint32_t i = 0; i < MAT_COUNT; ++i) { lastPageSize[i] = totalPageSize[i] = 0; pTemp = pHead[i]; while (pTemp) { PageInfo* pNext = pTemp->pNext; pTemp->Clear(); SAFE_DELETE(pTemp); pTemp = pNext; } pTemp = pNoShareHead[i]; while (pTemp) { PageInfo* pNext = pTemp->pNext; pTemp->Clear(); SAFE_DELETE(pTemp); pTemp = pNext; } } } VkDeviceSize NewPageSize(MemoryAllocateType type) { VkDeviceSize newSize = lastPageSize[type] ? lastPageSize[type] << 1 : MIN_PAGE_SIZE[memoryHeapIndex]; newSize = std::max(MIN_PAGE_SIZE[memoryHeapIndex], newSize); return newSize; } VkDeviceSize FindPageFitSize(VkDeviceSize pageSize, VkDeviceSize sizeToFit) { VkDeviceSize newPageSize = KNumerical::Factor2GreaterEqual(sizeToFit); newPageSize = std::max(newPageSize, MIN_PAGE_SIZE[memoryHeapIndex]); newPageSize = std::min(newPageSize, pageSize); return newPageSize; } BlockInfo* Alloc(VkDeviceSize sizeToFit, VkDeviceSize alignment, bool noShared, MemoryAllocateType type) { std::lock_guard<decltype(ALLOC_FREE_LOCK)> guard(ALLOC_FREE_LOCK); if(noShared) { PageInfo* pPage = KNEW PageInfo(this, vkDevice, sizeToFit, type, memoryTypeIndex, memoryHeapIndex, true); BlockInfo* pBlock = pPage->Alloc(sizeToFit, alignment); pPage->pNext = pNoShareHead[type]; if(pNoShareHead[type]) { pNoShareHead[type]->pPre = pPage; } pNoShareHead[type] = pPage; assert(pBlock && !pBlock->isFree); return pBlock; } else { VkDeviceSize allocFactor = ALLOC_FACTOR; // 分配大小必须是allocFactor的整数倍 // 当每次分配都是allocFactor的整数倍时候 就能保证同一个page里的offset也是allocFactor的整数倍 // sizeToFit = ((sizeToFit + ALLOC_FACTOR - 1) / ALLOC_FACTOR) * ALLOC_FACTOR; // assert(sizeToFit % ALLOC_FACTOR == 0); alignment = KNumerical::LCM(alignment, ALLOC_FACTOR); PageInfo* pPage = Find(sizeToFit, alignment, type); if(!pPage) { // 当前所有page里找不到足够空间 分配一个新的插入到最后 保证heap总空间2倍递增 while (true) { pPage = Nail(type); VkDeviceSize newSize = NewPageSize(type); lastPageSize[type] = newSize; totalPageSize[type] += newSize; PageInfo* pNewPage = KNEW PageInfo(this, vkDevice, newSize, type, memoryTypeIndex, memoryHeapIndex, false); if(pPage) pPage->pNext = pNewPage; pNewPage->pPre = pPage; pNewPage->pNext = nullptr; // 头结点 if(pHead[type] == nullptr) { pHead[type] = pNewPage; } if(pNewPage->size >= sizeToFit) { pPage = pNewPage; break; } } } // 把多余的空间分裂出来 尽量节省实际分配的内存 if(pPage->vkMemroy == VK_NULL_HANDLE) { VkDeviceSize newPageSize = FindPageFitSize(pPage->size, sizeToFit); Split(pPage, newPageSize); } BlockInfo* pBlock = pPage->Alloc(sizeToFit, alignment); assert(pBlock && !pBlock->isFree); Check(); return pBlock; } } void Free(BlockInfo* pBlock) { std::lock_guard<decltype(ALLOC_FREE_LOCK)> guard(ALLOC_FREE_LOCK); assert(pBlock->pParent != nullptr); PageInfo* pPage = pBlock->pParent; assert(pPage->pParent == this); MemoryAllocateType type = pPage->type; // 特殊情况只能独占一个vkAllocateMemory特殊处理 这里连同page同时删除 if(pPage->noShare) { if(pPage == pNoShareHead[type]) { pNoShareHead[type] = pPage->pNext; } if(pPage->pPre) { pPage->pPre->pNext = pPage->pNext; } if(pPage->pNext) { pPage->pNext->pPre = pPage->pPre; } pPage->Clear(); SAFE_DELETE(pPage); Check(); } else { pPage->Free(pBlock); Check(); // 空间为空 尝试合并临近page if(pPage->vkMemroy == VK_NULL_HANDLE) { Trim(pPage); } Check(); } } PageInfo* Find(VkDeviceSize sizeToFit, VkDeviceSize alignment, MemoryAllocateType type) { PageInfo* pTemp = pHead[type]; while(pTemp) { if(pTemp->size >= sizeToFit) { if(pTemp->HasSpace(sizeToFit, alignment)) { return pTemp; } } pTemp = pTemp->pNext; } return nullptr; } PageInfo* Nail(MemoryAllocateType type) { PageInfo* pTemp = pHead[type]; while(pTemp && pTemp->pNext) { pTemp = pTemp->pNext; } return pTemp; } static void Trim(PageInfo* pPage) { assert(pPage->vkMemroy == VK_NULL_HANDLE); PageInfo* pTemp = nullptr; if(pPage->vkMemroy == VK_NULL_HANDLE) { // 与后面的freepage合并 while(pPage->pNext && pPage->pNext->vkMemroy == VK_NULL_HANDLE) { pPage->size += pPage->pNext->size; pTemp = pPage->pNext; pPage->pNext = pTemp->pNext; if(pTemp->pNext) { pTemp->pNext->pPre = pPage; } SAFE_DELETE(pTemp); pPage->Check(); } // 与前面的freepage合并 while(pPage->pPre && pPage->pPre->vkMemroy == VK_NULL_HANDLE) { pPage->size += pPage->pPre->size; pTemp = pPage->pPre; pPage->pPre = pTemp->pPre; if(pTemp->pPre) { pTemp->pPre->pNext = pPage; } SAFE_DELETE(pTemp); pPage->Check(); } // 成为头结点 if(pPage->pPre == nullptr) { assert(pPage->pParent); MemoryAllocateType type = pPage->type; pPage->pParent->pHead[type] = pPage; } } } static void Split(PageInfo* pPage, VkDeviceSize sizeToFit) { assert(pPage->vkMemroy == VK_NULL_HANDLE && pPage->size >= sizeToFit); if(pPage->vkMemroy == VK_NULL_HANDLE && pPage->size >= sizeToFit) { // page的新大小不是ALLOC_FACTOR的整数倍 无法分裂 if(sizeToFit % ALLOC_FACTOR != 0) { return; } VkDeviceSize remainSize = pPage->size - sizeToFit; PageInfo* pNext = pPage->pNext; // 如果下一个page可以拿掉剩余空间 if(pNext && pNext->vkMemroy == VK_NULL_HANDLE) { pNext->size += remainSize; } // 否则分裂多一个page来记录剩余空间 else if(remainSize > 0) { // 把剩余的空间分配到新节点上 PageInfo* pNewPage = KNEW PageInfo(pPage->pParent, pPage->vkDevice, remainSize, pPage->type, pPage->memoryTypeIndex, pPage->memoryHeapIndex, false); pNewPage->vkMemroy = VK_NULL_HANDLE; pNewPage->size = remainSize; pNewPage->pNext = pNext; pNewPage->pPre = pPage; if(pNext) pNext->pPre = pNewPage; pPage->pNext = pNewPage; } // 重新分配本page空间 pPage->size = sizeToFit; } } }; bool Init() { if(KVulkanGlobal::deviceReady) { DEVICE = KVulkanGlobal::device; PHYSICAL_DEVICE = KVulkanGlobal::physicalDevice; VkPhysicalDeviceProperties deviceProperties = {}; vkGetPhysicalDeviceProperties(PHYSICAL_DEVICE, &deviceProperties); MAX_ALLOC_COUNT = deviceProperties.limits.maxMemoryAllocationCount; /* Linear buffer 0xXX is aliased with non-linear image 0xXX which may indicate a bug. For further info refer to the Buffer-Image Granularity section of the Vulkan specification. > (https://www.khronos.org/registry/vulkan/specs/1.0-extensions/xhtml/vkspec.html#resources-bufferimagegranularity) */ // 由于这里image与buffer共享同一份VkDeviceMemory 因此每次分配占用的空间大小必须是该factor的整数倍 ALLOC_FACTOR = deviceProperties.limits.bufferImageGranularity; VkPhysicalDeviceMemoryProperties memoryProperties = {}; vkGetPhysicalDeviceMemoryProperties(PHYSICAL_DEVICE, &memoryProperties); MEMORY_TYPE_COUNT = memoryProperties.memoryTypeCount; MEMORY_TYPE_TO_HEAP.resize(memoryProperties.memoryTypeCount); for(uint32_t memTypeIdx = 0; memTypeIdx < memoryProperties.memoryTypeCount; ++memTypeIdx) { uint32_t memHeapIndex = memoryProperties.memoryTypes[memTypeIdx].heapIndex; MEMORY_TYPE_TO_HEAP[memTypeIdx] = KNEW MemoryHeap(KVulkanGlobal::device, memTypeIdx, memHeapIndex); } HEAP_REMAIN_SIZE.resize(memoryProperties.memoryHeapCount); MIN_PAGE_SIZE.resize(memoryProperties.memoryHeapCount); for(uint32_t memHeapIdx = 0; memHeapIdx < memoryProperties.memoryHeapCount; ++memHeapIdx) { HEAP_REMAIN_SIZE[memHeapIdx] = memoryProperties.memoryHeaps[memHeapIdx].size; MIN_PAGE_SIZE[memHeapIdx] = std::min ( HEAP_REMAIN_SIZE[memHeapIdx], BLOCK_SIZE_FACTOR * KNumerical::Pow2GreaterEqual(memoryProperties.memoryHeaps[memHeapIdx].size * memoryProperties.memoryHeapCount / MAX_ALLOC_COUNT) ); } return true; } else { #ifdef KVUALKAN_HEAP_TRUELY_ALLOC return false; #else MEMORY_TYPE_COUNT = 1; MEMORY_TYPE_TO_HEAP.resize(1); MEMORY_TYPE_TO_HEAP[0] = KNEW MemoryHeap(KVulkanGlobal::device, 0, 0); HEAP_REMAIN_SIZE.resize(1); HEAP_REMAIN_SIZE[0] = static_cast<VkDeviceSize>(512U * 1024U * 1024U); MIN_PAGE_SIZE.resize(1); MIN_PAGE_SIZE[0] = static_cast<VkDeviceSize>(1); MAX_PAGE_SIZE.resize(1); MAX_PAGE_SIZE[0] = static_cast<VkDeviceSize>(512U * 1024U * 1024U); return true; #endif } } bool UnInit() { for(uint32_t memoryTypeIndex = 0; memoryTypeIndex < MEMORY_TYPE_COUNT; ++memoryTypeIndex) { MemoryHeap* pHeap = MEMORY_TYPE_TO_HEAP[memoryTypeIndex]; if(pHeap) { pHeap->Clear(); SAFE_DELETE(pHeap); } } MEMORY_TYPE_COUNT = 0; MEMORY_TYPE_TO_HEAP.clear(); HEAP_REMAIN_SIZE.clear(); MIN_PAGE_SIZE.clear(); return true; } bool Alloc(VkDeviceSize size, VkDeviceSize alignment, uint32_t memoryTypeIndex, VkMemoryPropertyFlags memoryUsage, VkBufferUsageFlags bufferUsage, AllocInfo& info) { if(memoryTypeIndex < MEMORY_TYPE_COUNT) { MemoryHeap* pHeap = MEMORY_TYPE_TO_HEAP[memoryTypeIndex]; bool noShared = false; MemoryAllocateType type = MAT_DEFAULT; if (memoryUsage & ~VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { noShared = true; } if (bufferUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) { type = MAT_DEVICE_ADDRESS; } // 光追加速结构不能够与其他资源共享VkDeviceMemory 这是否是驱动的BUG if (bufferUsage & VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR) { type = MAT_ACCELERATION_STRUCTURE; } info.internalData = pHeap->Alloc(size, alignment, noShared, type); if(info.internalData) { BlockInfo* pBlock = (BlockInfo*)info.internalData; PageInfo* pPage = (PageInfo*)pBlock->pParent; info.vkMemroy = static_cast<VkDeviceMemory>(pPage->vkMemroy); info.vkOffset = pBlock->offset; return true; } } return false; } bool Free(const AllocInfo& data) { BlockInfo* pBlock = (BlockInfo*)data.internalData; if(pBlock) { MemoryHeap* pHeap = pBlock->pParent->pParent; pHeap->Free(pBlock); return true; } return false; } }
22.88242
164
0.659317
King19931229
a1217c84f390c7b4ccaca56a570e71deecf726ba
2,473
cpp
C++
Section11/Section11Challenge/Section11Challenge/main.cpp
tslothorst/Learning-Cpp
ad7fd6fdcf6678202cc376e910cbdae454fd9273
[ "MIT" ]
null
null
null
Section11/Section11Challenge/Section11Challenge/main.cpp
tslothorst/Learning-Cpp
ad7fd6fdcf6678202cc376e910cbdae454fd9273
[ "MIT" ]
null
null
null
Section11/Section11Challenge/Section11Challenge/main.cpp
tslothorst/Learning-Cpp
ad7fd6fdcf6678202cc376e910cbdae454fd9273
[ "MIT" ]
null
null
null
#include "main.h" #include<iostream> #include<vector> #include<algorithm> using namespace std; void print_menu(); void add_number(vector<int> &userNumbers); void display_list(const vector<int> &userNumbers); double get_avgnum(const vector<int> &userNumbers); int get_smallnum(const vector<int> &userNumbers); int get_largenum(const vector<int> &userNumbers); int main() { vector<int> userNumbers{}; while (true) { char choice{}; print_menu(); cin >> choice; if (tolower(choice) == 'q') { cout << "Goodbye\n"; break; } if (towlower(choice) == 'a') { add_number(userNumbers); } if (tolower(choice) == 'p') { display_list(userNumbers); } if (tolower(choice) == 'm') { cout << "Average of the elements in the list is: " << get_avgnum(userNumbers) << endl; } if (tolower(choice) == 's') { cout << "The smallest number in the list is: " << get_smallnum(userNumbers) << endl; } if (tolower(choice) == 'l') { cout << "The largest number in the list is: " << get_largenum(userNumbers) << endl; } } return 0; } void print_menu() { cout << "\nPlease make a choice from these options" << endl; cout << "P - Print numbers\nA - Add a number\nM - Display mean of the numbers\nS - Display the smallest number\nL - Display the largest number\nQ - Quit\n"; cout << "Input: "; } void add_number(vector<int> &userNumbers) { int userNum{}; cout << "Please enter an integer: "; cin >> userNum; userNumbers.push_back(userNum); cout << userNum << " added to list!" << endl; } void display_list(const vector<int> &userNumbers) { if (userNumbers.size() == 0) { cout << "[] - the list is empty" << endl; } for (size_t i = 0; i < userNumbers.size(); i++) { cout << userNumbers.at(i) << endl; } } double get_avgnum(const vector<int> &userNumbers) { double buffer{}; double avgNum{}; for (size_t i = 0; i < userNumbers.size(); i++) { buffer += userNumbers[i]; avgNum = buffer / userNumbers.size(); } return avgNum; } int get_smallnum(const vector<int> &userNumbers) { auto result = min_element(userNumbers.begin(), userNumbers.end()); int smallpos = distance(userNumbers.begin(), result); int smallnum = userNumbers.at(smallpos); return smallnum; } int get_largenum(const vector<int> &userNumbers) { auto result = max_element(userNumbers.begin(), userNumbers.end()); int largepos = distance(userNumbers.begin(), result); int largenum = userNumbers.at(largepos); return largenum; }
22.688073
157
0.66114
tslothorst
a1252b251aa55c962d5b153bba9de8d48411f622
726
cpp
C++
LeetCode/0036. Valid Sudoku/solution.cpp
InnoFang/oh-my-algorithms
f559dba371ce725a926725ad28d5e1c2facd0ab2
[ "Apache-2.0" ]
19
2018-08-26T03:10:58.000Z
2022-03-07T18:12:52.000Z
LeetCode/0036. Valid Sudoku/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
null
null
null
LeetCode/0036. Valid Sudoku/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
6
2020-03-16T23:00:06.000Z
2022-01-13T07:02:08.000Z
/** * 507 / 507 test cases passed. * Runtime: 20 ms * Memory Usage: 17.6 MB */ class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { bool row[10][10] = { false }; bool col[10][10] = { false }; bool blk[10][10] = { false }; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char c = board[i][j]; if ('.' == c) continue; int num = c - '0'; int blk_idx = i / 3 * 3 + j / 3; if (row[i][num] || col[j][num] || blk[blk_idx][num]) return false; row[i][num] = col[j][num] = blk[blk_idx][num] = true; } } return true; } };
29.04
82
0.415978
InnoFang
a12692f2069db6fd63b1d5df08529db6910bf3cf
11,998
cpp
C++
newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp
execomrt/newton-dynamics
b38363000bed09cf514cdad92013b0c0b4c48f3f
[ "Zlib" ]
null
null
null
newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp
execomrt/newton-dynamics
b38363000bed09cf514cdad92013b0c0b4c48f3f
[ "Zlib" ]
null
null
null
newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp
execomrt/newton-dynamics
b38363000bed09cf514cdad92013b0c0b4c48f3f
[ "Zlib" ]
null
null
null
/* Copyright (c) <2003-2021> <Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ // this vehicle UI class was implemented by Dave Gravel, // so sole some of the Open Gl errors with legacy glBegin/GlEnd // operation with deprecated since OpenGl 3.3 // Thank you very much Dave #include "ndSandboxStdafx.h" #include "ndVehicleUI.h" #include "ndDemoEntityManager.h" //ndDemoMesh* CreateDialMesh(ndDemoEntityManager* const scene, const char* const texName) //{ // ndMeshEffect mesh; // // dArray<ndMeshEffect::dMaterial>& materialArray = mesh.GetMaterials(); // ndMeshEffect::dMaterial material; // strcpy(material.m_textureName, texName); // materialArray.PushBack(material); // // dFloat32 gageSize = 100.0f; // mesh.BeginBuild(); // mesh.BeginBuildFace(); // mesh.AddPoint(-gageSize, gageSize, 0.0f); // mesh.AddUV0(0.0f, 1.0f); // mesh.AddMaterial(0); // // mesh.AddPoint(-gageSize, -gageSize, 0.0f); // mesh.AddUV0(0.0f, 0.0f); // mesh.AddMaterial(0); // // mesh.AddPoint(gageSize, -gageSize, 0.0f); // mesh.AddUV0(1.0f, 0.0f); // mesh.AddMaterial(0); // mesh.EndBuildFace(); // // mesh.BeginBuildFace(); // mesh.AddPoint(-gageSize, gageSize, 0.0f); // mesh.AddUV0(0.0f, 1.0f); // mesh.AddMaterial(0); // // mesh.AddPoint(gageSize, -gageSize, 0.0f); // mesh.AddUV0(1.0f, 0.0f); // mesh.AddMaterial(0); // // mesh.AddPoint(gageSize, gageSize, 0.0f); // mesh.AddUV0(1.0f, 1.0f); // mesh.AddMaterial(0); // mesh.EndBuildFace(); // // mesh.EndBuild(0.0f); // return new ndDemoMesh("dialMesh", &mesh, scene->GetShaderCache()); //} const GLchar* ndVehicleUI::m_vertexShader = "in vec3 Position;\n" "in vec2 UV;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "uniform mat4 ProjMtx;\n" "uniform mat4 ModMtx;\n" "uniform float ptsize;\n" "uniform vec4 color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = color;\n" " gl_Position = ProjMtx * ModMtx * vec4(Position.xy * ptsize,0.0,1.0);\n" "}\n" ; const GLchar* ndVehicleUI::m_fragmentShader = "uniform sampler2D UIText;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture(UIText, Frag_UV.st);\n" "}\n" ; const GLchar* ndVehicleUI::m_vertexShaderWithVersion[2] = { "#version 330 core\n", m_vertexShader }; const GLchar* ndVehicleUI::m_fragmentShaderWithVersion[2] = { "#version 330 core\n", m_fragmentShader }; ndVehicleUI::ndVehicleUI() :dClassAlloc() ,m_shaderHandle(0) ,m_vboDyn(0) ,m_vboSta(0) ,m_vaoDyn(0) ,m_vaoSta(0) ,m_iboDyn(0) ,m_iboSta(0) { }; ndVehicleUI::~ndVehicleUI() { if (m_shaderHandle) { glDeleteProgram(m_shaderHandle); } if (m_iboSta) { glDeleteBuffers(1, &m_iboSta); } if (m_vboSta) { glDeleteBuffers(1, &m_vboSta); } if (m_vaoSta) { glDeleteVertexArrays(1, &m_vaoSta); } if (m_iboDyn) { glDeleteBuffers(1, &m_iboDyn); } if (m_vboDyn) { glDeleteBuffers(1, &m_vboDyn); } if (m_vaoDyn) { glDeleteVertexArrays(1, &m_vaoDyn); } }; void ndVehicleUI::CreateOrthoViewMatrix(ndDemoEntityManager* const uscene, dFloat32 origin_x, const dFloat32 origin_y, dMatrix& projmatrix) { dFloat32 sizeX = (dFloat32)(1.0f * uscene->GetWidth()); dFloat32 sizeY = (dFloat32)(1.0f * uscene->GetHeight()); dFloat32 L = origin_x; dFloat32 R = origin_x + sizeX; dFloat32 T = origin_y; dFloat32 B = origin_y + sizeY; projmatrix = dMatrix({ 2.0f / (R - L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / (T - B), 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { (R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f }); } void ndVehicleUI::CreateBufferUI() { if (!m_vaoDyn) { m_shaderHandle = glCreateProgram(); GLuint m_vertHandle = glCreateShader(GL_VERTEX_SHADER); GLuint m_fragHandle = glCreateShader(GL_FRAGMENT_SHADER); GLint Result = GL_FALSE; dInt32 InfoLogLength = 0; glShaderSource(m_vertHandle, 2, m_vertexShaderWithVersion, NULL); glCompileShader(m_vertHandle); // Check Vertex Shader glGetShaderiv(m_vertHandle, GL_COMPILE_STATUS, &Result); glGetShaderiv(m_vertHandle, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { printf("Vertex shader error! \n"); // std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); // glGetShaderInfoLog(g_VertHandle3D, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); // printf("Vertex %s\n", &VertexShaderErrorMessage[0]); } glShaderSource(m_fragHandle, 2, m_fragmentShaderWithVersion, NULL); glCompileShader(m_fragHandle); // Check Fragment Shader glGetShaderiv(m_fragHandle, GL_COMPILE_STATUS, &Result); glGetShaderiv(m_fragHandle, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { printf("Fragment shader error! \n"); // std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1); // glGetShaderInfoLog(g_FragHandle3D, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); // printf("Fragment %s\n", &FragmentShaderErrorMessage[0]); } glAttachShader(m_shaderHandle, m_vertHandle); glAttachShader(m_shaderHandle, m_fragHandle); glLinkProgram(m_shaderHandle); glDetachShader(m_shaderHandle, m_vertHandle); glDetachShader(m_shaderHandle, m_fragHandle); glDeleteShader(m_vertHandle); glDeleteShader(m_fragHandle); m_vertDyn[0].m_posit.m_x = -1.0f; m_vertDyn[0].m_posit.m_y = -1.0f; m_vertDyn[0].m_posit.m_z = 0.0f; m_vertDyn[0].m_uv.m_u = 0.0f; m_vertDyn[0].m_uv.m_v = 0.0f; // m_vertDyn[1].m_posit.m_x = -1.0f; m_vertDyn[1].m_posit.m_y = 1.0f; m_vertDyn[1].m_posit.m_z = 0.0f; m_vertDyn[1].m_uv.m_u = 0.0f; m_vertDyn[1].m_uv.m_v = 1.0f; m_vertDyn[2].m_posit.m_x = 1.0f; m_vertDyn[2].m_posit.m_y = 1.0f; m_vertDyn[2].m_posit.m_z = 0.0f; m_vertDyn[2].m_uv.m_u = -1.0f; m_vertDyn[2].m_uv.m_v = 1.0f; m_vertDyn[3].m_posit.m_x = 1.0f; m_vertDyn[3].m_posit.m_y = -1.0f; m_vertDyn[3].m_posit.m_z = 0.0f; m_vertDyn[3].m_uv.m_u = -1.0f; m_vertDyn[3].m_uv.m_v = 0.0f; m_indxDyn[0] = 0; m_indxDyn[1] = 1; m_indxDyn[2] = 2; m_indxDyn[3] = 2; m_indxDyn[4] = 3; m_indxDyn[5] = 0; glGenVertexArrays(1, &m_vaoDyn); glBindVertexArray(m_vaoDyn); glGenBuffers(1, &m_vboDyn); glBindBuffer(GL_ARRAY_BUFFER, m_vboDyn); glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertDyn), &m_vertDyn[0], GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)(offsetof(glPositionUV, m_uv))); glGenBuffers(1, &m_iboDyn); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboDyn); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_indxDyn), &m_indxDyn[0], GL_STATIC_DRAW); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); // Don't unbind this buffer, Let's it in opengl memory. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // remove this buffer from memory because it is updated in runtime. // you need to bind this buffer at any render pass. glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Gear dynamic buffer memcpy(m_vertSta, m_vertDyn, sizeof(m_vertDyn)); memcpy(m_indxSta, m_indxDyn, sizeof(m_indxDyn)); // // glGenVertexArrays(1, &m_vaoSta); glBindVertexArray(m_vaoSta); // glGenBuffers(1, &m_vboSta); glBindBuffer(GL_ARRAY_BUFFER, m_vboSta); glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertSta), &m_vertSta[0], GL_STATIC_DRAW); // glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)0); // glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)(offsetof(glPositionUV, m_uv))); glGenBuffers(1, &m_iboSta); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboSta); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_indxSta), &m_indxSta[0], GL_STATIC_DRAW); // glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); // // Static buffer, Let's it in opengl memory. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //glBindBuffer(GL_ARRAY_BUFFER, 0); // glBindVertexArray(0); } }; void ndVehicleUI::RenderGageUI(ndDemoEntityManager* const uscene, const GLuint tex1, const dFloat32 origin_x, const dFloat32 origin_y, const dFloat32 ptsize, dFloat32 cparam, dFloat32 minAngle, dFloat32 maxAngle) { if (m_vaoSta) { dMatrix aprojm(dGetIdentityMatrix()); CreateOrthoViewMatrix(uscene, origin_x, origin_y, aprojm); // minAngle *= -dDegreeToRad; maxAngle *= -dDegreeToRad; // dFloat32 angle = minAngle + (maxAngle - minAngle) * cparam; dMatrix modm(dRollMatrix(-angle)); dVector color(1.0f, 1.0f, 1.0f, 1.0f); glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ProjMtx"), 1, GL_FALSE, &aprojm[0][0]); glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ModMtx"), 1, GL_FALSE, &modm[0][0]); glUniform1f(glGetUniformLocation(m_shaderHandle, "ptsize"), ptsize); glUniform4fv(glGetUniformLocation(m_shaderHandle, "color"), 1, &color[0]); glBindVertexArray(m_vaoSta); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); // This buffer is already in the opengl memory. // Don't need to bind it again. //glBindBuffer(GL_ARRAY_BUFFER, m_vboSta); if (tex1) { glBindTexture(GL_TEXTURE_2D, tex1); } // This buffer is already in the memory. // Don't need to bind it again. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboSta); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); // Don't unbind this buffers from the opengl memory. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } }; void ndVehicleUI::RenderGearUI(ndDemoEntityManager* const uscene, const dInt32 gearid, GLuint tex1, dFloat32 origin_x, dFloat32 origin_y, dFloat32 ptsize) { if (m_vaoDyn) { dMatrix aprojm(dGetIdentityMatrix()); CreateOrthoViewMatrix(uscene, origin_x, origin_y, aprojm); dMatrix origin(dGetIdentityMatrix()); origin[1][1] = -1.0f; origin.m_posit = dVector(origin_x + ptsize * 1.9f, 50.0f, 0.0f, 1.0f); dFloat32 uwith = 0.1f; dFloat32 u0 = uwith * gearid; dFloat32 u1 = u0 + uwith; dFloat32 xy1 = 10.0f; dVector color; if (gearid == 0) { color = dVector(1.0f, 0.5f, 0.0f, 1.0f); } else if (gearid == 1) { color = dVector(1.0f, 1.0f, 0.0f, 1.0f); } else { color = dVector(0.0f, 1.0f, 0.0f, 1.0f); } glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ProjMtx"), 1, GL_FALSE, &aprojm[0][0]); glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ModMtx"), 1, GL_FALSE, &origin[0][0]); glUniform1f(glGetUniformLocation(m_shaderHandle, "ptsize"), xy1); glUniform4fv(glGetUniformLocation(m_shaderHandle, "color"), 1, &color[0]); glBindVertexArray(m_vaoDyn); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); // glBindBuffer(GL_ARRAY_BUFFER, m_vboDyn); m_vertDyn[0].m_uv.m_u = u0; m_vertDyn[1].m_uv.m_u = u0; m_vertDyn[2].m_uv.m_u = u1; m_vertDyn[3].m_uv.m_u = u1; // Bind and update the dynamic buffer uv data glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(m_vertDyn), &m_vertDyn[0]); if (tex1) { glBindTexture(GL_TEXTURE_2D, tex1); } // This buffer is static, Don't need to bind it again. // The buffer is already bind in the opengl memory. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboDyn); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); // Don't unbind this buffer to let's it in opengl memory. //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } };
28.364066
212
0.710202
execomrt
a1288a15b926eea092a4e59aaa532cb9750c1713
5,178
cpp
C++
src/CoreGenPortal/PortalUserPrefWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2019-06-25T13:06:14.000Z
2019-06-25T13:06:14.000Z
src/CoreGenPortal/PortalUserPrefWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
128
2018-10-23T12:45:15.000Z
2021-12-28T13:09:39.000Z
src/CoreGenPortal/PortalUserPrefWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2021-01-20T23:17:34.000Z
2021-01-20T23:17:34.000Z
// // _PORTALUSERPREFWIN_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // #include "PortalUserPrefWin.h" // Event Table wxBEGIN_EVENT_TABLE(PortalUserPrefWin, wxDialog) EVT_BUTTON(wxID_OK, PortalUserPrefWin::OnPressOk) EVT_BUTTON(wxID_CANCEL, PortalUserPrefWin::OnPressCancel) wxEND_EVENT_TABLE() PortalUserPrefWin::PortalUserPrefWin( wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style, CoreUserConfig *U): wxDialog( parent, id, title, pos, size, style ), User(U) { // init the internals this->SetSizeHints( wxDefaultSize, wxDefaultSize ); // create the box sizers wxBoxSizer *bSizer1 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer *bSizer2 = new wxBoxSizer( wxVERTICAL ); m_panel1 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); bSizer2->Add( m_panel1, 1, wxEXPAND | wxALL, 5 ); // init all the options // -- project directory static text ProjectDirText = new wxStaticText( this, wxID_ANY, wxT("Default project directory"), wxDefaultPosition, wxDefaultSize, 0 ); ProjectDirText->Wrap(-1); bSizer2->Add( ProjectDirText, 0, wxALIGN_CENTER|wxALL, 5 ); // -- project directory input box ProjectDirCtrl = new wxTextCtrl( this, wxID_ANY, User->wxGetProjectDir(), wxDefaultPosition, wxSize(400,25), 0, wxDefaultValidator, wxT("ProjectDirectory") ); bSizer2->Add( ProjectDirCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); // -- archive directory static text ArchiveDirText = new wxStaticText( this, wxID_ANY, wxT("Default archive directory"), wxDefaultPosition, wxDefaultSize, 0 ); ArchiveDirText->Wrap(-1); bSizer2->Add( ArchiveDirText, 0, wxALIGN_CENTER|wxALL, 5 ); // -- archive directory input box ArchiveDirCtrl = new wxTextCtrl( this, wxID_ANY, User->wxGetArchiveDir(), wxDefaultPosition, wxSize(400,25), 0, wxDefaultValidator, wxT("Archive Directory") ); bSizer2->Add( ArchiveDirCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); // add the static line FinalStaticLine = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); bSizer2->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 ); bSizer1->Add( bSizer2, 1, wxEXPAND, 5 ); // setup all the buttons wxBoxSizer *bSizer3 = new wxBoxSizer( wxVERTICAL ); m_userbuttonsizer = new wxStdDialogButtonSizer(); m_userOK = new wxButton( this, wxID_OK ); m_userbuttonsizer->AddButton( m_userOK ); m_userCancel = new wxButton( this, wxID_CANCEL ); m_userbuttonsizer->AddButton( m_userCancel ); m_userbuttonsizer->Realize(); bSizer3->Add( m_userbuttonsizer, 1, wxEXPAND, 5 ); bSizer1->Add( bSizer3, 1, wxEXPAND, 5 ); // draw the diag box until we get more info this->SetSizer( bSizer1 ); this->Layout(); bSizer1->Fit(this); this->Centre( wxBOTH ); } void PortalUserPrefWin::OnPressOk( wxCommandEvent& ok ){ // user pressed 'ok', walk through all the options and update // the configuration User->SetProjectDir(ProjectDirCtrl->GetValue()); User->SetArchiveDir(ArchiveDirCtrl->GetValue()); User->WriteConfig(); this->EndModal( wxID_OK ); } void PortalUserPrefWin::OnPressCancel( wxCommandEvent& ok ){ // cancel everything and close the window this->EndModal(wxID_CANCEL); } PortalUserPrefWin::~PortalUserPrefWin(){ } // EOF
36.723404
79
0.486288
opensocsysarch
a128e7fe9b346a83fd79072dd2db2f935fa76914
4,153
hpp
C++
query_optimizer/expressions/SubqueryExpression.hpp
yuanchenl/quickstep
cc20fed6e56b0e583ae15a0219c070c8bacf14ba
[ "Apache-2.0" ]
1
2021-08-22T19:16:59.000Z
2021-08-22T19:16:59.000Z
query_optimizer/expressions/SubqueryExpression.hpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
null
null
null
query_optimizer/expressions/SubqueryExpression.hpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
1
2021-11-30T13:50:59.000Z
2021-11-30T13:50:59.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_ #define QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "query_optimizer/expressions/AttributeReference.hpp" #include "query_optimizer/expressions/ExprId.hpp" #include "query_optimizer/expressions/Expression.hpp" #include "query_optimizer/expressions/ExpressionType.hpp" #include "query_optimizer/expressions/Scalar.hpp" #include "query_optimizer/logical/Logical.hpp" #include "query_optimizer/OptimizerTree.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { class CatalogAttribute; class Scalar; class Type; namespace optimizer { namespace expressions { /** \addtogroup OptimizerExpressions * @{ */ class SubqueryExpression; typedef std::shared_ptr<const SubqueryExpression> SubqueryExpressionPtr; /** * @brief A subquery used in an expression. */ class SubqueryExpression : public Scalar { public: ExpressionType getExpressionType() const override { return ExpressionType::kSubqueryExpression; } std::string getName() const override { return "SubqueryExpression"; } const Type& getValueType() const override { return output_attribute_->getValueType(); } bool isConstant() const override { return output_attribute_->isConstant(); } /** * @return The referenced logical subquery node. */ const logical::LogicalPtr& subquery() const { return subquery_; } std::vector<AttributeReferencePtr> getReferencedAttributes() const override; ExpressionPtr copyWithNewChildren( const std::vector<ExpressionPtr> &new_children) const override { DCHECK(new_children.empty()); return Create(subquery_); } ::quickstep::Scalar* concretize( const std::unordered_map<ExprId, const CatalogAttribute*> &substitution_map) const override; /** * @brief Creates a subquery expression. * @note This expression can only be used in a logical plan. * * @param subquery The logical subquery node. * @return An immutable SubqueryExpression. */ static SubqueryExpressionPtr Create(const logical::LogicalPtr &subquery) { return SubqueryExpressionPtr(new SubqueryExpression(subquery)); } protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<OptimizerTreeBaseNodePtr> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<OptimizerTreeBaseNodePtr>> *container_child_fields) const override; private: explicit SubqueryExpression(const logical::LogicalPtr &subquery) : subquery_(subquery), output_attribute_(subquery->getOutputAttributes()[0]) { DCHECK(!subquery->getOutputAttributes().empty()); } logical::LogicalPtr subquery_; // Set to the first output attribute if the subquery is a multi-column table query. const AttributeReferencePtr output_attribute_; DISALLOW_COPY_AND_ASSIGN(SubqueryExpression); }; /** @} */ } // namespace expressions } // namespace optimizer } // namespace quickstep #endif /* QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_ */
31.225564
98
0.75921
yuanchenl
a12b8188fb1a107d82a09bb3331f62b662b228e8
16,474
cpp
C++
src/circuits/BooleanCircuits.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
src/circuits/BooleanCircuits.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
src/circuits/BooleanCircuits.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
/** * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI) * This file is part of the SCAPI project. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * 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. * * We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to * http://crypto.biu.ac.il/SCAPI. * * Libscapi uses several open source libraries. Please see these projects for any further licensing issues. * For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD * * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * */ #include "../../include/circuits/BooleanCircuits.hpp" /****************************************************/ /* Gate */ /****************************************************/ void Gate::compute(map<int, Wire> & computedWires) { // we call the calculateIndexOfTruthTable method to tell us the position of the output value in the truth table // and look up the value at that position. bool bVal = truthTable.at(calculateIndexOfTruthTable(computedWires)); byte outputValue = (byte)(bVal ? 1 : 0); int numberOfOutputs = outputWireIndices.size(); // assigns output value to each of this gate's output Wires. for (int i = 0; i < numberOfOutputs; i++) computedWires[outputWireIndices[i]] = Wire(outputValue); } bool Gate::operator==(const Gate &other) const { // first we verify that the gates' numbers are the same. if (gateNumber_ != other.gateNumber_) return false; // next we verify that the gates' respective truth tables are the same. if (truthTable != other.truthTable) return false; // next we verify that the number of input and output wires to the two respective gates are equal. if ((inputWireIndices.size() != other.inputWireIndices.size()) || (outputWireIndices.size() != other.outputWireIndices.size())) return false; /* * Having determined that the number of input Wire's are the same, we now check that corresponding input wires * have the same index. As we demonstrated above (in the comments on the imputWireIndices field), the order of the * wires is significant as not all functions are symmetric. So not only do we care that Wire have the same indices, * but we also care that the wires with the same index are in the same position of the inputWireIndices array. */ int numberOfInputs = inputWireIndices.size(); for (int i = 0; i < numberOfInputs; i++) if (inputWireIndices[i] != other.inputWireIndices[i]) return false; /* * Having determined that the number of output Wire's are the same, we now check that corresponding output wires have * the same index. */ int numberOfOutputs = outputWireIndices.size(); for (int i = 0; i < numberOfOutputs; i++) if (outputWireIndices[i] != other.outputWireIndices[i]) return false; // If we've reached this point, then the Gate's are equal so we return true. return true; } int Gate::calculateIndexOfTruthTable(map<int, Wire> computedWires) const { /* * Since a truth tables order is the order of binary counting, the index of a desired row can be calculated as follows: * For a truth table with L inputs whose input columns are labeled aL...ai...a2,a1, * the output index for a given input set is given by: summation from 0 to L : ai *2^i. * This is calculated below: */ int truthTableIndex = 0; int numberOfInputs = inputWireIndices.size(); for (int i = numberOfInputs - 1, j = 0; j < numberOfInputs; i--, j++) truthTableIndex += (int) computedWires[inputWireIndices[i]].getValue() * pow(2, j); return truthTableIndex; } /****************************************************/ /* BooleanCircuit */ /****************************************************/ BooleanCircuit::BooleanCircuit(scannerpp::Scanner s) { //Read the number of gates. int numberOfGates = atoi(read(s).c_str()); gates.resize(numberOfGates); //Read the number of parties. numberOfParties = atoi(read(s).c_str()); isInputSet.resize(numberOfParties); //For each party, read the party's number, number of input wires and their indices. for (int i = 0; i < numberOfParties; i++) { if (atoi(read(s).c_str()) != i + 1) {//add 1 since parties are indexed from 1, not 0 throw runtime_error("Circuit file format is wrong"); } //Read the number of input wires. int numberOfInputsForCurrentParty = atoi(read(s).c_str()); if (numberOfInputsForCurrentParty < 0) { throw runtime_error("Circuit file format is wrong"); } bool isThisPartyInputSet = numberOfInputsForCurrentParty == 0 ? true : false; isInputSet[i] = isThisPartyInputSet; vector<int> currentPartyInput(numberOfInputsForCurrentParty); //Read the input wires indices. for (int j = 0; j < numberOfInputsForCurrentParty; j++) { currentPartyInput[j] = atoi(read(s).c_str()); } eachPartysInputWires.push_back(currentPartyInput); } /* * The ouputWireIndices are the outputs from this circuit. However, this circuit may actually be a single layer of a * larger layered circuit. So this output can be part of the input to another layer of the circuit. */ if (numberOfParties == 2){ int numberOfCircuitOutputs = atoi(read(s).c_str()); vector<int> currentPartyOutput(numberOfCircuitOutputs); //Read the input wires indices. for (int j = 0; j < numberOfCircuitOutputs; j++) { currentPartyOutput[j] = atoi(read(s).c_str()); } eachPartysOutputWires.push_back(currentPartyOutput); } else { //For each party, read the party's number, number of output wires and their indices. for (int i = 0; i < numberOfParties; i++) { if (atoi(read(s).c_str()) != i + 1) {//add 1 since parties are indexed from 1, not 0 throw runtime_error("Circuit file format is wrong"); } //Read the number of input wires. int numberOfOutputForCurrentParty = atoi(read(s).c_str()); if (numberOfOutputForCurrentParty < 0) { throw runtime_error("Circuit file format is wrong"); } vector<int> currentPartyOutput(numberOfOutputForCurrentParty); //Read the input wires indices. for (int j = 0; j < numberOfOutputForCurrentParty; j++) { currentPartyOutput[j] = atoi(read(s).c_str()); } eachPartysOutputWires.push_back(currentPartyOutput); } } int numberOfGateInputs, numberOfGateOutputs; //For each gate, read the number of input and output wires, their indices and the truth table. for (int i = 0; i < numberOfGates; i++) { numberOfGateInputs = atoi(read(s).c_str()); numberOfGateOutputs = atoi(read(s).c_str()); vector<int> inputWireIndices(numberOfGateInputs); vector<int> outputWireIndices(numberOfGateOutputs); for (int j = 0; j < numberOfGateInputs; j++) { inputWireIndices[j] = atoi(read(s).c_str()); } for (int j = 0; j < numberOfGateOutputs; j++) { outputWireIndices[j] = atoi(read(s).c_str()); } /* * We create a BitSet representation of the truth table from the 01 String * that we read from the file. */ vector<bool> truthTable; string tTable = read(s); for (size_t j = 0; j < tTable.length(); j++) { if (tTable.at(j) == '1') truthTable.push_back(true); else truthTable.push_back(false); } //Construct the gate. gates[i] = Gate(i, truthTable, inputWireIndices, outputWireIndices); } } void BooleanCircuit::setInputs(const map<int, Wire> & presetInputWires, int partyNumber) { if (partyNumber < 1 || partyNumber > numberOfParties) throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber)); if (!isInputSet[partyNumber - 1]) { computedWires.insert(presetInputWires.begin(), presetInputWires.end()); } else { int numberOfInputWires = getNumberOfInputs(partyNumber); auto inputIndices = getInputWireIndices(partyNumber); for (int i = 0; i < numberOfInputWires; i++) { computedWires[inputIndices[i]] = presetInputWires.at(inputIndices[i]).getValue(); } } isInputSet[partyNumber - 1] = true; } void BooleanCircuit::setInputs(scannerpp::File * inputWiresFile, int partyNumber) { if (partyNumber < 1 || partyNumber > numberOfParties) throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber)); scannerpp::Scanner s(inputWiresFile); int numberOfInputWires = getNumberOfInputs(partyNumber); auto inputIndices = getInputWireIndices(partyNumber); map<int, Wire> presetInputWires; for (int i = 0; i < numberOfInputWires; i++) { presetInputWires[inputIndices[i]] = Wire(stoi(read(s))); } setInputs(presetInputWires, partyNumber); } map<int, Wire> BooleanCircuit::compute() { for (int i = 0; i < numberOfParties; i++) if (!isInputSet[i]) throw NotAllInputsSetException("not all inputs set"); /* Computes each Gate. * Since the Gates are provided in topological order, by the time the compute function on a given Gate is called, * its input Wires will have already been assigned values */ for (Gate g : getGates()) g.compute(computedWires); /* * The computedWires array contains all the computed wire values, even those that it is no longer necessary to retain. * So, we create a new Map called outputMap which only stores the Wires that are output Wires to the circuit. * We return outputMap. */ map<int, Wire> outputMap; for (int i=0; i<numberOfParties; i++) { auto outputWireIndices = eachPartysOutputWires[i]; for (int w : outputWireIndices) outputMap[w] = computedWires[w]; } return outputMap; } bool BooleanCircuit::operator==(const BooleanCircuit &other) const { // first tests to see that the number of Gates is the same for each circuit. If it's not, then the two are not equal. if (getGates().size() != other.getGates().size()) { return false; } // calls the equals method of the Gate class to compare each corresponding Gate. // if any of them return false, the circuits are not the same. for (size_t i = 0; i < getGates().size(); i++) if ( getGates()[i]!= other.getGates()[i] ) return false; return true; } vector<int> BooleanCircuit::getInputWireIndices(int partyNumber) const { if (partyNumber < 1 || partyNumber > numberOfParties) throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber)); // we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0 return eachPartysInputWires[partyNumber - 1]; } vector<int> BooleanCircuit::getOutputWireIndices(int partyNumber) const { if (partyNumber < 1 || partyNumber > numberOfParties) throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber)); // we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0 return eachPartysOutputWires[partyNumber - 1]; } vector<int> BooleanCircuit::getOutputWireIndices() const { if (numberOfParties != 2){ throw IllegalStateException("This function should be called in case of two party only"); } // we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0 return eachPartysOutputWires[0]; } int BooleanCircuit::getNumberOfInputs(int partyNumber) const { if (partyNumber < 1 || partyNumber > numberOfParties) throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber)); // we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0 return (int) eachPartysInputWires[partyNumber - 1].size(); } string BooleanCircuit::read(scannerpp::Scanner s) { string token = s.next(); while (boost::starts_with(token, "#")) { s.nextLine(); token = s.next(); } return token; } void BooleanCircuit::write(string outputFileName){ ofstream outputFile; outputFile.open(outputFileName); if (outputFile.is_open()) { //write the number of gates. int numberOfGates = gates.size(); outputFile << numberOfGates << endl; //write the number of parties. outputFile << numberOfParties << endl; outputFile << endl; //For each party, read the party's number, number of input wires and their indices. for (int i = 0; i < numberOfParties; i++) { outputFile << i+1 << " ";//add 1 since parties are indexed from 1, not 0 int numberOfInputsForCurrentParty = eachPartysInputWires[i].size(); //Read the number of input wires. outputFile << numberOfInputsForCurrentParty << endl; //Read the input wires indices. for (int j = 0; j < numberOfInputsForCurrentParty; j++) { outputFile << eachPartysInputWires[i][j] << endl; } outputFile << endl; } //Write the outputs number if (numberOfParties == 2) { int numberOfOutputs = eachPartysOutputWires[0].size(); outputFile << numberOfOutputs << endl; //Write the output wires indices. for (int i = 0; i < numberOfOutputs; i++) { outputFile << eachPartysOutputWires[0][i] << endl; } } else { //For each party, read the party's number, number of input wires and their indices. for (int i = 0; i < numberOfParties; i++) { outputFile << i+1 << " ";//add 1 since parties are indexed from 1, not 0 int numberOfOutputForCurrentParty = eachPartysOutputWires[i].size(); //Read the number of input wires. outputFile << numberOfOutputForCurrentParty << endl; //Read the input wires indices. for (int j = 0; j < numberOfOutputForCurrentParty; j++) { outputFile << eachPartysOutputWires[i][j] << endl; } outputFile << endl; } } outputFile << endl; //For each gate, write the number of input and output wires, their indices and the truth table. int numberOfGateInputs, numberOfGateOutputs; for (int i = 0; i < numberOfGates; i++) { numberOfGateInputs = gates[i].getInputWireIndices().size(); numberOfGateOutputs = gates[i].getOutputWireIndices().size(); outputFile << numberOfGateInputs << " "; outputFile << numberOfGateOutputs << " "; for (int j = 0; j < numberOfGateInputs; j++) { outputFile << gates[i].getInputWireIndices()[j] << " "; } for (int j = 0; j < numberOfGateOutputs; j++) { outputFile << gates[i].getOutputWireIndices()[j] << " "; } /* * We create a BitSet representation of the truth table from the 01 String * that we read from the file. */ auto tTable = gates[i].getTruthTable(); for (size_t j = 0; j < tTable.size(); j++) { if (tTable[j]) outputFile << "1"; else outputFile <<"0"; } outputFile << endl; } } outputFile.close(); }
41.60101
158
0.657824
cryptobiu
a12e1de881cb1f29545e43285b1fdb13eb451d73
2,642
cpp
C++
src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
6
2018-12-30T15:09:26.000Z
2020-04-20T09:27:59.000Z
src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
null
null
null
src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
2
2019-11-12T08:07:16.000Z
2019-11-29T11:19:47.000Z
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software (contact@borasoftware.com) // // 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 <TestResources.hpp> #include <Balau/Type/OnScopeExit.hpp> #include <Balau/Util/Files.hpp> namespace Balau { using Testing::is; namespace Resource { struct FileUtf32To8WriteResourceTest : public Testing::TestGroup<FileUtf32To8WriteResourceTest> { explicit FileUtf32To8WriteResourceTest() { RegisterTestCase(test); } static File prepWritePath(const std::string & testName, const std::string & text) { const std::string filename = std::string("FileUtf32To8WriteResourceTest-") + testName + ".log"; File file = TestResources::TestResultsFolder / "Resource" / filename; const std::string fileUriStr = file.toUriString(); file.getParentDirectory().createDirectories(); AssertThat(file.getParentDirectory().exists(), is(true)); file.removeFile(); AssertThat(file.exists(), is(false)); return file; } void test() { const std::string expected = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; File fileA = prepWritePath("test_a", expected); File fileB = prepWritePath("test_b", expected); OnScopeExit removeFileA([=] () mutable { fileA.removeFile(); }); OnScopeExit removeFileB([=] () mutable { fileB.removeFile(); }); auto fileWriteResource = fileA.getUtf32To8WriteResource(); auto uriWriteResource = fileB.utf32To8WriteResource(); std::u32ostream & fileWriteStream = fileWriteResource.writeStream(); std::u32ostream & uriWriteStream = uriWriteResource->writeStream(); fileWriteStream << toString32(expected); uriWriteStream << toString32(expected); fileWriteStream.flush(); uriWriteStream.flush(); fileWriteResource.close(); uriWriteResource->close(); const std::string actualA = Util::Files::readToString(fileA); const std::string actualB = Util::Files::readToString(fileA); AssertThat(actualA, is(expected)); AssertThat(actualB, is(expected)); } }; } // namespace Resource } // namespace Balau
31.082353
97
0.735428
borasoftware
a132a9281ce212aa497879d7c91326a33d50b0aa
11,305
hh
C++
Networking/BLIP/LoopbackProvider.hh
tophatch/couchbase-lite-core
f457d9bc74af276516d868b61a48b81b5d717e5c
[ "Apache-2.0" ]
null
null
null
Networking/BLIP/LoopbackProvider.hh
tophatch/couchbase-lite-core
f457d9bc74af276516d868b61a48b81b5d717e5c
[ "Apache-2.0" ]
null
null
null
Networking/BLIP/LoopbackProvider.hh
tophatch/couchbase-lite-core
f457d9bc74af276516d868b61a48b81b5d717e5c
[ "Apache-2.0" ]
null
null
null
// // LoopbackProvider.hh // // Copyright 2017-Present Couchbase, Inc. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL-Couchbase.txt. As of the Change Date specified // in that file, in accordance with the Business Source License, use of this // software will be governed by the Apache License, Version 2.0, included in // the file licenses/APL2.txt. // #pragma once #include "WebSocketInterface.hh" #include "Headers.hh" #include "Actor.hh" #include "Error.hh" #include "Logging.hh" #include "NumConversion.hh" #include <algorithm> #include <atomic> #include <chrono> #include <iomanip> #include <memory> #include <sstream> #include <cinttypes> namespace litecore { namespace websocket { class LoopbackProvider; static constexpr size_t kSendBufferSize = 256 * 1024; /** A WebSocket connection that relays messages to another instance of LoopbackWebSocket. */ class LoopbackWebSocket final : public WebSocket { protected: class Driver; private: Retained<Driver> _driver; actor::delay_t _latency; public: LoopbackWebSocket(const fleece::alloc_slice &url, Role role, actor::delay_t latency =actor::delay_t::zero()) :WebSocket(url, role) ,_latency(latency) { } /** Binds two LoopbackWebSocket objects to each other, so after they open, each will receive messages sent by the other. When one closes, the other will receive a close event. MUST be called before the socket objects' connect() methods are called! */ static void bind(WebSocket *c1, WebSocket *c2, const websocket::Headers &responseHeaders ={}) { auto lc1 = dynamic_cast<LoopbackWebSocket*>(c1); auto lc2 = dynamic_cast<LoopbackWebSocket*>(c2); lc1->bind(lc2, responseHeaders); lc2->bind(lc1, responseHeaders); } virtual void connect() override { Assert(_driver && _driver->_peer); _driver->enqueue(FUNCTION_TO_QUEUE(Driver::_connect)); } virtual bool send(fleece::slice msg, bool binary) override { auto newValue = (_driver->_bufferedBytes += msg.size); _driver->enqueue(FUNCTION_TO_QUEUE(Driver::_send), fleece::alloc_slice(msg), binary); return newValue <= kSendBufferSize; } virtual void close(int status =1000, fleece::slice message =fleece::nullslice) override { _driver->enqueue(FUNCTION_TO_QUEUE(Driver::_close), status, fleece::alloc_slice(message)); } protected: void bind(LoopbackWebSocket *peer, const websocket::Headers &responseHeaders) { Assert(!_driver); _driver = createDriver(); _driver->bind(peer, responseHeaders); } virtual Driver* createDriver() { return new Driver(this, _latency); } Driver* driver() const {return _driver;} void peerIsConnecting(actor::delay_t latency = actor::delay_t::zero()) { _driver->enqueueAfter(latency, FUNCTION_TO_QUEUE(Driver::_peerIsConnecting)); } virtual void ack(size_t msgSize) { _driver->enqueue(FUNCTION_TO_QUEUE(Driver::_ack), msgSize); } void received(Message *message, actor::delay_t latency = actor::delay_t::zero()) { _driver->enqueueAfter(latency, FUNCTION_TO_QUEUE(Driver::_received), retained(message)); } void closed(CloseReason reason =kWebSocketClose, int status =1000, const char *message =nullptr, actor::delay_t latency = actor::delay_t::zero()) { _driver->enqueueAfter(latency, FUNCTION_TO_QUEUE(Driver::_closed), CloseStatus(reason, status, fleece::slice(message))); } class LoopbackMessage : public Message { public: template <class SLICE> LoopbackMessage(LoopbackWebSocket *ws, SLICE data, bool binary) :Message(data, binary) ,_size(data.size) ,_webSocket(ws) { } ~LoopbackMessage() { _webSocket->ack(_size); } private: size_t _size; Retained<LoopbackWebSocket> _webSocket; }; // The internal Actor that does the real work class Driver final : public actor::Actor { public: Driver(LoopbackWebSocket *ws, actor::delay_t latency) :Actor(WSLogDomain) ,_webSocket(ws) ,_latency(latency) { } virtual std::string loggingIdentifier() const override { return _webSocket ? _webSocket->name() : "[Already closed]"; } virtual std::string loggingClassName() const override { return "LoopbackWS"; } void bind(LoopbackWebSocket *peer, const websocket::Headers &responseHeaders) { // Called by LoopbackProvider::bind, which is called before my connect() method, // so it's safe to set the member variables directly instead of on the actor queue. _peer = peer; _responseHeaders = responseHeaders; } bool connected() const { return _state == State::connected; } protected: enum class State { unconnected, peerConnecting, connecting, connected, closed }; ~Driver() { DebugAssert(!connected()); } virtual void _connect() { // Connecting uses a handshake, to ensure both sides have notified their delegates // they're connected before either side sends a message. In other words, to // prevent one side from receiving a message from the peer before it's ready. logVerbose("Connecting to peer..."); Assert(_state < State::connecting); _peer->peerIsConnecting(_latency); if (_state == State::peerConnecting) connectCompleted(); else _state = State::connecting; } void _peerIsConnecting() { logVerbose("(Peer is connecting...)"); switch (_state) { case State::unconnected: _state = State::peerConnecting; break; case State::connecting: connectCompleted(); break; case State::closed: // ignore in this state break; default: Assert(false, "illegal state"); break; } } void connectCompleted() { logInfo("CONNECTED"); _state = State::connected; _webSocket->delegate().onWebSocketGotHTTPResponse(200, _responseHeaders); _webSocket->delegate().onWebSocketConnect(); } virtual void _send(fleece::alloc_slice msg, bool binary) { if (_peer) { Assert(_state == State::connected); logDebug("SEND: %s", formatMsg(msg, binary).c_str()); Retained<Message> message(new LoopbackMessage(_webSocket, msg, binary)); _peer->received(message, _latency); } else { logInfo("SEND: Failed, socket is closed"); } } virtual void _received(Retained<Message> message) { if (!connected()) return; logDebug("RECEIVED: %s", formatMsg(message->data, message->binary).c_str()); _webSocket->delegate().onWebSocketMessage(message); } virtual void _ack(size_t msgSize) { if (!connected()) return; auto newValue = (_bufferedBytes -= msgSize); if (newValue <= kSendBufferSize && newValue + msgSize > kSendBufferSize) { logDebug("WRITEABLE"); _webSocket->delegate().onWebSocketWriteable(); } } virtual void _close(int status, fleece::alloc_slice message) { if (_state != State::unconnected) { Assert(_state == State::connecting || _state == State::connected); logInfo("CLOSE; status=%d", status); std::string messageStr(message); if (_peer) _peer->closed(kWebSocketClose, status, messageStr.c_str(), _latency); } _closed({kWebSocketClose, status, message}); } virtual void _closed(CloseStatus status) { if (_state == State::closed) return; if (_state >= State::connecting) { logInfo("CLOSED with %-s %d: %.*s", status.reasonName(), status.code, fleece::narrow_cast<int>(status.message.size), (char *)status.message.buf); _webSocket->delegate().onWebSocketClose(status); } else { logInfo("CLOSED"); } _state = State::closed; _peer = nullptr; _webSocket->clearDelegate(); _webSocket = nullptr; // breaks cycle } static std::string formatMsg(fleece::slice msg, bool binary, size_t maxBytes = 64) { std::stringstream desc; size_t size = std::min(msg.size, maxBytes); if (binary) { desc << std::hex; for (size_t i = 0; i < size; i++) { if (i > 0) { if ((i % 32) == 0) desc << "\n\t\t"; else if ((i % 4) == 0) desc << ' '; } desc << std::setw(2) << std::setfill('0') << (unsigned)msg[i]; } desc << std::dec; } else { desc.write((char*)msg.buf, size); } if (size < msg.size) desc << "... [" << msg.size << "]"; return desc.str(); } private: friend class LoopbackWebSocket; Retained<LoopbackWebSocket> _webSocket; actor::delay_t _latency {0.0}; Retained<LoopbackWebSocket> _peer; websocket::Headers _responseHeaders; std::atomic<size_t> _bufferedBytes {0}; State _state {State::unconnected}; }; }; } }
35.888889
102
0.515789
tophatch
a135afa046cff6d9c021a331e0d1f070e399de6a
228
cpp
C++
CustomWindow.Test.cpp
jmfb/wex
b012a7e5d8dfa978a432363bb11b64474e487f5f
[ "MIT" ]
1
2017-01-08T14:11:58.000Z
2017-01-08T14:11:58.000Z
CustomWindow.Test.cpp
jmfb/wex
b012a7e5d8dfa978a432363bb11b64474e487f5f
[ "MIT" ]
null
null
null
CustomWindow.Test.cpp
jmfb/wex
b012a7e5d8dfa978a432363bb11b64474e487f5f
[ "MIT" ]
null
null
null
#include "WindowsInclude.h" #include "CustomWindow.h" #include "Exception.h" #include <UnitTest/UnitTest.h> using UnitTest::Assert; namespace Wex { TEST_CLASS(CustomWindowTest) { public: CustomWindowTest() { } }; }
12
30
0.710526
jmfb
a1361af5530ec5a99f22969d394784f7cd19a9f5
527
cpp
C++
motion/velocity_controller/src/velocity_controller_node.cpp
vortexntnu/manta-AUV
c9e223c60cf0672e74b42aa2ea2dfe988de5d359
[ "MIT" ]
null
null
null
motion/velocity_controller/src/velocity_controller_node.cpp
vortexntnu/manta-AUV
c9e223c60cf0672e74b42aa2ea2dfe988de5d359
[ "MIT" ]
null
null
null
motion/velocity_controller/src/velocity_controller_node.cpp
vortexntnu/manta-AUV
c9e223c60cf0672e74b42aa2ea2dfe988de5d359
[ "MIT" ]
null
null
null
#include "velocity_controller/velocity_controller.h" int main(int argc, char **argv) { const bool DEBUG_MODE = false; // debug logs are printed to console when true ros::init(argc, argv, "velocity_controller"); ros::NodeHandle nh; if (DEBUG_MODE) { ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug); ros::console::notifyLoggerLevelsChanged(); } VelocityController velocity_controller(nh); velocity_controller.spin(); return 0; }
27.736842
79
0.688805
vortexntnu
a13654a0a2dfad380548bf3b0cd7837adec698c3
910
hpp
C++
sources/dansandu/glyph/error.hpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
sources/dansandu/glyph/error.hpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
sources/dansandu/glyph/error.hpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
#pragma once #include <exception> namespace dansandu::glyph::error { class GrammarError : public std::exception { public: explicit GrammarError(std::string message) : message_{std::move(message)} { } const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; }; class TokenizationError : public std::exception { public: explicit TokenizationError(std::string message) : message_{std::move(message)} { } const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; }; class SyntaxError : public std::exception { public: explicit SyntaxError(std::string message) : message_{std::move(message)} { } const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; }; }
15.964912
82
0.647253
dansandu
a1390401d6de5efb986f1ed268c0a972948b5742
4,269
cpp
C++
client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp
pertgame/battleframe
ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9
[ "MIT" ]
1
2020-10-28T15:19:15.000Z
2020-10-28T15:19:15.000Z
client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp
pertgame/battleframe
ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9
[ "MIT" ]
null
null
null
client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp
pertgame/battleframe
ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9
[ "MIT" ]
1
2020-10-28T15:19:40.000Z
2020-10-28T15:19:40.000Z
/**************************************************************************** Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 "middleware-adapter.h" #include "base/ccMacros.h" #include "renderer/gfx/Texture.h" using namespace cocos2d; using namespace cocos2d::renderer; MIDDLEWARE_BEGIN Texture2D::Texture2D() { } Texture2D::~Texture2D() { CC_SAFE_RELEASE(_texture); _texParamCallback = nullptr; } int Texture2D::getPixelsWide() const { return _pixelsWide; } int Texture2D::getPixelsHigh() const { return _pixelsHigh; } void Texture2D::setPixelsWide(int wide) { this->_pixelsWide = wide; } void Texture2D::setPixelsHigh(int high) { this->_pixelsHigh = high; } int Texture2D::getRealTextureIndex() const { return this->_realTextureIndex; } void Texture2D::setRealTextureIndex(int textureIndex) { this->_realTextureIndex = textureIndex; } void Texture2D::setTexParamCallback(const texParamCallback& callback) { this->_texParamCallback = callback; } void Texture2D::setTexParameters(const TexParams& texParams) { if (_texParamCallback) { _texParamCallback(this->_realTextureIndex,texParams.minFilter,texParams.magFilter,texParams.wrapS,texParams.wrapT); } } void Texture2D::setNativeTexture(Texture* texture) { if (_texture == texture) return; CC_SAFE_RELEASE(_texture); _texture = texture; CC_SAFE_RETAIN(_texture); } Texture* Texture2D::getNativeTexture() const { return _texture; } SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const cocos2d::Rect& rect) { SpriteFrame *spriteFrame = new (std::nothrow) SpriteFrame(); spriteFrame->initWithTexture(texture, rect); spriteFrame->autorelease(); return spriteFrame; } SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const cocos2d::Rect& rect, bool rotated, const cocos2d::Vec2& offset, const cocos2d::Size& originalSize) { SpriteFrame *spriteFrame = new (std::nothrow) SpriteFrame(); spriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize); spriteFrame->autorelease(); return spriteFrame; } bool SpriteFrame::initWithTexture(Texture2D* texture, const cocos2d::Rect& rect) { return initWithTexture(texture, rect, false, cocos2d::Vec2::ZERO, rect.size); } bool SpriteFrame::initWithTexture(Texture2D* texture, const cocos2d::Rect& rect, bool rotated, const cocos2d::Vec2& offset, const cocos2d::Size& originalSize) { _texture = texture; if (texture) { texture->retain(); } _rectInPixels = rect; _offsetInPixels = offset; _originalSizeInPixels = originalSize; _rotated = rotated; _anchorPoint = cocos2d::Vec2(NAN, NAN); return true; } SpriteFrame::SpriteFrame() { } SpriteFrame::~SpriteFrame() { CC_SAFE_RELEASE(_texture); } void SpriteFrame::setTexture(Texture2D * texture) { if( _texture != texture ) { CC_SAFE_RELEASE(_texture); CC_SAFE_RETAIN(texture); _texture = texture; } } Texture2D* SpriteFrame::getTexture() { return _texture; } MIDDLEWARE_END
25.562874
168
0.707191
pertgame
a13addd75a2145e126f57e0a70f0b888612b612c
5,759
cpp
C++
flang/unittests/Runtime/CommandTest.cpp
undingen/BOLT
87e45c91d3dd440021177bc9d37f449db57ecd2d
[ "Apache-1.1" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
flang/unittests/Runtime/CommandTest.cpp
undingen/BOLT
87e45c91d3dd440021177bc9d37f449db57ecd2d
[ "Apache-1.1" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
flang/unittests/Runtime/CommandTest.cpp
undingen/BOLT
87e45c91d3dd440021177bc9d37f449db57ecd2d
[ "Apache-1.1" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===-- flang/unittests/RuntimeGTest/CommandTest.cpp ----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "flang/Runtime/command.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "flang/Runtime/descriptor.h" #include "flang/Runtime/main.h" using namespace Fortran::runtime; template <std::size_t n = 64> static OwningPtr<Descriptor> CreateEmptyCharDescriptor() { OwningPtr<Descriptor> descriptor{Descriptor::Create( sizeof(char), n, nullptr, 0, nullptr, CFI_attribute_allocatable)}; if (descriptor->Allocate() != 0) { return nullptr; } return descriptor; } class CommandFixture : public ::testing::Test { protected: CommandFixture(int argc, const char *argv[]) { RTNAME(ProgramStart)(argc, argv, {}); } std::string GetPaddedStr(const char *text, std::size_t len) const { std::string res{text}; assert(res.length() <= len && "No room to pad"); res.append(len - res.length(), ' '); return res; } void CheckDescriptorEqStr( const Descriptor *value, const std::string &expected) const { EXPECT_EQ(std::strncmp(value->OffsetElement(), expected.c_str(), value->ElementBytes()), 0); } void CheckArgumentValue(int n, const char *argv) const { OwningPtr<Descriptor> value{CreateEmptyCharDescriptor()}; ASSERT_NE(value, nullptr); std::string expected{GetPaddedStr(argv, value->ElementBytes())}; EXPECT_EQ(RTNAME(ArgumentValue)(n, value.get(), nullptr), 0); CheckDescriptorEqStr(value.get(), expected); } void CheckMissingArgumentValue(int n, const char *errStr = nullptr) const { OwningPtr<Descriptor> value{CreateEmptyCharDescriptor()}; ASSERT_NE(value, nullptr); OwningPtr<Descriptor> err{errStr ? CreateEmptyCharDescriptor() : nullptr}; EXPECT_GT(RTNAME(ArgumentValue)(n, value.get(), err.get()), 0); std::string spaces(value->ElementBytes(), ' '); CheckDescriptorEqStr(value.get(), spaces); if (errStr) { std::string paddedErrStr(GetPaddedStr(errStr, err->ElementBytes())); CheckDescriptorEqStr(err.get(), paddedErrStr); } } }; static const char *commandOnlyArgv[]{"aProgram"}; class ZeroArguments : public CommandFixture { protected: ZeroArguments() : CommandFixture(1, commandOnlyArgv) {} }; TEST_F(ZeroArguments, ArgumentCount) { EXPECT_EQ(0, RTNAME(ArgumentCount)()); } TEST_F(ZeroArguments, ArgumentLength) { EXPECT_EQ(0, RTNAME(ArgumentLength)(-1)); EXPECT_EQ(8, RTNAME(ArgumentLength)(0)); EXPECT_EQ(0, RTNAME(ArgumentLength)(1)); } TEST_F(ZeroArguments, ArgumentValue) { CheckArgumentValue(0, commandOnlyArgv[0]); } static const char *oneArgArgv[]{"aProgram", "anArgumentOfLength20"}; class OneArgument : public CommandFixture { protected: OneArgument() : CommandFixture(2, oneArgArgv) {} }; TEST_F(OneArgument, ArgumentCount) { EXPECT_EQ(1, RTNAME(ArgumentCount)()); } TEST_F(OneArgument, ArgumentLength) { EXPECT_EQ(0, RTNAME(ArgumentLength)(-1)); EXPECT_EQ(8, RTNAME(ArgumentLength)(0)); EXPECT_EQ(20, RTNAME(ArgumentLength)(1)); EXPECT_EQ(0, RTNAME(ArgumentLength)(2)); } TEST_F(OneArgument, ArgumentValue) { CheckArgumentValue(0, oneArgArgv[0]); CheckArgumentValue(1, oneArgArgv[1]); } static const char *severalArgsArgv[]{ "aProgram", "16-char-long-arg", "", "-22-character-long-arg", "o"}; class SeveralArguments : public CommandFixture { protected: SeveralArguments() : CommandFixture(sizeof(severalArgsArgv) / sizeof(*severalArgsArgv), severalArgsArgv) {} }; TEST_F(SeveralArguments, ArgumentCount) { EXPECT_EQ(4, RTNAME(ArgumentCount)()); } TEST_F(SeveralArguments, ArgumentLength) { EXPECT_EQ(0, RTNAME(ArgumentLength)(-1)); EXPECT_EQ(8, RTNAME(ArgumentLength)(0)); EXPECT_EQ(16, RTNAME(ArgumentLength)(1)); EXPECT_EQ(0, RTNAME(ArgumentLength)(2)); EXPECT_EQ(22, RTNAME(ArgumentLength)(3)); EXPECT_EQ(1, RTNAME(ArgumentLength)(4)); EXPECT_EQ(0, RTNAME(ArgumentLength)(5)); } TEST_F(SeveralArguments, ArgumentValue) { CheckArgumentValue(0, severalArgsArgv[0]); CheckArgumentValue(1, severalArgsArgv[1]); CheckArgumentValue(3, severalArgsArgv[3]); CheckArgumentValue(4, severalArgsArgv[4]); } TEST_F(SeveralArguments, NoArgumentValue) { // Make sure we don't crash if the 'value' and 'error' parameters aren't // passed. EXPECT_EQ(RTNAME(ArgumentValue)(2, nullptr, nullptr), 0); EXPECT_GT(RTNAME(ArgumentValue)(-1, nullptr, nullptr), 0); } TEST_F(SeveralArguments, MissingArguments) { CheckMissingArgumentValue(-1, "Invalid argument number"); CheckMissingArgumentValue(2, "Missing argument"); CheckMissingArgumentValue(5, "Invalid argument number"); CheckMissingArgumentValue(5); } TEST_F(SeveralArguments, ValueTooShort) { OwningPtr<Descriptor> tooShort{CreateEmptyCharDescriptor<15>()}; ASSERT_NE(tooShort, nullptr); EXPECT_EQ(RTNAME(ArgumentValue)(1, tooShort.get(), nullptr), -1); CheckDescriptorEqStr(tooShort.get(), severalArgsArgv[1]); OwningPtr<Descriptor> errMsg{CreateEmptyCharDescriptor()}; ASSERT_NE(errMsg, nullptr); EXPECT_EQ(RTNAME(ArgumentValue)(1, tooShort.get(), errMsg.get()), -1); std::string expectedErrMsg{ GetPaddedStr("Value too short", errMsg->ElementBytes())}; CheckDescriptorEqStr(errMsg.get(), expectedErrMsg); } TEST_F(SeveralArguments, ErrMsgTooShort) { OwningPtr<Descriptor> errMsg{CreateEmptyCharDescriptor<3>()}; EXPECT_GT(RTNAME(ArgumentValue)(-1, nullptr, errMsg.get()), 0); CheckDescriptorEqStr(errMsg.get(), "Inv"); }
32.353933
80
0.708109
undingen
a13b7be1fa2df2e4b6931f137b7b24dfd069a80c
9,444
cc
C++
src/nnet2bin/nnet2-modify-learning-rates.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
2
2017-05-02T15:45:03.000Z
2017-07-06T06:34:51.000Z
src/nnet2bin/nnet2-modify-learning-rates.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
null
null
null
src/nnet2bin/nnet2-modify-learning-rates.cc
vimalmanohar/kaldi-tfmask
592c784f582e3d19a8cc1fe1071eac4c7e0c4833
[ "Apache-2.0" ]
null
null
null
// nnet2bin/nnet2-modify-learning-rates.cc // Copyright 2013 Guoguo Chen // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "hmm/transition-model.h" #include "nnet2/nnet-randomize.h" #include "nnet2/train-nnet.h" #include "nnet2/am-nnet.h" namespace kaldi { namespace nnet2 { void SetMaxChange(BaseFloat max_change, Nnet *nnet) { for (int32 c = 0; c < nnet->NumComponents(); c++) { Component *component = &(nnet->GetComponent(c)); AffineComponentPreconditioned *ac = dynamic_cast<AffineComponentPreconditioned*>(component); if (ac != NULL) ac->SetMaxChange(max_change); } } } } int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::nnet2; typedef kaldi::int32 int32; typedef kaldi::int64 int64; const char *usage = "This program modifies the learning rates so as to equalize the\n" "relative changes in parameters for each layer, while keeping their\n" "geometric mean the same (or changing it to a value specified using\n" "the --average-learning-rate option).\n" "By default reads/writes model file (.mdl) but with --raw=true,\n" "reads/writes raw-nnet.\n" "\n" "Usage: nnet2-modify-learning-rates [options] <prev-model> \\\n" " <cur-model> <modified-cur-model>\n" "e.g.: nnet2-modify-learning-rates --average-learning-rate=0.0002 \\\n" " 5.mdl 6.mdl 6.mdl\n"; bool binary_write = true; bool retroactive = false; BaseFloat average_learning_rate = 0.0; BaseFloat first_layer_factor = 1.0; BaseFloat last_layer_factor = 1.0; bool raw = false; ParseOptions po(usage); po.Register("raw", &raw, "If true, read/write raw neural net rather than .mdl"); po.Register("binary", &binary_write, "Write output in binary mode"); po.Register("average-learning-rate", &average_learning_rate, "If supplied, change learning rate geometric mean to the given " "value."); po.Register("first-layer-factor", &first_layer_factor, "Factor that " "reduces the target relative learning rate for first layer."); po.Register("last-layer-factor", &last_layer_factor, "Factor that " "reduces the target relative learning rate for last layer."); po.Register("retroactive", &retroactive, "If true, scale the parameter " "differences as well."); po.Read(argc, argv); if (po.NumArgs() != 3) { po.PrintUsage(); exit(1); } KALDI_ASSERT(average_learning_rate >= 0); std::string prev_nnet_rxfilename = po.GetArg(1), cur_nnet_rxfilename = po.GetArg(2), modified_cur_nnet_rxfilename = po.GetOptArg(3); TransitionModel trans_model; AmNnet am_prev_nnet, am_cur_nnet; Nnet prev_nnet, cur_nnet; if (!raw) { bool binary_read; Input ki(prev_nnet_rxfilename, &binary_read); trans_model.Read(ki.Stream(), binary_read); am_prev_nnet.Read(ki.Stream(), binary_read); } else { ReadKaldiObject(prev_nnet_rxfilename, &prev_nnet); } if (!raw) { bool binary_read; Input ki(cur_nnet_rxfilename, &binary_read); trans_model.Read(ki.Stream(), binary_read); am_cur_nnet.Read(ki.Stream(), binary_read); } else { ReadKaldiObject(cur_nnet_rxfilename, &cur_nnet); } if (am_prev_nnet.GetNnet().GetParameterDim() != am_cur_nnet.GetNnet().GetParameterDim()) { KALDI_WARN << "Parameter-dim mismatch, cannot equalize the relative " << "changes in parameters for each layer."; exit(0); } int32 ret = 0; // Gets relative parameter differences. int32 num_updatable = (raw ? prev_nnet.NumUpdatableComponents() : am_prev_nnet.GetNnet().NumUpdatableComponents()); Vector<BaseFloat> relative_diff(num_updatable); { Nnet diff_nnet((raw ? prev_nnet : am_prev_nnet.GetNnet())); diff_nnet.AddNnet(-1.0, (raw ? cur_nnet : am_cur_nnet.GetNnet())); diff_nnet.ComponentDotProducts(diff_nnet, &relative_diff); relative_diff.ApplyPow(0.5); Vector<BaseFloat> baseline_prod(num_updatable); if (!raw) { am_prev_nnet.GetNnet().ComponentDotProducts(am_prev_nnet.GetNnet(), &baseline_prod); } else { prev_nnet.ComponentDotProducts(prev_nnet, &baseline_prod); } baseline_prod.ApplyPow(0.5); relative_diff.DivElements(baseline_prod); KALDI_LOG << "Relative parameter differences per layer are " << relative_diff; // If relative parameter difference for a certain is zero, set it to the // mean of the rest values. int32 num_zero = 0; for (int32 i = 0; i < num_updatable; i++) { if (relative_diff(i) == 0.0) { num_zero++; } } if (num_zero > 0) { BaseFloat average_diff = relative_diff.Sum() / static_cast<BaseFloat>(num_updatable - num_zero); for (int32 i = 0; i < num_updatable; i++) { if (relative_diff(i) == 0.0) { relative_diff(i) = average_diff; } } KALDI_LOG << "Zeros detected in the relative parameter difference " << "vector, updating the vector to " << relative_diff; } } // Gets learning rates for previous neural net. Vector<BaseFloat> prev_nnet_learning_rates(num_updatable), cur_nnet_learning_rates(num_updatable); if (!raw) { am_prev_nnet.GetNnet().GetLearningRates(&prev_nnet_learning_rates); am_cur_nnet.GetNnet().GetLearningRates(&cur_nnet_learning_rates); } else { prev_nnet.GetLearningRates(&prev_nnet_learning_rates); cur_nnet.GetLearningRates(&cur_nnet_learning_rates); } KALDI_LOG << "Learning rates for previous model per layer are " << prev_nnet_learning_rates; KALDI_LOG << "Learning rates for current model per layer are " << cur_nnet_learning_rates; // Gets target geometric mean. BaseFloat target_geometric_mean = 0.0; if (average_learning_rate == 0.0) { target_geometric_mean = exp(cur_nnet_learning_rates.SumLog() / static_cast<BaseFloat>(num_updatable)); } else { target_geometric_mean = average_learning_rate; } KALDI_ASSERT(target_geometric_mean > 0.0); // Works out the new learning rates. We start from the previous model; // this ensures that if this program is run twice, we get consistent // results even if it's overwritten the current model. Vector<BaseFloat> nnet_learning_rates(prev_nnet_learning_rates); nnet_learning_rates.DivElements(relative_diff); KALDI_ASSERT(last_layer_factor > 0.0); nnet_learning_rates(num_updatable - 1) *= last_layer_factor; KALDI_ASSERT(first_layer_factor > 0.0); nnet_learning_rates(0) *= first_layer_factor; BaseFloat cur_geometric_mean = exp(nnet_learning_rates.SumLog() / static_cast<BaseFloat>(num_updatable)); nnet_learning_rates.Scale(target_geometric_mean / cur_geometric_mean); KALDI_LOG << "New learning rates for current model per layer are " << nnet_learning_rates; // Changes the parameter differences if --retroactivate is set to true. if (retroactive) { Vector<BaseFloat> scale_factors(nnet_learning_rates); scale_factors.DivElements(prev_nnet_learning_rates); if (!raw) { am_cur_nnet.GetNnet().AddNnet(-1.0, am_prev_nnet.GetNnet()); am_cur_nnet.GetNnet().ScaleComponents(scale_factors); am_cur_nnet.GetNnet().AddNnet(1.0, am_prev_nnet.GetNnet()); } else { cur_nnet.AddNnet(-1.0, prev_nnet); cur_nnet.ScaleComponents(scale_factors); cur_nnet.AddNnet(1.0, prev_nnet); } KALDI_LOG << "Scale parameter difference retroactively. Scaling factors " << "are " << scale_factors; } // Sets learning rates and writes updated model. if (!raw) { am_cur_nnet.GetNnet().SetLearningRates(nnet_learning_rates); SetMaxChange(0.0, &(am_cur_nnet.GetNnet())); Output ko(modified_cur_nnet_rxfilename, binary_write); trans_model.Write(ko.Stream(), binary_write); am_cur_nnet.Write(ko.Stream(), binary_write); } else { cur_nnet.SetLearningRates(nnet_learning_rates); SetMaxChange(0.0, &(cur_nnet)); WriteKaldiObject(cur_nnet, modified_cur_nnet_rxfilename, binary_write); } return ret; } catch(const std::exception &e) { std::cerr << e.what() << '\n'; return -1; } }
38.704918
119
0.654913
vimalmanohar
a13d6b129a3f2b8b679d5dd730cc64cd0630e842
1,823
cc
C++
alidns/src/model/ModifyHichinaDomainDNSResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
alidns/src/model/ModifyHichinaDomainDNSResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
alidns/src/model/ModifyHichinaDomainDNSResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/alidns/model/ModifyHichinaDomainDNSResult.h> #include <json/json.h> using namespace AlibabaCloud::Alidns; using namespace AlibabaCloud::Alidns::Model; ModifyHichinaDomainDNSResult::ModifyHichinaDomainDNSResult() : ServiceResult() {} ModifyHichinaDomainDNSResult::ModifyHichinaDomainDNSResult(const std::string &payload) : ServiceResult() { parse(payload); } ModifyHichinaDomainDNSResult::~ModifyHichinaDomainDNSResult() {} void ModifyHichinaDomainDNSResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allOriginalDnsServers = value["OriginalDnsServers"]["DnsServer"]; for (const auto &item : allOriginalDnsServers) originalDnsServers_.push_back(item.asString()); auto allNewDnsServers = value["NewDnsServers"]["DnsServer"]; for (const auto &item : allNewDnsServers) newDnsServers_.push_back(item.asString()); } std::vector<std::string> ModifyHichinaDomainDNSResult::getNewDnsServers()const { return newDnsServers_; } std::vector<std::string> ModifyHichinaDomainDNSResult::getOriginalDnsServers()const { return originalDnsServers_; }
29.403226
88
0.77345
sdk-team
a13db81a87da872e78d54c2eb1cabdd7e38a3d9f
6,806
cpp
C++
youth/cpp_exp/ex5/project5/lab5/findstop.cpp
uivid64/violet_youth
8568c1c22b2dc446d54061474330620f92bd594d
[ "Apache-2.0" ]
null
null
null
youth/cpp_exp/ex5/project5/lab5/findstop.cpp
uivid64/violet_youth
8568c1c22b2dc446d54061474330620f92bd594d
[ "Apache-2.0" ]
null
null
null
youth/cpp_exp/ex5/project5/lab5/findstop.cpp
uivid64/violet_youth
8568c1c22b2dc446d54061474330620f92bd594d
[ "Apache-2.0" ]
null
null
null
#include "lab5.h" #include "logiclayer.h" #include "QtWidgetsFL.h" #include "findstop.h" #include <QDialog> #include <QDesktopWidget> #include <QApplication> #include <QMessageBox> #include <QGraphicsSceneMouseEvent> #include <QGraphicsRectItem> #include <QGraphicsEllipseItem> #include "QtTipsDlgView.h" #include <QtWidgets/QMainWindow> #include <QTextCodec> #include <qdirmodel.h> #include <QKeyEvent> #include <QKeyEvent> #include <qstringlistmodel.h> findstop::findstop(QStringList words, QWidget* parent) : QWidget(parent), words(words) { ui.setupUi(this); connect(ui.pushButton_exit, SIGNAL(clicked()), this, SLOT(findstop_exit()), Qt::UniqueConnection); listView1 = ui.listView1;//new QListView(this); listView2 = ui.listView2;//new QListView(this); model1 = new QStringListModel(this); model2 = new QStringListModel(this); listView1->setWindowFlags(Qt::ToolTip); listView2->setWindowFlags(Qt::ToolTip); connect(ui.lineEdit1, SIGNAL(textChanged(QString)), this, SLOT(setCompleter1(QString)), Qt::UniqueConnection); connect(listView1, SIGNAL(clicked(const QModelIndex&)), this, SLOT(completeText1(const QModelIndex&))); connect(ui.lineEdit2, SIGNAL(textChanged(QString)), this, SLOT(setCompleter2(QString)), Qt::UniqueConnection); connect(listView2, SIGNAL(clicked(const QModelIndex&)), this, SLOT(completeText2(const QModelIndex&))); } findstop::~findstop() { } void findstop::myShow(QGraphicsView* p) { parnt = p; show(); } QString toch(const QString& str) { QTextCodec* gbk = QTextCodec::codecForName("GB18030"); return gbk->toUnicode(str.toLocal8Bit()); } void findstop::findstop_ok() { QString start = toch(ui.lineEdit1->text()); QString stop = toch(ui.lineEdit2->text()); char start_str[100]; char stop_str[100]; strcpy(start_str, start.toLocal8Bit().data()); strcpy(stop_str, stop.toLocal8Bit().data()); //addItem(new MyItem(100, 100, 1)); int flag = 0, flag2 = 0; if (strcmp(start_str, "华中科技大学") == 0) flag = 1; if (strcmp(start_str, "华乐山庄") == 0) flag = 2; if (strcmp(start_str, "光谷中心花园") == 0) flag = 3; if (strcmp(start_str, "光谷街北路") == 0) flag = 4; if (strcmp(stop_str, "华中科技大学") == 0) flag2 = 1; if (strcmp(stop_str, "华乐山庄") == 0) flag2 = 2; if (strcmp(stop_str, "光谷中心花园") == 0) flag2 = 3; if (strcmp(stop_str, "光谷街北路") == 0) flag2 = 4; ((MyScene*)(parnt->scene()))->add_place(flag, flag2); } void findstop::focusOutEvent(QFocusEvent* e) { //listView->hide(); } void findstop::keyPressEvent1(QKeyEvent* e) { if (!listView1->isHidden()) { int key = e->key(); int count = listView1->model()->rowCount(); QModelIndex currentIndex = listView1->currentIndex(); if (Qt::Key_Down == key) { // 按向下方向键时,移动光标选中下一个完成列表中的项 int row = currentIndex.row() + 1; if (row >= count) { row = 0; } QModelIndex index = listView1->model()->index(row, 0); listView1->setCurrentIndex(index); } else if (Qt::Key_Up == key) { // 按向下方向键时,移动光标选中上一个完成列表中的项 int row = currentIndex.row() - 1; if (row < 0) { row = count - 1; } QModelIndex index = listView1->model()->index(row, 0); listView1->setCurrentIndex(index); } else if (Qt::Key_Escape == key) { // 按下Esc键时,隐藏完成列表 listView1->hide(); } else if (Qt::Key_Enter == key || Qt::Key_Return == key) { // 按下回车键时,使用完成列表中选中的项,并隐藏完成列表 if (currentIndex.isValid()) { QString text = listView1->currentIndex().data().toString(); setText1(text); } listView1->hide(); } else { // 其他情况,隐藏完成列表,并使用QLineEdit的键盘按下事件 listView1->hide(); //QLineEdit::keyPressEvent(e); } } else { //QLineEdit::keyPressEvent(e); } } bool contains(QString s, QString t) { int i = 0, j = 0; for (i = 0; i < t.length(); i++) { while (s.at(j) != t.at(i)) { j++; if (j == s.length()) return 0; } } return 1; } void findstop::setCompleter1(QString text) { if (text.isEmpty()) { listView1->hide(); return; } if ((text.length() > 1) && (!listView1->isHidden())) { //return; } // 如果完整的完成列表中的某个单词包含输入的文本,则加入要显示的完成列表串中 QStringList sl; foreach(QString word, words) { //if (word.contains(text)) { if (contains(word, text)) { sl << word; } } model1->setStringList(sl); listView1->setModel(model1); if (model1->rowCount() == 0) { return; } // Position the text edit listView1->setMinimumWidth(width() / 2); listView1->setMaximumWidth(width() / 2); QPoint p(0, 0); int x = mapToGlobal(p).x() + 170; int y = mapToGlobal(p).y() + 110; //int x = 122; //int y = 90; listView1->move(x, y); listView1->show(); } void findstop::completeText1(const QModelIndex& index) { QString text = index.data().toString(); setText1(text); listView1->hide(); } void findstop::keyPressEvent2(QKeyEvent* e) { if (!listView2->isHidden()) { int key = e->key(); int count = listView2->model()->rowCount(); QModelIndex currentIndex = listView2->currentIndex(); if (Qt::Key_Down == key) { // 按向下方向键时,移动光标选中下一个完成列表中的项 int row = currentIndex.row() + 1; if (row >= count) { row = 0; } QModelIndex index = listView2->model()->index(row, 0); listView2->setCurrentIndex(index); } else if (Qt::Key_Up == key) { // 按向下方向键时,移动光标选中上一个完成列表中的项 int row = currentIndex.row() - 1; if (row < 0) { row = count - 1; } QModelIndex index = listView2->model()->index(row, 0); listView2->setCurrentIndex(index); } else if (Qt::Key_Escape == key) { // 按下Esc键时,隐藏完成列表 listView2->hide(); } else if (Qt::Key_Enter == key || Qt::Key_Return == key) { // 按下回车键时,使用完成列表中选中的项,并隐藏完成列表 if (currentIndex.isValid()) { QString text = listView2->currentIndex().data().toString(); setText2(text); } listView2->hide(); } else { // 其他情况,隐藏完成列表,并使用QLineEdit的键盘按下事件 listView2->hide(); //QLineEdit::keyPressEvent(e); } } else { //QLineEdit::keyPressEvent(e); } } void findstop::setCompleter2(QString text) { if (text.isEmpty()) { listView2->hide(); return; } if ((text.length() > 1) && (!listView2->isHidden())) { //return; } // 如果完整的完成列表中的某个单词包含输入的文本,则加入要显示的完成列表串中 QStringList sl; foreach(QString word, words) { if (contains(word, text)) { sl << word; } } model2->setStringList(sl); listView2->setModel(model2); if (model2->rowCount() == 0) { return; } // Position the text edit listView2->setMinimumWidth(width() / 2); listView2->setMaximumWidth(width() / 2); QPoint p(0, 0); int x = mapToGlobal(p).x() + 170; int y = mapToGlobal(p).y() + 190; //int x = 122; //int y = 90; listView2->move(x, y); listView2->show(); } void findstop::completeText2(const QModelIndex& index) { QString text = index.data().toString(); setText2(text); listView2->hide(); } void findstop::setText1(QString text) { ui.lineEdit1->setText(text); } void findstop::setText2(QString text) { ui.lineEdit2->setText(text); }
23.308219
111
0.653982
uivid64
a13e9b36229a60c983d67c9876ab9ac18e4ca931
2,368
hpp
C++
src/polygon.hpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
null
null
null
src/polygon.hpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
1
2015-01-13T10:15:56.000Z
2015-01-13T10:15:56.000Z
src/polygon.hpp
npolar/reshp
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * *\ |* ╔═╗ v0.4 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #ifndef RESHP_POLYGON_HPP_ #define RESHP_POLYGON_HPP_ #include "point.hpp" #include "aabb.hpp" #include "shp.hpp" #include "segment.hpp" #include <vector> namespace reshp { struct polygon { struct ring; struct intersection { reshp::point point; reshp::polygon::ring* ring; reshp::segment* segment; int segment_index; struct intersector { reshp::polygon::ring* ring; reshp::segment* segment; int segment_index; intersector(reshp::polygon::ring* = NULL); } intersector; intersection(reshp::polygon::ring* = NULL, reshp::polygon::ring* intersector_ring = NULL); }; struct ring { ring(); reshp::aabb aabb; enum { outer, inner } type; std::vector<reshp::segment> segments; void calculate_aabb(); bool contains(const reshp::point&) const; void invert(); // Change direction (toggle inner/outer typed ring) bool inside(const reshp::polygon::ring&) const; bool intersects() const; // Self-intersection bool intersects(const reshp::polygon::ring&, std::vector<reshp::polygon::intersection>* intersections = NULL) const; }; polygon(); polygon(const reshp::polygon&); polygon(const reshp::shp::polygon&); reshp::aabb aabb; std::vector<reshp::polygon::ring> rings; void calculate_aabb(); bool contains(const reshp::point&) const; bool inside(const reshp::polygon&) const; bool intersects() const; // Self-intersection bool intersects(const reshp::polygon&, std::vector<reshp::polygon::intersection>* intersections = NULL) const; void operator>> (reshp::shp::polygon&) const; }; } #endif // RESHP_POLYGON_HPP_
29.234568
128
0.494932
npolar
a140a746eb600e0c2ab11b97d3ffbb028fec4b12
1,711
cpp
C++
Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp
MasumBhai/cse-216-presentation
6c25dc537c949ab6b4e8ebeb20af7909fac4801c
[ "CC0-1.0" ]
null
null
null
Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp
MasumBhai/cse-216-presentation
6c25dc537c949ab6b4e8ebeb20af7909fac4801c
[ "CC0-1.0" ]
null
null
null
Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp
MasumBhai/cse-216-presentation
6c25dc537c949ab6b4e8ebeb20af7909fac4801c
[ "CC0-1.0" ]
null
null
null
/* auther : Abdullah Al Masum MIST_roll : 201914044 problem Link : https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/oliver-and-the-battle-1/submissions/ */ #include<bits/stdc++.h> #define MAX 1000 using namespace std; int n,m; int mat[MAX][MAX]; int visited[MAX][MAX]; int bfs(int x, int y) { visited[x][y] = 1; int countt = 1; queue<pair<int,int> > Queue; Queue.push(make_pair(x,y)); while(!Queue.empty()) { x = Queue.front().first; y = Queue.front().second; Queue.pop(); for(int i = -1 ; i<=1; i++ ) { for(int j = -1; j<=1; j++) { if(!visited[x+i][y+j] && mat[x+i][y+j]) { countt++; Queue.push(make_pair(x+i,y+j)); visited[x+i][y+j] = 1; } } } } return countt; } int main() { int test; cin>>test; while(test--) { cin>>n>>m; memset(mat,0,sizeof(mat)); memset(visited,0,sizeof(visited)); for(int i = 1; i<=n ; i++) { for(int j = 1; j<= m; j++) { int res; cin>>res; mat[i][j] = res; } } int maxZomniKill = 0; int zomnitroops = 0; for(int i = 1; i <= n ; i++) for(int j = 1; j<= m; j++) { if(!visited[i][j] && mat[i][j]) { maxZomniKill = max( bfs(i,j), maxZomniKill ); zomnitroops++; } } cout<<zomnitroops<<" "<<maxZomniKill<<endl; } return 0; }
26.734375
156
0.435418
MasumBhai
a141b8d8bc5d94757ea150d3ed4e91e0fa1bdc27
3,042
cc
C++
engines/ep/src/diskdockey.cc
hrajput89/kv_engine
33fb1ab2c9787f55555e5f7edea38807b3dbc371
[ "BSD-3-Clause" ]
1
2019-06-13T07:33:09.000Z
2019-06-13T07:33:09.000Z
engines/ep/src/diskdockey.cc
paolococchi/kv_engine
40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45
[ "BSD-3-Clause" ]
null
null
null
engines/ep/src/diskdockey.cc
paolococchi/kv_engine
40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45
[ "BSD-3-Clause" ]
1
2020-01-15T16:52:37.000Z
2020-01-15T16:52:37.000Z
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2019 Couchbase, Inc * * 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 "diskdockey.h" #include "item.h" #include <mcbp/protocol/unsigned_leb128.h> #include <sstream> DiskDocKey::DiskDocKey(const DocKey& key, bool prepared) { uint8_t keyOffset = 0; if (prepared) { // 1 byte for Prepare prefix keydata.resize(1); keydata[0] = CollectionID::DurabilityPrepare; keyOffset++; } if (key.getEncoding() == DocKeyEncodesCollectionId::No) { // 1 byte for the Default CollectionID keydata.resize(keyOffset + 1); keydata[keyOffset] = DefaultCollectionLeb128Encoded; keyOffset++; } keydata.resize(keyOffset + key.size()); std::copy(key.data(), key.data() + key.size(), keydata.begin() + keyOffset); } DiskDocKey::DiskDocKey(const Item& item) : DiskDocKey(item.getKey(), item.isPending() || item.isAbort() /*Prepare namespace?*/) { } DiskDocKey::DiskDocKey(const char* ptr, size_t len) : keydata(ptr, len) { } std::size_t DiskDocKey::hash() const { return std::hash<std::string>()(keydata); } DocKey DiskDocKey::getDocKey() const { // Skip past Prepared prefix if present. const auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); if (decoded.first == CollectionID::DurabilityPrepare) { return {decoded.second.data(), decoded.second.size(), DocKeyEncodesCollectionId::Yes}; } return {data(), size(), DocKeyEncodesCollectionId::Yes}; } bool DiskDocKey::isCommitted() const { return !isPrepared(); } bool DiskDocKey::isPrepared() const { const auto prefix = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); return prefix.first == CollectionID::DurabilityPrepare; } std::string DiskDocKey::to_string() const { std::stringstream ss; auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); if (decoded.first == CollectionID::DurabilityPrepare) { ss << "pre:"; decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( decoded.second); } ss << "cid:0x" << std::hex << decoded.first << std::dec << ":" << std::string(reinterpret_cast<const char*>(decoded.second.data()), decoded.second.size()); return ss.str(); }
33.428571
80
0.642998
hrajput89
a144165b6dc1368ad2c104a8d0c850aaa57af5f1
15,475
cpp
C++
transit/transit_graph_data.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
transit/transit_graph_data.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
transit/transit_graph_data.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#include "transit/transit_graph_data.hpp" #include "transit/transit_serdes.hpp" #include "base/assert.hpp" #include "base/checked_cast.hpp" #include "base/logging.hpp" #include "base/stl_helpers.hpp" #include "base/string_utils.hpp" #include <algorithm> #include <iterator> #include <set> #include "defines.hpp" using namespace routing; using namespace routing::transit; using namespace std; namespace { struct ClearVisitor { template<typename Cont> void operator()(Cont & c, char const * /* name */) const { c.clear(); } }; struct SortVisitor { template<typename Cont> void operator()(Cont & c, char const * /* name */) const { sort(c.begin(), c.end()); } }; struct CheckValidVisitor { template <typename Cont> void operator()(Cont const & c, char const * name) { CheckValid(c, name); } }; struct CheckUniqueVisitor { template <typename Cont> void operator()(Cont const & c, char const * name) { CheckUnique(c, name); } }; struct CheckSortedVisitor { template <typename Cont> void operator()(Cont const & c, char const * name) { CheckSorted(c, name); } }; template<typename T> void Append(vector<T> const & src, vector<T> & dst) { dst.insert(dst.end(), src.begin(), src.end()); } bool HasStop(vector<Stop> const & stops, StopId stopId) { return binary_search(stops.cbegin(), stops.cend(), Stop(stopId)); } /// \brief Removes from |items| all items which stop ids is not contained in |stops|. /// \note This method keeps relative order of |items|. template <class Item> void ClipItemsByStops(vector<Stop> const & stops, vector<Item> & items) { CHECK(is_sorted(stops.cbegin(), stops.cend()), ()); vector<Item> itemsToFill; for (auto const & item : items) { for (auto const stopId : item.GetStopIds()) { if (HasStop(stops, stopId)) { itemsToFill.push_back(item); break; } } } items.swap(itemsToFill); } /// \returns ref to an item at |items| by |id|. /// \note |items| must be sorted before a call of this method. template <class Id, class Item> Item const & FindById(vector<Item> const & items, Id id) { auto const s1Id = equal_range(items.cbegin(), items.cend(), Item(id)); CHECK_EQUAL(distance(s1Id.first, s1Id.second), 1, ("An item with id:", id, "is not unique or there's not such item. items:", items)); return *s1Id.first; } /// \brief Fills |items| with items which have ids from |ids|. /// \note |items| must be sorted before a call of this method. template <class Id, class Item> void UpdateItems(set<Id> const & ids, vector<Item> & items) { vector<Item> itemsToFill; for (auto const id : ids) itemsToFill.push_back(FindById(items, id)); SortVisitor{}(itemsToFill, nullptr /* name */); items.swap(itemsToFill); } template <class Item> void ReadItems(uint32_t start, uint32_t end, string const & name, NonOwningReaderSource & src, vector<Item> & items) { Deserializer<NonOwningReaderSource> deserializer(src); CHECK_EQUAL(src.Pos(), start, ("Wrong", TRANSIT_FILE_TAG, "section format. Table name:", name)); deserializer(items); CHECK_EQUAL(src.Pos(), end, ("Wrong", TRANSIT_FILE_TAG, "section format. Table name:", name)); CheckValidSortedUnique(items, name); } } // namespace namespace routing { namespace transit { // DeserializerFromJson --------------------------------------------------------------------------- DeserializerFromJson::DeserializerFromJson(json_struct_t * node, OsmIdToFeatureIdsMap const & osmIdToFeatureIds) : m_node(node), m_osmIdToFeatureIds(osmIdToFeatureIds) { } void DeserializerFromJson::operator()(m2::PointD & p, char const * name) { // @todo(bykoianko) Instead of having a special operator() method for m2::PointD class it's // necessary to add Point class to transit_types.hpp and process it in DeserializerFromJson with // regular method. json_t * item = nullptr; if (name == nullptr) item = m_node; // Array item case else item = base::GetJSONObligatoryField(m_node, name); CHECK(json_is_object(item), ("Item is not a json object:", name)); FromJSONObject(item, "x", p.x); FromJSONObject(item, "y", p.y); } void DeserializerFromJson::operator()(FeatureIdentifiers & id, char const * name) { // Conversion osm id to feature id. string osmIdStr; GetField(osmIdStr, name); uint64_t osmIdNum; CHECK(strings::to_uint64(osmIdStr, osmIdNum), ("Cann't convert osm id string:", osmIdStr, "to a number.")); base::GeoObjectId const osmId(osmIdNum); auto const it = m_osmIdToFeatureIds.find(osmId); if (it != m_osmIdToFeatureIds.cend()) { CHECK(!it->second.empty(), ("Osm id:", osmId, "(encoded", osmId.GetEncodedId(), ") from transit graph does not correspond to any feature.")); if (it->second.size() != 1) { // Note. |osmId| corresponds to several feature ids. It may happen in case of stops, // if a stop is present as a relation. It's a rare case. LOG(LWARNING, ("Osm id:", osmId, "( encoded", osmId.GetEncodedId(), ") corresponds to", it->second.size(), "feature ids.")); } id.SetFeatureId(it->second[0]); } id.SetOsmId(osmId.GetEncodedId()); } void DeserializerFromJson::operator()(EdgeFlags & edgeFlags, char const * name) { bool transfer = false; (*this)(transfer, name); // Note. Only |transfer| field of |edgeFlags| may be set at this point because the // other fields of |edgeFlags| are unknown. edgeFlags.SetFlags(0); edgeFlags.m_transfer = transfer; } void DeserializerFromJson::operator()(StopIdRanges & rs, char const * name) { vector<StopId> stopIds; (*this)(stopIds, name); rs = StopIdRanges({stopIds}); } // GraphData -------------------------------------------------------------------------------------- void GraphData::DeserializeFromJson(base::Json const & root, OsmIdToFeatureIdsMap const & mapping) { DeserializerFromJson deserializer(root.get(), mapping); Visit(deserializer); // Removes equivalent edges from |m_edges|. If there are several equivalent edges only // the most lightweight edge is left. // Note. It's possible that two stops are connected with the same line several times // in the same direction. It happens in Oslo metro (T-banen): // https://en.wikipedia.org/wiki/Oslo_Metro#/media/File:Oslo_Metro_Map.svg branch 5. base::SortUnique(m_edges, [](Edge const & e1, Edge const & e2) { if (e1 != e2) return e1 < e2; return e1.GetWeight() < e2.GetWeight(); }, [](Edge const & e1, Edge const & e2) { return e1 == e2; }); } void GraphData::Serialize(Writer & writer) { auto const startOffset = writer.Pos(); Serializer<Writer> serializer(writer); FixedSizeSerializer<Writer> numberSerializer(writer); m_header.Reset(); numberSerializer(m_header); m_header.m_stopsOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_stops); m_header.m_gatesOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_gates); m_header.m_edgesOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_edges); m_header.m_transfersOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_transfers); m_header.m_linesOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_lines); m_header.m_shapesOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_shapes); m_header.m_networksOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); serializer(m_networks); m_header.m_endOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset); // Rewriting header info. CHECK(m_header.IsValid(), (m_header)); auto const endOffset = writer.Pos(); writer.Seek(startOffset); numberSerializer(m_header); writer.Seek(endOffset); LOG(LINFO, (TRANSIT_FILE_TAG, "section is ready. Header:", m_header)); } void GraphData::DeserializeAll(Reader & reader) { DeserializeWith(reader, [this](NonOwningReaderSource & src) { ReadStops(src); ReadGates(src); ReadEdges(src); ReadTransfers(src); ReadLines(src); ReadShapes(src); ReadNetworks(src); }); } void GraphData::DeserializeForRouting(Reader & reader) { DeserializeWith(reader, [this](NonOwningReaderSource & src) { ReadStops(src); ReadGates(src); ReadEdges(src); src.Skip(m_header.m_linesOffset - src.Pos()); ReadLines(src); }); } void GraphData::DeserializeForRendering(Reader & reader) { DeserializeWith(reader, [this](NonOwningReaderSource & src) { ReadStops(src); src.Skip(m_header.m_transfersOffset - src.Pos()); ReadTransfers(src); ReadLines(src); ReadShapes(src); }); } void GraphData::DeserializeForCrossMwm(Reader & reader) { DeserializeWith(reader, [this](NonOwningReaderSource & src) { ReadStops(src); src.Skip(m_header.m_edgesOffset - src.Pos()); ReadEdges(src); }); } void GraphData::AppendTo(GraphData const & rhs) { ::Append(rhs.m_stops, m_stops); ::Append(rhs.m_gates, m_gates); ::Append(rhs.m_edges, m_edges); ::Append(rhs.m_transfers, m_transfers); ::Append(rhs.m_lines, m_lines); ::Append(rhs.m_shapes, m_shapes); ::Append(rhs.m_networks, m_networks); } void GraphData::Clear() { ClearVisitor const v{}; Visit(v); } void GraphData::CheckValidSortedUnique() const { { CheckSortedVisitor v; Visit(v); } { CheckUniqueVisitor v; Visit(v); } { CheckValidVisitor v; Visit(v); } } bool GraphData::IsEmpty() const { // Note. |m_transfers| may be empty if GraphData instance is not empty. return m_stops.empty() || m_gates.empty() || m_edges.empty() || m_lines.empty() || m_shapes.empty() || m_networks.empty(); } void GraphData::Sort() { SortVisitor const v{}; Visit(v); } void GraphData::ClipGraph(vector<m2::RegionD> const & borders) { Sort(); CheckValidSortedUnique(); ClipLines(borders); ClipStops(); ClipNetworks(); ClipGates(); ClipTransfer(); ClipEdges(); ClipShapes(); CheckValidSortedUnique(); } void GraphData::SetGateBestPedestrianSegment(size_t gateIdx, SingleMwmSegment const & s) { CHECK_LESS(gateIdx, m_gates.size(), ()); m_gates[gateIdx].SetBestPedestrianSegment(s); } void GraphData::ClipLines(vector<m2::RegionD> const & borders) { // Set with stop ids with stops which are inside |borders|. set<StopId> stopIdInside; for (auto const & stop : m_stops) { if (m2::RegionsContain(borders, stop.GetPoint())) stopIdInside.insert(stop.GetId()); } set<StopId> hasNeighborInside; for (auto const & edge : m_edges) { auto const stop1Inside = stopIdInside.count(edge.GetStop1Id()) != 0; auto const stop2Inside = stopIdInside.count(edge.GetStop2Id()) != 0; if (stop1Inside && !stop2Inside) hasNeighborInside.insert(edge.GetStop2Id()); if (stop2Inside && !stop1Inside) hasNeighborInside.insert(edge.GetStop1Id()); } stopIdInside.insert(hasNeighborInside.cbegin(), hasNeighborInside.cend()); // Filling |lines| with stops inside |borders|. vector<Line> lines; for (auto const & line : m_lines) { // Note. |stopIdsToFill| will be filled with continuous sequences of stop ids. // In most cases only one sequence of stop ids should be placed to |stopIdsToFill|. // But if a line is split by |borders| several times then several // continuous groups of stop ids will be placed to |stopIdsToFill|. // The loop below goes through all the stop ids belong the line |line| and // keeps in |stopIdsToFill| continuous groups of stop ids which are inside |borders|. Ranges stopIdsToFill; Ranges const & ranges = line.GetStopIds(); CHECK_EQUAL(ranges.size(), 1, ()); vector<StopId> const & stopIds = ranges[0]; auto it = stopIds.begin(); while (it != stopIds.end()) { while (it != stopIds.end() && stopIdInside.count(*it) == 0) ++it; auto jt = it; while (jt != stopIds.end() && stopIdInside.count(*jt) != 0) ++jt; if (it != jt) stopIdsToFill.emplace_back(it, jt); it = jt; } if (!stopIdsToFill.empty()) { lines.emplace_back(line.GetId(), line.GetNumber(), line.GetTitle(), line.GetType(), line.GetColor(), line.GetNetworkId(), stopIdsToFill, line.GetInterval()); } } m_lines.swap(lines); } void GraphData::ClipStops() { CHECK(is_sorted(m_stops.cbegin(), m_stops.cend()), ()); set<StopId> stopIds; for (auto const & line : m_lines) { for (auto const & range : line.GetStopIds()) stopIds.insert(range.cbegin(), range.cend()); } UpdateItems(stopIds, m_stops); } void GraphData::ClipNetworks() { CHECK(is_sorted(m_networks.cbegin(), m_networks.cend()), ()); set<NetworkId> networkIds; for (auto const & line : m_lines) networkIds.insert(line.GetNetworkId()); UpdateItems(networkIds, m_networks); } void GraphData::ClipGates() { ClipItemsByStops(m_stops, m_gates); } void GraphData::ClipTransfer() { ClipItemsByStops(m_stops, m_transfers); } void GraphData::ClipEdges() { CHECK(is_sorted(m_stops.cbegin(), m_stops.cend()), ()); vector<Edge> edges; for (auto const & edge : m_edges) { if (HasStop(m_stops, edge.GetStop1Id()) && HasStop(m_stops, edge.GetStop2Id())) edges.push_back(edge); } SortVisitor{}(edges, nullptr /* name */); m_edges.swap(edges); } void GraphData::ClipShapes() { CHECK(is_sorted(m_edges.cbegin(), m_edges.cend()), ()); // Set with shape ids contained in m_edges. set<ShapeId> shapeIdInEdges; for (auto const & edge : m_edges) { auto const & shapeIds = edge.GetShapeIds(); shapeIdInEdges.insert(shapeIds.cbegin(), shapeIds.cend()); } vector<Shape> shapes; for (auto const & shape : m_shapes) { if (shapeIdInEdges.count(shape.GetId()) != 0) shapes.push_back(shape); } m_shapes.swap(shapes); } void GraphData::ReadHeader(NonOwningReaderSource & src) { FixedSizeDeserializer<NonOwningReaderSource> numberDeserializer(src); numberDeserializer(m_header); CHECK_EQUAL(src.Pos(), m_header.m_stopsOffset, ("Wrong", TRANSIT_FILE_TAG, "section format.")); CHECK(m_header.IsValid(), ()); } void GraphData::ReadStops(NonOwningReaderSource & src) { ReadItems(m_header.m_stopsOffset, m_header.m_gatesOffset, "stops", src, m_stops); } void GraphData::ReadGates(NonOwningReaderSource & src) { ReadItems(m_header.m_gatesOffset, m_header.m_edgesOffset, "gates", src, m_gates); } void GraphData::ReadEdges(NonOwningReaderSource & src) { ReadItems(m_header.m_edgesOffset, m_header.m_transfersOffset, "edges", src, m_edges); } void GraphData::ReadTransfers(NonOwningReaderSource & src) { ReadItems(m_header.m_transfersOffset, m_header.m_linesOffset, "transfers", src, m_transfers); } void GraphData::ReadLines(NonOwningReaderSource & src) { ReadItems(m_header.m_linesOffset, m_header.m_shapesOffset, "lines", src, m_lines); } void GraphData::ReadShapes(NonOwningReaderSource & src) { ReadItems(m_header.m_shapesOffset, m_header.m_networksOffset, "shapes", src, m_shapes); } void GraphData::ReadNetworks(NonOwningReaderSource & src) { ReadItems(m_header.m_networksOffset, m_header.m_endOffset, "networks", src, m_networks); } } // namespace transit } // namespace routing
28.085299
99
0.675735
smartyw
a145de89d4dd625c605d25cde097f39edeed0ec3
420
hpp
C++
pythran/pythonic/__builtin__/list/count.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/list/count.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/list/count.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_BUILTIN_LIST_COUNT_HPP #define PYTHONIC_BUILTIN_LIST_COUNT_HPP #include "pythonic/include/__builtin__/list/count.hpp" #include "pythonic/__dispatch__/count.hpp" #include "pythonic/utils/proxy.hpp" namespace pythonic { namespace __builtin__ { namespace list { ALIAS(count, pythonic::__dispatch__::count); PROXY_IMPL(pythonic::__builtin__::list, count); } } } #endif
16.153846
54
0.738095
artas360
a14afec67d4ea5ccf1a6c3c9dbdaecd1a93af368
671
hpp
C++
src/datastructures/boost.hpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/datastructures/boost.hpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
src/datastructures/boost.hpp
rvanvenetie/spacetime
b516419be2a59115d9b2d853aeea9fcd4f125c94
[ "MIT" ]
null
null
null
#pragma once #include <boost/container/deque.hpp> #include <boost/container/options.hpp> #include <boost/container/small_vector.hpp> #include <boost/container/static_vector.hpp> template <typename I, size_t N> using SmallVector = boost::container::small_vector<I, N>; template <typename I, size_t N> using StaticVector = boost::container::static_vector<I, N>; // Boost deque container with default block size N. (REQUIRES LATEST BOOST). template <typename I, size_t N = 128> using Deque = boost::container::deque<I, void, typename boost::container::deque_options< boost::container::block_size<N>>::type>;
37.277778
76
0.692996
rvanvenetie
a1567eda4a122071dce708a5314751c64b9599e6
10,663
cpp
C++
src/hsa_balance.cpp
TheRobotStudio/osa_control
cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c
[ "BSD-3-Clause" ]
null
null
null
src/hsa_balance.cpp
TheRobotStudio/osa_control
cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c
[ "BSD-3-Clause" ]
null
null
null
src/hsa_balance.cpp
TheRobotStudio/osa_control
cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019, The Robot Studio * 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. */ /** * @file hsa_balance.cpp * @author Cyril Jourdan * @author Rob Knight * @date Sept 18, 2017 * @version 0.1.0 * @brief Implementation file for the High Speed Android balance algorithm * * Contact: contact@therobotstudio.com * Created on : Sept 18, 2017 */ #include <exception> #include <stdexcept> //ROS #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <osa_control/hsa_balance_dyn_Config.h> //ROS messages #include <sensor_msgs/Joy.h> #include <razor_imu_9dof/RazorImu.h> #include <osa_msgs/MotorCmdMultiArray.h> #include <osa_msgs/MotorDataMultiArray.h> #include "robot_defines.h" /*** Defines ***/ #define LOOP_RATE 15 //HEART_BEAT #define NUMBER_OF_WHEELS 2 #define NUMBER_OF_MOTORS 10 using namespace std; /*** Global variables ***/ osa_control::hsa_balance_dyn_Config pid_param; sensor_msgs::Joy xbox_joy; razor_imu_9dof::RazorImu razor_imu; osa_msgs::MotorDataMultiArray motor_data_array; osa_msgs::MotorCmdMultiArray motor_cmd_array; bool joy_arrived = false; bool imu_arrived = false; bool motor_data_array_arrived = true; /*** Callback functions ***/ void HSABalanceDynCallback(osa_control::hsa_balance_dyn_Config &config, uint32_t level) { ROS_INFO("Reconfigure Request: %f %f %f %f", config.p_double_param, config.i_double_param, config.d_double_param, config.pt_double_param); pid_param = config; } void joyCallback(const sensor_msgs::JoyConstPtr& joy) { xbox_joy = *joy; joy_arrived = true; } void imuRawCallback(const razor_imu_9dof::RazorImuConstPtr& imu) { razor_imu = *imu; imu_arrived = true; } void motorDataArrayCallback(const osa_msgs::MotorDataMultiArrayConstPtr& data) { motor_data_array = *data; motor_data_array_arrived = true; } /*** Main ***/ int main(int argc, char** argv) { //Initialize ROS ros::init(argc, argv, "osa_hsa_balance_node"); ros::NodeHandle nh("~"); ros::Rate r(LOOP_RATE); // Parameters string dof_wheel_name[NUMBER_OF_WHEELS]; int joy_axis_left_right_idx, joy_axis_up_down_idx; ROS_INFO("OSA High Speed Android balance node."); ROS_INFO("Setup dynamic_reconfigure parameters."); dynamic_reconfigure::Server<osa_control::hsa_balance_dyn_Config> hsa_balance_dyn_server; dynamic_reconfigure::Server<osa_control::hsa_balance_dyn_Config>::CallbackType f; f = boost::bind(&HSABalanceDynCallback, _1, _2); hsa_balance_dyn_server.setCallback(f); ROS_INFO("Grab the parameters."); // Grab the parameters try { nh.param("dof_right_wheel", dof_wheel_name[0], string("/dof1")); nh.param("dof_left_wheel", dof_wheel_name[1], string("/dof2")); nh.param("joy_axis_left_right", joy_axis_left_right_idx, 3); nh.param("joy_axis_up_down", joy_axis_up_down_idx, 4); } catch(ros::InvalidNameException const &e) { ROS_ERROR(e.what()); } string name[NUMBER_OF_WHEELS]; string type[NUMBER_OF_WHEELS]; int node_id[NUMBER_OF_WHEELS] = {0}; string controller[NUMBER_OF_WHEELS]; string motor[NUMBER_OF_WHEELS]; bool inverted[NUMBER_OF_WHEELS]; string mode[NUMBER_OF_WHEELS]; int value[NUMBER_OF_WHEELS] = {0}; //Publishers ros::Publisher pub_motor_cmd_array = nh.advertise<osa_msgs::MotorCmdMultiArray>("/set_motor_commands", 100); //Subscribers ros::Subscriber sub_joy = nh.subscribe ("/joy", 10, joyCallback); ros::Subscriber sub_imu = nh.subscribe ("/imuRaw", 10, imuRawCallback); ros::Subscriber sub_motor_data_array = nh.subscribe("/motor_data_array", 10, motorDataArrayCallback); // Grab the parameters try { //start with controller 1 //int dof_idx = 1; //string rad_str = "dof"; //common radical name for(int i=0; i<NUMBER_OF_WHEELS; i++) { //create the string "controller+index" to search for the controller parameter with that index number ostringstream dof_idx_path; dof_idx_path << dof_wheel_name[i]; //rad_str << dof_idx; string absolute_str = "absolute_str"; ROS_INFO("string=%s", dof_idx_path.str().c_str()); if(nh.searchParam(dof_idx_path.str(), absolute_str)) { //grab the parameters of the current controller //name ostringstream name_path; name_path << absolute_str << "/name"; if(!nh.getParam(name_path.str(), name[i])) { ROS_ERROR("Can't grab param name for %s", dof_idx_path.str().c_str()); return false; } //type ostringstream type_path; type_path << absolute_str << "/type"; if(!nh.getParam(type_path.str(), type[i])) { ROS_ERROR("Can't grab param type for %s", dof_idx_path.str().c_str()); return false; } /* //check that the type is "WHEEL" if(type[i] == string("WHEEL")) { throw runtime_error("Selected DOF is not of type WHEEL."); } */ //node_id ostringstream node_id_path; node_id_path << absolute_str << "/node_id"; if(!nh.getParam(node_id_path.str(), node_id[i])) { ROS_ERROR("Can't grab param node_id for %s", dof_idx_path.str().c_str()); return false; } //controller ostringstream controller_path; controller_path << absolute_str << "/controller"; if(!nh.getParam(controller_path.str(), controller[i])) { ROS_ERROR("Can't grab param controller for %s", dof_idx_path.str().c_str()); return false; } //motor ostringstream motor_path; motor_path << absolute_str << "/motor"; if(!nh.getParam(motor_path.str(), motor[i])) { ROS_ERROR("Can't grab param motor for %s", dof_idx_path.str().c_str()); return false; } //inverted ostringstream inverted_path; inverted_path << absolute_str << "/inverted"; if(!nh.getParam(inverted_path.str(), inverted[i])) { ROS_ERROR("Can't grab param inverted for %s", dof_idx_path.str().c_str()); return false; } //mode ostringstream mode_path; mode_path << absolute_str << "/mode"; if(!nh.getParam(mode_path.str(), mode[i])) { ROS_ERROR("Can't grab param mode for %s", dof_idx_path.str().c_str()); return false; } //value ostringstream value_path; value_path << absolute_str << "/value"; if(!nh.getParam(value_path.str(), value[i])) { ROS_ERROR("Can't grab param value for %s", dof_idx_path.str().c_str()); return false; } //print the dof parameters ROS_INFO("%s : name[%s], type[%s], node_id[%d], controller[%s], motor[%s], inverted[%d], mode[%s], value[%d]", dof_idx_path.str().c_str(), name[i].c_str(), type[i].c_str(), node_id[i], controller[i].c_str(), motor[i].c_str(), inverted[i], mode[i].c_str(), value[i]); } else { //dof_exist = false; ROS_WARN("Controllers not found in YAML config file"); } //dof_exist = false; } ROS_INFO("Wheels parameters found successfully!\n"); } catch(ros::InvalidNameException const &e) { ROS_ERROR(e.what()); ROS_ERROR("Wrong parameters in config file or launch file!"); ROS_ERROR("Please modify your YAML config file or launch file and try again."); return false; } //create the command array motor_cmd_array.layout.dim.push_back(std_msgs::MultiArrayDimension()); motor_cmd_array.layout.dim[0].size = NUMBER_OF_MOTORS; motor_cmd_array.layout.dim[0].stride = NUMBER_OF_MOTORS; motor_cmd_array.layout.dim[0].label = "motors"; motor_cmd_array.layout.data_offset = 0; motor_cmd_array.motor_cmd.clear(); motor_cmd_array.motor_cmd.resize(NUMBER_OF_MOTORS); //Initialization for(int i=0; i<NUMBER_OF_MOTORS; i++) { motor_cmd_array.motor_cmd[i].node_id = i+1; motor_cmd_array.motor_cmd[i].command = SET_TARGET_POSITION; motor_cmd_array.motor_cmd[i].value = 0; } motor_cmd_array.motor_cmd[8].command = SET_TARGET_VELOCITY; //For the drive wheels motor_cmd_array.motor_cmd[9].command = SET_TARGET_VELOCITY; /* Main loop */ ROS_INFO("Main loop"); while(ros::ok()) { // Get imu and motor data through callbacks. ros::spinOnce(); if(joy_arrived) //Will only be true if values have changed { //Joystick control //xbox_joy.buttons[0]; //xbox_joy.axes[0]; } // Check that both imu and motor data has arrived. if(imu_arrived && motor_data_array_arrived) { //--------------------- PID loop --------------------- // Variables float angle = razor_imu.pitch; //in rad float velocity_f = 0.0; int velocity_i = 0; float dt = 1/LOOP_RATE; //PID parameters are accessed with config.p_double_param, config.i_double_param, config.d_double_param. //Pitch Trim parameter is accessed with config.pt_double_param // Computation velocity_f = -(angle*4000)/M_PI; velocity_i = (int)velocity_f; // Print velocity value ROS_INFO("angle = %f, velocity = %d", angle, velocity_i); // Set final motor velocity motor_cmd_array.motor_cmd[8].value = velocity_i; motor_cmd_array.motor_cmd[9].value = velocity_i; // Publish the motor commands topic, caught by the command_builder node // which send it to the CAN bus via topic_to_socketcan_node pub_motor_cmd_array.publish(motor_cmd_array); } imu_arrived = false; motor_data_array_arrived = false; joy_arrived = false; if(!r.sleep()) ROS_WARN("sleep: desired rate %dhz not met!", LOOP_RATE); }//while ros ok return 0; }
30.640805
142
0.710119
TheRobotStudio
a15896da6718b2d3f177743e26947b189a98205b
7,119
cc
C++
code/Modules/HTTP/pnacl/pnaclURLLoader.cc
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
code/Modules/HTTP/pnacl/pnaclURLLoader.cc
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
code/Modules/HTTP/pnacl/pnaclURLLoader.cc
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // pnaclURLLoader.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "pnaclURLLoader.h" #include "Core/pnacl/pnaclInstance.h" #include "IO/Stream/MemoryStream.h" #include <ppapi/cpp/module.h> #include <ppapi/cpp/completion_callback.h> #include <ppapi/cpp/url_request_info.h> #include <ppapi/cpp/url_response_info.h> #include <ppapi/cpp/url_loader.h> namespace Oryol { namespace _priv { // a helper class to wrap all request-related data into a ref-counted object class pnaclRequestWrapper : public RefCounted { OryolClassPoolAllocDecl(pnaclRequestWrapper); public: pnaclRequestWrapper(Ptr<HTTPProtocol::HTTPRequest> req) { this->httpRequest = req; pp::Instance* ppInst = pnaclInstance::Instance(); this->ppUrlRequestInfo = pp::URLRequestInfo(ppInst); this->ppUrlRequestInfo.SetMethod("GET"); String urlPath = req->GetURL().PathToEnd(); this->ppUrlRequestInfo.SetURL(urlPath.AsCStr()); this->ppUrlLoader = pp::URLLoader(ppInst); }; virtual ~pnaclRequestWrapper() { this->httpRequest = nullptr; this->ppUrlLoader = pp::URLLoader(); this->ppUrlRequestInfo = pp::URLRequestInfo(); } void readBodyData() { const Ptr<Stream>& responseBody = this->httpRequest->GetResponse()->GetBody(); if (!responseBody->IsOpen()) { responseBody->Open(OpenMode::WriteOnly); } pp::CompletionCallback cc = pp::CompletionCallback(pnaclURLLoader::cbOnRead, this); int32_t result = PP_OK; do { result = this->ppUrlLoader.ReadResponseBody(this->readBuffer, ReadBufferSize, cc); if (result > 0) { responseBody->Write(this->readBuffer, result); } } while (result > 0); if (PP_OK_COMPLETIONPENDING != result) { cc.Run(result); } } Ptr<HTTPProtocol::HTTPRequest> httpRequest; pp::URLRequestInfo ppUrlRequestInfo; pp::URLLoader ppUrlLoader; static const int32 ReadBufferSize = 4096; uint8 readBuffer[ReadBufferSize]; }; OryolClassPoolAllocImpl(pnaclRequestWrapper); //------------------------------------------------------------------------------ // FIXME FIXME FIXME // Properly handle cancelled messages. // void pnaclURLLoader::doWork() { while (!this->requestQueue.Empty()) { this->startRequest(this->requestQueue.Dequeue()); } } //------------------------------------------------------------------------------ void pnaclURLLoader::startRequest(const Ptr<HTTPProtocol::HTTPRequest>& req) { o_assert(req.isValid() && !req->Handled()); // currently only support GET o_assert(req->GetMethod() == HTTPMethod::Get); // bump the requests refcount and get a raw pointer HTTPProtocol::HTTPRequest* reqPtr = req.get(); reqPtr->addRef(); // fire off main-thread callback to create and send the HTTP request pp::Module::Get()->core()->CallOnMainThread(0, pp::CompletionCallback(cbSendRequest, reqPtr)); } //------------------------------------------------------------------------------ void pnaclURLLoader::cbSendRequest(void* data, int32_t /*result*/) { o_assert(pp::Module::Get()->core()->IsMainThread()); // FIXME: support request headers, support methods other then GET, // support request body Ptr<HTTPProtocol::HTTPRequest> httpRequest = (HTTPProtocol::HTTPRequest*) data; auto req = pnaclRequestWrapper::Create(httpRequest); httpRequest->release(); req->addRef(); pnaclRequestWrapper* reqPtr = req.get(); ORYOL_UNUSED int32_t openResult = req->ppUrlLoader.Open(req->ppUrlRequestInfo, pp::CompletionCallback(cbRequestComplete, reqPtr)); o_assert(PP_OK_COMPLETIONPENDING == openResult); } //------------------------------------------------------------------------------ void pnaclURLLoader::cbRequestComplete(void* data, int32_t result) { o_assert(PP_OK == result); Ptr<pnaclRequestWrapper> req((pnaclRequestWrapper*)data); // create a response object, and a memory stream object which // will hold the received data auto httpResponse = HTTPProtocol::HTTPResponse::Create(); req->httpRequest->SetResponse(httpResponse); Ptr<MemoryStream> httpResponseBody = MemoryStream::Create(); httpResponseBody->SetURL(req->httpRequest->GetURL()); httpResponse->SetBody(httpResponseBody); // translate response o_assert(!req->ppUrlLoader.is_null()); o_assert(!req->ppUrlLoader.GetResponseInfo().is_null()); IOStatus::Code httpStatus = (IOStatus::Code) req->ppUrlLoader.GetResponseInfo().GetStatusCode(); httpResponse->SetStatus(httpStatus); if (httpStatus == IOStatus::OK) { // response header received ok, start loading response body, // first get the immediately available data now, and maybe // do async call to fetch the rest req->readBodyData(); } else { // HTTP error, dump a warning, and cleanup Log::Warn("pnaclURLLoader::cbRequestComplete: GET '%s' returned with '%d'\n", req->httpRequest->GetURL().AsCStr(), httpStatus); auto ioReq = req->httpRequest->GetIoRequest(); if (ioReq) { auto httpResponse = req->httpRequest->GetResponse(); ioReq->SetStatus(httpResponse->GetStatus()); ioReq->SetHandled(); } req->httpRequest->SetHandled(); req->release(); } } //------------------------------------------------------------------------------ void pnaclURLLoader::cbOnRead(void* data, int32_t result) { Ptr<pnaclRequestWrapper> req((pnaclRequestWrapper*)data); if (PP_OK == result) { // all data received req->httpRequest->GetResponse()->GetBody()->Close(); auto ioReq = req->httpRequest->GetIoRequest(); if (ioReq) { auto httpResponse = req->httpRequest->GetResponse(); ioReq->SetStatus(httpResponse->GetStatus()); ioReq->SetStream(httpResponse->GetBody()); ioReq->SetErrorDesc(httpResponse->GetErrorDesc()); ioReq->SetHandled(); } req->httpRequest->SetHandled(); req->release(); return; } else if (result > 0) { // read all available data... req->httpRequest->GetResponse()->GetBody()->Write(req->readBuffer, result); req->readBodyData(); } else { // an error occurred Log::Warn("pnaclURLLoader::cbOnRead: Error while reading body data.\n"); req->httpRequest->GetResponse()->SetStatus(IOStatus::DownloadError); auto ioReq = req->httpRequest->GetIoRequest(); if (ioReq) { auto httpResponse = req->httpRequest->GetResponse(); ioReq->SetStatus(httpResponse->GetStatus()); ioReq->SetHandled(); } req->httpRequest->SetHandled(); req->release(); return; } } } // namespace _priv } // namespace Oryol
37.078125
134
0.597977
waywardmonkeys
a15aeebbf3a10b8093e2aab3fe289f48403d4884
11,028
cc
C++
ssTableCache.cc
q4x3/KVStore
51190a9487d32f26046de4638f6b8d1b85fbc079
[ "MIT" ]
null
null
null
ssTableCache.cc
q4x3/KVStore
51190a9487d32f26046de4638f6b8d1b85fbc079
[ "MIT" ]
null
null
null
ssTableCache.cc
q4x3/KVStore
51190a9487d32f26046de4638f6b8d1b85fbc079
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <algorithm> #include <queue> #include "utils.h" #include "ssTableCache.h" std::vector<entryForMerge> ssTableCache::genSortedEntry(std::vector<uint64_t> &&keyArray, ssTable *table) { std::vector<entryForMerge> res; for (uint32_t i = 0; i < keyArray.size(); ++i) { res.emplace_back(keyArray[i], i, table); } return res; } void ssTableCache::mergesort(std::vector<entryForMerge> &array, uint64_t start, uint64_t end) { uint64_t mid = (start + end) >> 1; if (end <= start) return; mergesort(array, start, mid); mergesort(array, mid + 1, end); uint64_t i = start, j = mid + 1, k = 0; std::vector<entryForMerge> tmpArray(end - start + 1); while (i <= mid && j <= end) { if (array[i].key > array[j].key) tmpArray[k++] = array[j++]; else tmpArray[k++] = array[i++]; } while (i <= mid) tmpArray[k++] = array[i++]; while (j <= end) tmpArray[k++] = array[j++]; for (i = start, k = 0; i <= end; ++i, ++k) { array[i] = tmpArray[k]; } } void ssTableCache::compaction(uint32_t targetLevel, std::vector<ssTable *> &targetCells) { std::vector<entryForMerge> array; std::vector<entryForMerge> uniqueArray; for (auto &it: targetCells) { auto tmp = genSortedEntry(it->getKeySeq(), it); array.insert(array.cend(), tmp.cbegin(), tmp.cend()); } mergesort(array, 0, array.size() - 1); uint32_t lastInd = 0; for (uint32_t i = 1; i < array.size(); ++i) { if (array[i].key != array[lastInd].key) { uniqueArray.emplace_back(array[lastInd]); lastInd = i; } else { if (array[i].table->header.timeStamp > array[lastInd].table->header.timeStamp) { lastInd = i; } } } uniqueArray.emplace_back(array[lastInd]); array.clear(); std::vector<std::pair<uint64_t, std::string>> tmp; const uint32_t MAX_SIZE = 2 * 1024 * 1024 - sstableHeader::HEADER_SIZE - bloomFilter::FILTER_SIZE; uint64_t tmpTimeStamp = 0; uint32_t tmpSize = 0; bool needHandleDeleteFlag = targetLevel >= levelArray.size() - 1; for (auto &it: uniqueArray) { std::string val = it.table->getValInd(it.ind); if (needHandleDeleteFlag && val == DELETE_FLAG) { continue; } if (tmpSize + val.size() + sizeof (uint64_t) + sizeof (uint32_t) > MAX_SIZE) { std::string targetDir = filePath + "/level-" + std::to_string(targetLevel); if (!utils::dirExists(targetDir)) { if (utils::mkdir(targetDir.c_str())) { std::cerr << "ERROR: Fail to create directory." << std::endl; exit(1); } levelArray.emplace_back(); nextLabel.push_back(0); } std::string fileName = targetDir + '/' + std::to_string(nextLabel[targetLevel]) + ".sst"; levelArray[targetLevel].emplace_back(ssTable::genTable(fileName, tmpTimeStamp, tmp)); ++nextLabel[targetLevel]; tmp.clear(); tmpTimeStamp = 0; tmpSize = 0; } tmp.emplace_back(it.key, val); tmpSize += val.size() + sizeof (uint64_t) + sizeof (uint32_t); if (it.table->header.timeStamp > tmpTimeStamp) { tmpTimeStamp = it.table->header.timeStamp; } } if (!tmp.empty()) { std::string targetDir = filePath + "/level-" + std::to_string(targetLevel); if (!utils::dirExists(targetDir)) { if (utils::mkdir(targetDir.c_str())) { std::cerr << "ERROR: Fail to create directory." << std::endl; exit(1); } levelArray.emplace_back(); nextLabel.push_back(0); } std::string fileName = targetDir + '/' + std::to_string(nextLabel[targetLevel]) + ".sst"; levelArray[targetLevel].emplace_back(ssTable::genTable(fileName, tmpTimeStamp, tmp)); ++nextLabel[targetLevel]; tmp.clear(); } for (auto &it: targetCells) { it->clearTable(); delete it; it = nullptr; } } void ssTableCache::modify() { uint32_t level = 0; while (level < levelArray.size() && levelArray[level].size() > (0b10 << level)) { std::vector<ssTable *> targetCells; uint64_t minKey; uint64_t maxKey; if (level == 0) { minKey = levelArray[0][0]->header.minKey; maxKey = levelArray[0][0]->header.maxKey; for (auto &it: levelArray[0]) { targetCells.emplace_back(it); minKey = std::min(minKey, it->header.minKey); maxKey = std::max(maxKey, it->header.maxKey); } levelArray[0].clear(); } else { std::deque<ssTable *> &tmpCells = levelArray[level]; std::priority_queue<entryForCmp, std::vector<entryForCmp>, std::greater<>> q; for (uint32_t i = 0; i < tmpCells.size(); ++i) { q.emplace(tmpCells[i]->header.timeStamp, tmpCells[i]->header.minKey, tmpCells[i]->header.maxKey, i, tmpCells[i]); } minKey = q.top().minKey; maxKey = q.top().maxKey; std::vector<uint32_t> deleteList; uint32_t n = tmpCells.size() - (0b10 << level); while (n--) { targetCells.emplace_back(q.top().table); deleteList.emplace_back(q.top().index); minKey = std::min(minKey, q.top().minKey); maxKey = std::max(maxKey, q.top().maxKey); q.pop(); } std::sort(deleteList.begin(), deleteList.end()); auto iter = tmpCells.begin(); uint32_t iterTimes = deleteList[0]; while (iterTimes--) ++iter; iter = tmpCells.erase(iter); for (uint32_t i = 1; i < deleteList.size(); ++i) { iterTimes = deleteList[i] - deleteList[i - 1] - 1; while (iterTimes--) ++iter; iter = tmpCells.erase(iter); } } if (level + 1 < levelArray.size()) { std::deque<ssTable *> &tmpCells = levelArray[level + 1]; auto iter = tmpCells.begin(); while (iter != tmpCells.end()) { if (minKey <= (*iter)->header.maxKey && maxKey >= (*iter)->header.minKey) { targetCells.emplace_back(*iter); iter = tmpCells.erase(iter); } else { ++iter; } } } compaction(level + 1, targetCells); ++level; } } ssTableCache::ssTableCache(std::string f): filePath(std::move(f)){ if (!utils::dirExists(filePath) && utils::mkdir(filePath.c_str())) { std::cerr << "ERROR: Fail to create directory." << std::endl; exit(1); } uint64_t level = 0; std::string subDir; nextTimeStamp = 1; while (utils::dirExists(subDir = filePath + "/level-" + std::to_string(level))) { uint64_t fileNum; uint64_t nextFileNum = 0; std::vector<std::string> ret; utils::scanDir(subDir, ret); levelArray.emplace_back(); std::deque<ssTable *> &ssTableArray = levelArray[levelArray.size() - 1]; for (const auto &it: ret) { std::string subFile = subDir; subFile += "/" + it; ssTableArray.emplace_back(new ssTable); ssTableArray[ssTableArray.size() - 1]->read(subFile); uint64_t tmp = ssTableArray[ssTableArray.size() - 1]->header.timeStamp; if (tmp >= nextTimeStamp) nextTimeStamp = tmp + 1; fileNum = stoul(it.substr(0, it.find('.'))); if (nextFileNum <= fileNum) { nextFileNum = fileNum + 1; } } nextLabel.push_back(nextFileNum); ++level; } if (levelArray.empty()) { if ( utils::mkdir((filePath + "/level-0").c_str()) ) { std::cerr << "ERROR: Fail to create directory." << std::endl; exit(1); } levelArray.emplace_back(); nextLabel.push_back(0); } } ssTableCache::~ssTableCache() { for (auto & it : levelArray) { for (auto & item : it) { delete item; item = nullptr; } } } void ssTableCache::addTable(const std::vector<std::pair<uint64_t, std::string>> &kVarray) { std::string fileName = filePath + "/level-0/" + std::to_string(nextLabel[0]) + ".sst"; levelArray[0].emplace_back(ssTable::genTable(fileName, nextTimeStamp, kVarray)); ++nextTimeStamp; ++nextLabel[0]; modify(); } std::pair<bool, std::string> ssTableCache::getValKey(uint64_t key) const { std::pair<bool, std::string> res(false, ""); uint64_t maxTimeStamp; if (!levelArray.empty()) { for (const auto &it: levelArray[0]) { std::pair<bool, std::string> test = it->getValKey(key); if (test.first) { if (res.first) { if (maxTimeStamp < it->header.timeStamp) { maxTimeStamp = it->header.timeStamp; res.second = test.second; } } else { maxTimeStamp = it->header.timeStamp; res.first = true; res.second = test.second; } } } uint64_t i = 1; while (i < levelArray.size()) { for (const auto &it: levelArray[i]) { std::pair<bool, std::string> test = it->getValKey(key); if (test.first) { if (res.first) { if (maxTimeStamp < it->header.timeStamp) { maxTimeStamp = it->header.timeStamp; res.second = test.second; } } else { maxTimeStamp = it->header.timeStamp; res.first = true; res.second = test.second; } break; } } ++i; } } return res; } void ssTableCache::reset() { for (auto & it : levelArray) { for (auto & item : it) { item->clearTable(); delete item; item = nullptr; } it.clear(); } for (uint64_t i = 0; i < levelArray.size(); ++i) { if( utils::rmdir((filePath + "/level-" + std::to_string(i)).c_str()) ) { std::cerr << "ERROR: Fail to delete directory." << std::endl; exit(1); } } levelArray.clear(); nextLabel.clear(); if ( utils::mkdir((filePath + "/level-0").c_str()) ) { std::cerr << "ERROR: Fail to create directory." << std::endl; exit(1); } levelArray.emplace_back(); nextLabel.push_back(0); nextTimeStamp = 1; }
37.256757
129
0.518589
q4x3
a15b0836431db7eb733d6c96000f3491139413e4
1,423
cpp
C++
model/mosesdecoder/misc/processLexicalTable.cpp
saeedesm/UNMT_AH
cc171bf66933b5c0ad8a0ab87e57f7364312a7df
[ "Apache-2.0" ]
3
2019-12-02T14:53:29.000Z
2020-08-12T18:01:49.000Z
tools/mosesdecoder-master/misc/processLexicalTable.cpp
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-11-06T14:40:10.000Z
2020-12-29T19:03:11.000Z
tools/mosesdecoder-master/misc/processLexicalTable.cpp
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-03-26T16:05:11.000Z
2020-08-06T16:35:39.000Z
#include <iostream> #include <string> #include "moses/Timer.h" #include "moses/InputFileStream.h" #include "moses/FF/LexicalReordering/LexicalReorderingTable.h" using namespace Moses; Timer timer; void printHelp() { std::cerr << "Usage:\n" "options: \n" "\t-in string -- input table file name\n" "\t-out string -- prefix of binary table files\n" "If -in is not specified reads from stdin\n" "\n"; } int main(int argc, char** argv) { std::cerr << "processLexicalTable v0.1 by Konrad Rawlik\n"; std::string inFilePath; std::string outFilePath("out"); if(1 >= argc) { printHelp(); return 1; } for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if("-in" == arg && i+1 < argc) { ++i; inFilePath = argv[i]; } else if("-out" == arg && i+1 < argc) { ++i; outFilePath = argv[i]; } else { //somethings wrong... print help printHelp(); return 1; } } bool success = false; if(inFilePath.empty()) { std::cerr << "processing stdin to " << outFilePath << ".*\n"; success = LexicalReorderingTableTree::Create(std::cin, outFilePath); } else { std::cerr << "processing " << inFilePath<< " to " << outFilePath << ".*\n"; InputFileStream file(inFilePath); success = LexicalReorderingTableTree::Create(file, outFilePath); } return (success ? 0 : 1); }
24.118644
79
0.580464
saeedesm
a15b9f8e1bd8f28c2a36cb942ae4f2b5558b0723
158
cpp
C++
cpp/libs/main.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
cpp/libs/main.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
cpp/libs/main.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
// // Created by lbinr on 2020/11/5. // #include <iostream> using namespace std; int main( int argc, char* argv[] ){ cout << "hello, world!" << endl; }
14.363636
36
0.601266
BinRay
a15e698a959b763c6365cae82d35603508491a89
1,501
cpp
C++
practice/Artist.cpp
jordanjohnston/console-music-player
35c80d9b083a04f75b3959e10cb4c91da56f4b1b
[ "MIT" ]
null
null
null
practice/Artist.cpp
jordanjohnston/console-music-player
35c80d9b083a04f75b3959e10cb4c91da56f4b1b
[ "MIT" ]
null
null
null
practice/Artist.cpp
jordanjohnston/console-music-player
35c80d9b083a04f75b3959e10cb4c91da56f4b1b
[ "MIT" ]
null
null
null
#include "Artist.h" #include <iostream> using std::vector; using std::map; using std::wstring; Artist::Artist() { m_name = L""; m_albumTitles = vector<wstring>(); m_albumMap = map<wstring, vector<Song>>(); } Artist::Artist(const wstring name) :m_name(name) { m_albumTitles = vector<wstring>(); m_albumMap = map<wstring, vector<Song>>(); } Artist::Artist(const wstring name, const map<wstring, vector<Song>> albumMap) :m_name(name), m_albumMap(albumMap) { m_albumTitles = vector<wstring>(); } Artist::~Artist() { } wstring Artist::getName() const { return m_name; } void Artist::setName(const wstring& name) { m_name = name; } map<wstring, vector<Song>> Artist::getAlbums() const { return m_albumMap; } void Artist::setAlbumMap(const map<wstring, vector<Song>>& albums) { m_albumMap = albums; } void Artist::addSongToAlbum(const wstring& album, const Song& song) { m_albumTitles.push_back(album); m_albumMap[album].push_back(song); } vector<Song> Artist::getAlbumName(const wstring& album) const { try { return m_albumMap.at(album); } catch (const std::out_of_range e) { std::wcerr << L"Couldn't find album: " << album << std::endl; return vector<Song>(); } } vector<wstring> Artist::getAllAlbumTitles() const { return m_albumTitles; } void Artist::addAlbumToList(const wstring albumKey, const wstring albumName, const vector<Song> album) { std::pair<wstring, vector<Song>> ap(albumKey, album); m_albumMap.insert(ap); m_albumTitles.push_back(albumName); }
17.869048
102
0.710193
jordanjohnston
a15f8cc02f1399eddaadd7f65e07d2f259f5b754
1,572
cc
C++
components/history_clusters/core/memories_features.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
components/history_clusters/core/memories_features.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
components/history_clusters/core/memories_features.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 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 "components/history_clusters/core/memories_features.h" #include "base/metrics/field_trial_params.h" namespace history_clusters { namespace { const base::FeatureParam<std::string> kRemoteModelEndpoint{ &kRemoteModelForDebugging, "MemoriesRemoteModelEndpoint", ""}; } // namespace GURL RemoteModelEndpoint() { return GURL(kRemoteModelEndpoint.Get()); } const base::FeatureParam<std::string> kRemoteModelEndpointExperimentName{ &kRemoteModelForDebugging, "MemoriesRemoteModelEndpointExperimentName", ""}; const base::FeatureParam<int> kMaxVisitsToCluster{ &kMemories, "MemoriesMaxVisitsToCluster", 1000}; const base::FeatureParam<int> kMaxDaysToCluster{&kMemories, "MemoriesMaxDaysToCluster", 9}; const base::FeatureParam<bool> kPersistClustersInHistoryDb{ &kMemories, "MemoriesPersistClustersInHistoryDb", false}; const base::Feature kMemories{"Memories", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kDebug{"MemoriesDebug", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kRemoteModelForDebugging{"MemoriesRemoteModelForDebugging", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kPersistContextAnnotationsInHistoryDb{ "MemoriesPersistContextAnnotationsInHistoryDb", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace history_clusters
34.173913
80
0.755725
DamieFC
a162e71560dca828a9dee675fa745df8dfb724c0
717
cpp
C++
samples/common/src/platform/android/bitmap.cpp
soyzhc/agge
bf6b2b0f76178524b6f19baeec9dfba81e251086
[ "MIT" ]
96
2015-02-02T11:18:44.000Z
2022-01-24T13:41:13.000Z
samples/common/src/platform/android/bitmap.cpp
soyzhc/agge
bf6b2b0f76178524b6f19baeec9dfba81e251086
[ "MIT" ]
8
2018-01-13T11:44:54.000Z
2021-04-18T17:25:47.000Z
samples/common/src/platform/android/bitmap.cpp
soyzhc/agge
bf6b2b0f76178524b6f19baeec9dfba81e251086
[ "MIT" ]
16
2017-11-19T03:08:22.000Z
2020-09-11T08:30:35.000Z
#include "bitmap.h" #include <android/native_window.h> android_native_surface::android_native_surface(ANativeWindow &window) : _window(window) { ANativeWindow_Buffer descriptor = { }; if (ANativeWindow_lock(&_window, &descriptor, 0) < 0) throw 0; switch (descriptor.format) { case WINDOW_FORMAT_RGBA_8888: case WINDOW_FORMAT_RGBX_8888: break; default: // Unsupported format: unlock window and throw exception... ANativeWindow_unlockAndPost(&_window); throw 0; } _width = descriptor.width; _height = descriptor.height; _stride = descriptor.stride * sizeof(pixel); _buffer = descriptor.bits; } android_native_surface::~android_native_surface() { ANativeWindow_unlockAndPost(&_window); }
20.485714
69
0.758717
soyzhc
a1634727a90eb72ef0b67bd9f973af2e85cf22d0
9,958
cpp
C++
third_party/skia_m63/src/shaders/gradients/SkTwoPointConicalGradient.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
4
2019-10-18T05:53:30.000Z
2021-08-21T07:36:37.000Z
third_party/skia_m63/src/shaders/gradients/SkTwoPointConicalGradient.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
2
2019-03-14T10:26:45.000Z
2021-08-06T01:24:06.000Z
third_party/skia_m63/src/shaders/gradients/SkTwoPointConicalGradient.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
4
2018-10-14T00:17:11.000Z
2020-07-01T04:01:25.000Z
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTwoPointConicalGradient.h" #include "SkRasterPipeline.h" #include "../../jumper/SkJumper.h" sk_sp<SkShader> SkTwoPointConicalGradient::Create(const SkPoint& c0, SkScalar r0, const SkPoint& c1, SkScalar r1, bool flipped, const Descriptor& desc) { SkMatrix gradientMatrix; Type gradientType; if (SkScalarNearlyZero((c0 - c1).length())) { // Concentric case: we can pretend we're radial (with a tiny twist). gradientMatrix = SkMatrix::MakeTrans(-c1.x(), -c1.y()); gradientMatrix.postScale(1 / r1, 1 / r1); gradientType = Type::kRadial; } else { const SkPoint centers[2] = { c0 , c1 }; const SkPoint unitvec[2] = { {0, 0}, {1, 0} }; if (!gradientMatrix.setPolyToPoly(centers, unitvec, 2)) { // Degenerate case. return nullptr; } // General two-point case. gradientType = Type::kTwoPoint; } return sk_sp<SkShader>(new SkTwoPointConicalGradient(c0, r0, c1, r1, flipped, desc, gradientType, gradientMatrix)); } SkTwoPointConicalGradient::SkTwoPointConicalGradient( const SkPoint& start, SkScalar startRadius, const SkPoint& end, SkScalar endRadius, bool flippedGrad, const Descriptor& desc, Type type, const SkMatrix& gradientMatrix) : SkGradientShaderBase(desc, gradientMatrix) , fCenter1(start) , fCenter2(end) , fRadius1(startRadius) , fRadius2(endRadius) , fFlippedGrad(flippedGrad) , fType(type) { // this is degenerate, and should be caught by our caller SkASSERT(fCenter1 != fCenter2 || fRadius1 != fRadius2); } bool SkTwoPointConicalGradient::isOpaque() const { // Because areas outside the cone are left untouched, we cannot treat the // shader as opaque even if the gradient itself is opaque. // TODO(junov): Compute whether the cone fills the plane crbug.com/222380 return false; } // Returns the original non-sorted version of the gradient SkShader::GradientType SkTwoPointConicalGradient::asAGradient( GradientInfo* info) const { if (info) { commonAsAGradient(info, fFlippedGrad); info->fPoint[0] = fCenter1; info->fPoint[1] = fCenter2; info->fRadius[0] = fRadius1; info->fRadius[1] = fRadius2; if (fFlippedGrad) { SkTSwap(info->fPoint[0], info->fPoint[1]); SkTSwap(info->fRadius[0], info->fRadius[1]); } } return kConical_GradientType; } sk_sp<SkFlattenable> SkTwoPointConicalGradient::CreateProc(SkReadBuffer& buffer) { DescriptorScope desc; if (!desc.unflatten(buffer)) { return nullptr; } SkPoint c1 = buffer.readPoint(); SkPoint c2 = buffer.readPoint(); SkScalar r1 = buffer.readScalar(); SkScalar r2 = buffer.readScalar(); if (buffer.readBool()) { // flipped SkTSwap(c1, c2); SkTSwap(r1, r2); SkColor4f* colors = desc.mutableColors(); SkScalar* pos = desc.mutablePos(); const int last = desc.fCount - 1; const int half = desc.fCount >> 1; for (int i = 0; i < half; ++i) { SkTSwap(colors[i], colors[last - i]); if (pos) { SkScalar tmp = pos[i]; pos[i] = SK_Scalar1 - pos[last - i]; pos[last - i] = SK_Scalar1 - tmp; } } if (pos) { if (desc.fCount & 1) { pos[half] = SK_Scalar1 - pos[half]; } } } return SkGradientShader::MakeTwoPointConical(c1, r1, c2, r2, desc.fColors, std::move(desc.fColorSpace), desc.fPos, desc.fCount, desc.fTileMode, desc.fGradFlags, desc.fLocalMatrix); } void SkTwoPointConicalGradient::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writePoint(fCenter1); buffer.writePoint(fCenter2); buffer.writeScalar(fRadius1); buffer.writeScalar(fRadius2); buffer.writeBool(fFlippedGrad); } #if SK_SUPPORT_GPU #include "SkGr.h" #include "SkTwoPointConicalGradient_gpu.h" std::unique_ptr<GrFragmentProcessor> SkTwoPointConicalGradient::asFragmentProcessor( const AsFPArgs& args) const { SkASSERT(args.fContext); sk_sp<GrColorSpaceXform> colorSpaceXform = GrColorSpaceXform::Make(fColorSpace.get(), args.fDstColorSpace); auto inner = Gr2PtConicalGradientEffect::Make(GrGradientEffect::CreateArgs( args.fContext, this, args.fLocalMatrix, fTileMode, std::move(colorSpaceXform), SkToBool(args.fDstColorSpace))); if (!inner) { return nullptr; } return GrFragmentProcessor::MulOutputByInputAlpha(std::move(inner)); } #endif sk_sp<SkShader> SkTwoPointConicalGradient::onMakeColorSpace(SkColorSpaceXformer* xformer) const { SkSTArray<8, SkColor> origColorsStorage(fColorCount); SkSTArray<8, SkScalar> origPosStorage(fColorCount); SkSTArray<8, SkColor> xformedColorsStorage(fColorCount); SkColor* origColors = origColorsStorage.begin(); SkScalar* origPos = fOrigPos ? origPosStorage.begin() : nullptr; SkColor* xformedColors = xformedColorsStorage.begin(); // Flip if necessary SkPoint center1 = fFlippedGrad ? fCenter2 : fCenter1; SkPoint center2 = fFlippedGrad ? fCenter1 : fCenter2; SkScalar radius1 = fFlippedGrad ? fRadius2 : fRadius1; SkScalar radius2 = fFlippedGrad ? fRadius1 : fRadius2; for (int i = 0; i < fColorCount; i++) { origColors[i] = fFlippedGrad ? fOrigColors[fColorCount - i - 1] : fOrigColors[i]; if (origPos) { origPos[i] = fFlippedGrad ? 1.0f - fOrigPos[fColorCount - i - 1] : fOrigPos[i]; } } xformer->apply(xformedColors, origColors, fColorCount); return SkGradientShader::MakeTwoPointConical(center1, radius1, center2, radius2, xformedColors, origPos, fColorCount, fTileMode, fGradFlags, &this->getLocalMatrix()); } #ifndef SK_IGNORE_TO_STRING void SkTwoPointConicalGradient::toString(SkString* str) const { str->append("SkTwoPointConicalGradient: ("); str->append("center1: ("); str->appendScalar(fCenter1.fX); str->append(", "); str->appendScalar(fCenter1.fY); str->append(") radius1: "); str->appendScalar(fRadius1); str->append(" "); str->append("center2: ("); str->appendScalar(fCenter2.fX); str->append(", "); str->appendScalar(fCenter2.fY); str->append(") radius2: "); str->appendScalar(fRadius2); str->append(" "); this->INHERITED::toString(str); str->append(")"); } #endif void SkTwoPointConicalGradient::appendGradientStages(SkArenaAlloc* alloc, SkRasterPipeline* p, SkRasterPipeline* postPipeline) const { const auto dRadius = fRadius2 - fRadius1; SkASSERT(dRadius >= 0); if (fType == Type::kRadial) { p->append(SkRasterPipeline::xy_to_radius); // Tiny twist: radial computes a t for [0, r2], but we want a t for [r1, r2]. auto scale = fRadius2 / dRadius; auto bias = -fRadius1 / dRadius; p->append_matrix(alloc, SkMatrix::Concat(SkMatrix::MakeTrans(bias, 0), SkMatrix::MakeScale(scale, 1))); return; } const auto dCenter = (fCenter1 - fCenter2).length(); // Since we've squashed the centers into a unit vector, we must also scale // all the coefficient variables by (1 / dCenter). const auto coeffA = 1 - dRadius * dRadius / (dCenter * dCenter); auto* ctx = alloc->make<SkJumper_2PtConicalCtx>(); ctx->fCoeffA = coeffA; ctx->fInvCoeffA = 1 / coeffA; ctx->fR0 = fRadius1 / dCenter; ctx->fDR = dRadius / dCenter; // Is the solver guaranteed to not produce degenerates? bool isWellBehaved = true; if (SkScalarNearlyZero(coeffA)) { // The focal point is on the edge of the end circle. p->append(SkRasterPipeline::xy_to_2pt_conical_linear, ctx); isWellBehaved = false; } else { if (dCenter + fRadius1 > fRadius2) { // The focal point is outside the end circle. // We want the larger root, per spec: // "For all values of ω where r(ω) > 0, starting with the value of ω nearest // to positive infinity and ending with the value of ω nearest to negative // infinity, draw the circumference of the circle with radius r(ω) at position // (x(ω), y(ω)), with the color at ω, but only painting on the parts of the // bitmap that have not yet been painted on by earlier circles in this step for // this rendering of the gradient." // (https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createradialgradient) p->append(fFlippedGrad ? SkRasterPipeline::xy_to_2pt_conical_quadratic_min : SkRasterPipeline::xy_to_2pt_conical_quadratic_max, ctx); isWellBehaved = false; } else { // The focal point is inside (well-behaved case). p->append(SkRasterPipeline::xy_to_2pt_conical_quadratic_max, ctx); } } if (!isWellBehaved) { p->append(SkRasterPipeline::mask_2pt_conical_degenerates, ctx); postPipeline->append(SkRasterPipeline::apply_vector_mask, &ctx->fMask); } }
37.43609
103
0.610263
kniefliu
a1684962ee6f79f90d6c042414e5b92e1552860c
404
cpp
C++
books/C++_Prime_Plus/Chapter6/not.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
books/C++_Prime_Plus/Chapter6/not.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
books/C++_Prime_Plus/Chapter6/not.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include"iostream" #include"climits" using namespace std; bool is_int(double); int main() { double num; cout<<"Enter an integer value:"; cin>>num; while(!is_int(num)) { cout<<"Out of range--please try agagin:"; cin.get(); cin>>num; } int val=(int)num; cout<<"The valu is:"<<val<<endl; return 0; } bool is_int(double num) { if(num<=INT_MAX && num>=INT_MIN) return true; return false; }
16.833333
43
0.65099
liangjisheng
a168f706c026d400cb7ade7000eb2eff43cc3136
387
hpp
C++
Paramedic.hpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
Paramedic.hpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
Paramedic.hpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
// // Created by rotem levy on 27/05/2020. // #pragma once #include "Soldier.hpp" using namespace std; class Paramedic: public Soldier { public: static const uint MAX_HP = 100; Paramedic() {}; virtual ~Paramedic() {}; Paramedic(uint num); void attack(vector<vector<Soldier*>> &b, pair<int,int> location); virtual uint getMaxHP(); };
16.125
70
0.612403
rotemish7
a16e09521a95b870c4462eebaae3fbe5919363fa
542
cpp
C++
2A. C++ Advanced (STL)/Attic/setw.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/setw.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
2A. C++ Advanced (STL)/Attic/setw.cpp
alemesa1991/School-Projects
ed9170fa4cadfe18c6d9850a17077686ca16d1a1
[ "MIT" ]
null
null
null
// http://www.cplusplus.com/reference/iomanip/setw/ // setw example #include <iostream> // std::cout #include <iomanip> // std::setw int main () { int width = 20; std::cout << "0 1 2 3\n"; std::cout << "123456789012345678901234567890\n"; std::cout << std::setw(width); std::cout << 77 << "<-- " << width << " wide, right justified by default\n"; std::cout << std::left << std::setw(width); std::cout << 77 << "<-- " << width << " wide, left justified by std::left directive\n"; return 0; }
30.111111
89
0.560886
alemesa1991
a16f864cd332112cd327e49ef24b8a43908e0fdf
677
cpp
C++
ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp
dmkozh/TestAdapter_Catch2
6584596594f11bf477fddebfd1211483ca091ee3
[ "MIT" ]
null
null
null
ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp
dmkozh/TestAdapter_Catch2
6584596594f11bf477fddebfd1211483ca091ee3
[ "MIT" ]
null
null
null
ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp
dmkozh/TestAdapter_Catch2
6584596594f11bf477fddebfd1211483ca091ee3
[ "MIT" ]
null
null
null
/** Basic Info ** Copyright: 2019 Johnny Hendriks Author : Johnny Hendriks Year : 2019 Project: VSTestAdapter for Catch2 Licence: MIT Notes: None ** Basic Info **/ /************ * Includes * ************/ // Catch2 #include <catch2/catch_test_macros.hpp> /************** * Start code * **************/ namespace CatchHidden { // Shift one line to distinguish test case line numbers from the UT_Hidden.cpp file TEST_CASE( "NotHidden. One tag", "[Tag1]" ) { CHECK(true); } TEST_CASE( "NotHidden. Two tags", "[Tag1][Tag2]" ) { CHECK(true); } } // End namespace: CatchHidden /************ * End code * ************/
15.044444
87
0.55096
dmkozh
a171f05454e22d638a2f450d95e3fc0d1e5a1118
1,763
hpp
C++
include/evt/evtapproach.hpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
2
2021-02-04T18:22:41.000Z
2021-12-08T10:57:00.000Z
include/evt/evtapproach.hpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
9
2018-03-20T10:24:22.000Z
2018-08-27T21:53:56.000Z
include/evt/evtapproach.hpp
AlterB/chronovise
5c5fac329b143f3e62ebbc8523d7e205835dd4cb
[ "Apache-2.0" ]
4
2018-05-16T14:27:55.000Z
2022-01-28T17:18:24.000Z
#ifndef EVT_EVTAPPROACH_HPP_ #define EVT_EVTAPPROACH_HPP_ #include "measures_pool.hpp" namespace chronovise { /** * The abstract class implementing one of the EVT approach (BM or PoT). */ template <typename T_INPUT, typename T_TIME=unsigned long> class EVTApproach { public: /** * A default virtual costructor */ virtual ~EVTApproach() = default; /** * It performs the analysis on the provided pool of data. It also splits the pool * according to the iterators of the pool itself * @param original_pool The raw pool from which the sample are drawned * @throw std::runtime_error In case of failure. */ virtual void perform(const MeasuresPoolSet<T_INPUT, T_TIME>& original_pool) = 0; /** * It returns the training pool. Calling this method before `perform` returns an * empty pool. */ MeasuresPool<T_INPUT, T_TIME>& get_training_pool() noexcept { return this->training_pool; } /** * It returns the test pool. Calling this method before `perform` returns an * empty pool. */ MeasuresPool<T_INPUT, T_TIME>& get_test_pool() noexcept { return this->test_pool; } /** * @brief It returns the minimal sample size to run the estimator. If a sample with lower * size is provided to run() function, it will probably fail. */ virtual unsigned long get_minimal_sample_size() const noexcept = 0; /** * @brief A method returning a constant character string identifying the * EVT method */ virtual const char* to_string() const noexcept = 0; protected: MeasuresPool<T_INPUT, T_TIME> training_pool; MeasuresPool<T_INPUT, T_TIME> test_pool; }; } // namespace chronovise #endif
26.313433
93
0.673284
AlterB
a1727dfcaa0d68978b242b0f18757785f8c40668
2,334
hpp
C++
source/triceratone/mechanics/cylinderMath.hpp
a-day-old-bagel/at3
868cec7672fd109760cae740b1acf26cec5eb85e
[ "MIT" ]
null
null
null
source/triceratone/mechanics/cylinderMath.hpp
a-day-old-bagel/at3
868cec7672fd109760cae740b1acf26cec5eb85e
[ "MIT" ]
null
null
null
source/triceratone/mechanics/cylinderMath.hpp
a-day-old-bagel/at3
868cec7672fd109760cae740b1acf26cec5eb85e
[ "MIT" ]
null
null
null
#pragma once #include "math.hpp" namespace at3 { /** * Get the faked cylinder gravity to apply to a mass. * This attempts to take into account cylinder-tangential velocity of the mass, and provide a complete picure of the * way an object would move inside the cylinder from the perspective of the cylinder's own reference frame. * I may have gotten this wrong. * The non-tangential component of a mass's motion might need to be rotated every step to match the tangent. * Right now I'm just applying a negative cylinder-gravity and hoping that it's equivalent (I haven't done the math.) * * EDIT: TODO: FIXME: This is not completely right - a projectile shot "upwards" from the ground surface should curve, * but right now I'm only applying the curve based on tangential velocity, while neglecting change to radial velocity. * It might not be correct to just add another curve factor multiplied by 1 - dot(tangential, vel), but that might * be closer and good enough. * * @param pos * @param nativeVel * @return */ glm::vec3 getCylGrav(const glm::vec3 & pos, const glm::vec3 & nativeVel); /** * Get the faked cylinder gravity to apply to a mass. * This neglects any velocity component of the mass in the cylinder-tangential direction, and thus is wrong. * But it's useful for some things, like finding an appropriate "up" for some objects * @param pos The center of the mass in standard R3 * @return A likely-incorrect gravity vector */ glm::vec3 getNaiveCylGrav(const glm::vec3 &pos); /** * Get only the directional part of the naive gravity vector returned by getNaiveCylGrav. * @param pos The center of the mass in standard R3 * @return A likely-incorrect gravity direction vector */ glm::vec3 getNaiveCylGravDir(const glm::vec3 &pos); /** * Get a full view rotation from a planar z=up ground plane while facing foward to a cylinder-gravity-up orientation * including pitch and yaw rotations. * @param pos The camera position in standard R3 * @param pitch * @param yaw * @return A rotation described by pitch and yaw and exhibiting cylinder-gravity-up orientation */ glm::mat3 getCylStandingRot(const glm::vec3 &pos, const float &pitch, const float &yaw); }
44.037736
121
0.705656
a-day-old-bagel
a173d518a45d21db284feef54cb158e7eccc9983
23,364
cpp
C++
modules/gles31/functional/es31fShaderHelperInvocationTests.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
20
2019-04-18T07:37:34.000Z
2022-02-02T21:43:47.000Z
modules/gles31/functional/es31fShaderHelperInvocationTests.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
11
2019-10-21T13:39:41.000Z
2021-11-05T08:11:54.000Z
modules/gles31/functional/es31fShaderHelperInvocationTests.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
3
2017-01-21T00:56:25.000Z
2020-10-31T12:00:02.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.1 Module * ------------------------------------------------- * * Copyright 2014 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. * *//*! * \file * \brief gl_HelperInvocation tests. *//*--------------------------------------------------------------------*/ #include "es31fShaderHelperInvocationTests.hpp" #include "gluObjectWrapper.hpp" #include "gluShaderProgram.hpp" #include "gluDrawUtil.hpp" #include "gluPixelTransfer.hpp" #include "glwFunctions.hpp" #include "glwEnums.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" #include "tcuSurface.hpp" #include "deUniquePtr.hpp" #include "deStringUtil.hpp" #include "deRandom.hpp" #include "deString.h" namespace deqp { namespace gles31 { namespace Functional { namespace { using glu::ShaderProgram; using tcu::TestLog; using tcu::Vec2; using tcu::IVec2; using de::MovePtr; using std::string; using std::vector; enum PrimitiveType { PRIMITIVETYPE_TRIANGLE = 0, PRIMITIVETYPE_LINE, PRIMITIVETYPE_WIDE_LINE, PRIMITIVETYPE_POINT, PRIMITIVETYPE_WIDE_POINT, PRIMITIVETYPE_LAST }; static int getNumVerticesPerPrimitive (PrimitiveType primType) { switch (primType) { case PRIMITIVETYPE_TRIANGLE: return 3; case PRIMITIVETYPE_LINE: return 2; case PRIMITIVETYPE_WIDE_LINE: return 2; case PRIMITIVETYPE_POINT: return 1; case PRIMITIVETYPE_WIDE_POINT: return 1; default: DE_ASSERT(false); return 0; } } static glu::PrimitiveType getGluPrimitiveType (PrimitiveType primType) { switch (primType) { case PRIMITIVETYPE_TRIANGLE: return glu::PRIMITIVETYPE_TRIANGLES; case PRIMITIVETYPE_LINE: return glu::PRIMITIVETYPE_LINES; case PRIMITIVETYPE_WIDE_LINE: return glu::PRIMITIVETYPE_LINES; case PRIMITIVETYPE_POINT: return glu::PRIMITIVETYPE_POINTS; case PRIMITIVETYPE_WIDE_POINT: return glu::PRIMITIVETYPE_POINTS; default: DE_ASSERT(false); return glu::PRIMITIVETYPE_LAST; } } static void genVertices (PrimitiveType primType, int numPrimitives, de::Random* rnd, vector<Vec2>* dst) { const bool isTri = primType == PRIMITIVETYPE_TRIANGLE; const float minCoord = isTri ? -1.5f : -1.0f; const float maxCoord = isTri ? +1.5f : +1.0f; const int numVerticesPerPrimitive = getNumVerticesPerPrimitive(primType); const int numVert = numVerticesPerPrimitive*numPrimitives; dst->resize(numVert); for (size_t ndx = 0; ndx < dst->size(); ndx++) { (*dst)[ndx][0] = rnd->getFloat(minCoord, maxCoord); (*dst)[ndx][1] = rnd->getFloat(minCoord, maxCoord); } // Don't produce completely or almost completely discardable primitives. // \note: This doesn't guarantee that resulting primitives are visible or // produce any fragments. This just removes trivially discardable // primitives. for (int primitiveNdx = 0; primitiveNdx < numPrimitives; ++primitiveNdx) for (int component = 0; component < 2; ++component) { bool negativeClip = true; bool positiveClip = true; for (int vertexNdx = 0; vertexNdx < numVerticesPerPrimitive; ++vertexNdx) { const float p = (*dst)[primitiveNdx * numVerticesPerPrimitive + vertexNdx][component]; // \note 0.9 instead of 1.0 to avoid just barely visible primitives if (p > -0.9f) negativeClip = false; if (p < +0.9f) positiveClip = false; } // if discardable, just mirror first vertex along center if (negativeClip || positiveClip) { (*dst)[primitiveNdx * numVerticesPerPrimitive + 0][0] *= -1.0f; (*dst)[primitiveNdx * numVerticesPerPrimitive + 0][1] *= -1.0f; } } } static int getInteger (const glw::Functions& gl, deUint32 pname) { int v = 0; gl.getIntegerv(pname, &v); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetIntegerv()"); return v; } static Vec2 getRange (const glw::Functions& gl, deUint32 pname) { Vec2 v(0.0f); gl.getFloatv(pname, v.getPtr()); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetFloatv()"); return v; } static void drawRandomPrimitives (const glu::RenderContext& renderCtx, deUint32 program, PrimitiveType primType, int numPrimitives, de::Random* rnd) { const glw::Functions& gl = renderCtx.getFunctions(); const float minPointSize = 16.0f; const float maxPointSize = 32.0f; const float minLineWidth = 16.0f; const float maxLineWidth = 32.0f; vector<Vec2> vertices; vector<glu::VertexArrayBinding> vertexArrays; genVertices(primType, numPrimitives, rnd, &vertices); vertexArrays.push_back(glu::va::Float("a_position", 2, (int)vertices.size(), 0, (const float*)&vertices[0])); gl.useProgram(program); // Special state for certain primitives if (primType == PRIMITIVETYPE_POINT || primType == PRIMITIVETYPE_WIDE_POINT) { const Vec2 range = getRange(gl, GL_ALIASED_POINT_SIZE_RANGE); const bool isWidePoint = primType == PRIMITIVETYPE_WIDE_POINT; const float pointSize = isWidePoint ? de::min(rnd->getFloat(minPointSize, maxPointSize), range.y()) : 1.0f; const int pointSizeLoc = gl.getUniformLocation(program, "u_pointSize"); gl.uniform1f(pointSizeLoc, pointSize); } else if (primType == PRIMITIVETYPE_WIDE_LINE) { const Vec2 range = getRange(gl, GL_ALIASED_LINE_WIDTH_RANGE); const float lineWidth = de::min(rnd->getFloat(minLineWidth, maxLineWidth), range.y()); gl.lineWidth(lineWidth); } glu::draw(renderCtx, program, (int)vertexArrays.size(), &vertexArrays[0], glu::PrimitiveList(getGluPrimitiveType(primType), (int)vertices.size())); } class FboHelper { public: FboHelper (const glu::RenderContext& renderCtx, int width, int height, deUint32 format, int numSamples); ~FboHelper (void); void bindForRendering (void); void readPixels (int x, int y, const tcu::PixelBufferAccess& dst); private: const glu::RenderContext& m_renderCtx; const int m_numSamples; const IVec2 m_size; glu::Renderbuffer m_colorbuffer; glu::Framebuffer m_framebuffer; glu::Renderbuffer m_resolveColorbuffer; glu::Framebuffer m_resolveFramebuffer; }; FboHelper::FboHelper (const glu::RenderContext& renderCtx, int width, int height, deUint32 format, int numSamples) : m_renderCtx (renderCtx) , m_numSamples (numSamples) , m_size (width, height) , m_colorbuffer (renderCtx) , m_framebuffer (renderCtx) , m_resolveColorbuffer (renderCtx) , m_resolveFramebuffer (renderCtx) { const glw::Functions& gl = m_renderCtx.getFunctions(); const int maxSamples = getInteger(gl, GL_MAX_SAMPLES); gl.bindRenderbuffer(GL_RENDERBUFFER, *m_colorbuffer); gl.renderbufferStorageMultisample(GL_RENDERBUFFER, m_numSamples, format, width, height); gl.bindFramebuffer(GL_FRAMEBUFFER, *m_framebuffer); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *m_colorbuffer); if (m_numSamples > maxSamples && gl.checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw tcu::NotSupportedError("Sample count exceeds GL_MAX_SAMPLES"); TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); if (m_numSamples != 0) { gl.bindRenderbuffer(GL_RENDERBUFFER, *m_resolveColorbuffer); gl.renderbufferStorage(GL_RENDERBUFFER, format, width, height); gl.bindFramebuffer(GL_FRAMEBUFFER, *m_resolveFramebuffer); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *m_resolveColorbuffer); TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); } GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to create framebuffer"); } FboHelper::~FboHelper (void) { } void FboHelper::bindForRendering (void) { const glw::Functions& gl = m_renderCtx.getFunctions(); gl.bindFramebuffer(GL_FRAMEBUFFER, *m_framebuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindFramebuffer()"); gl.viewport(0, 0, m_size.x(), m_size.y()); GLU_EXPECT_NO_ERROR(gl.getError(), "viewport()"); } void FboHelper::readPixels (int x, int y, const tcu::PixelBufferAccess& dst) { const glw::Functions& gl = m_renderCtx.getFunctions(); const int width = dst.getWidth(); const int height = dst.getHeight(); if (m_numSamples != 0) { gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, *m_resolveFramebuffer); gl.blitFramebuffer(x, y, width, height, x, y, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); gl.bindFramebuffer(GL_READ_FRAMEBUFFER, *m_resolveFramebuffer); } glu::readPixels(m_renderCtx, x, y, dst); } enum { FRAMEBUFFER_WIDTH = 256, FRAMEBUFFER_HEIGHT = 256, FRAMEBUFFER_FORMAT = GL_RGBA8, NUM_SAMPLES_MAX = -1 }; //! Verifies that gl_HelperInvocation is false in all rendered pixels. class HelperInvocationValueCase : public TestCase { public: HelperInvocationValueCase (Context& context, const char* name, const char* description, PrimitiveType primType, int numSamples); ~HelperInvocationValueCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: const PrimitiveType m_primitiveType; const int m_numSamples; const int m_numIters; const int m_numPrimitivesPerIter; MovePtr<ShaderProgram> m_program; MovePtr<FboHelper> m_fbo; int m_iterNdx; }; HelperInvocationValueCase::HelperInvocationValueCase (Context& context, const char* name, const char* description, PrimitiveType primType, int numSamples) : TestCase (context, name, description) , m_primitiveType (primType) , m_numSamples (numSamples) , m_numIters (5) , m_numPrimitivesPerIter (10) , m_iterNdx (0) { } HelperInvocationValueCase::~HelperInvocationValueCase (void) { deinit(); } void HelperInvocationValueCase::init (void) { const glu::RenderContext& renderCtx = m_context.getRenderContext(); const glw::Functions& gl = renderCtx.getFunctions(); const int maxSamples = getInteger(gl, GL_MAX_SAMPLES); const int actualSamples = m_numSamples == NUM_SAMPLES_MAX ? maxSamples : m_numSamples; m_program = MovePtr<ShaderProgram>(new ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource( "#version 310 es\n" "in highp vec2 a_position;\n" "uniform highp float u_pointSize;\n" "void main (void)\n" "{\n" " gl_Position = vec4(a_position, 0.0, 1.0);\n" " gl_PointSize = u_pointSize;\n" "}\n") << glu::FragmentSource( "#version 310 es\n" "out mediump vec4 o_color;\n" "void main (void)\n" "{\n" " if (gl_HelperInvocation)\n" " o_color = vec4(1.0, 0.0, 0.0, 1.0);\n" " else\n" " o_color = vec4(0.0, 1.0, 0.0, 1.0);\n" "}\n"))); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) { m_program.clear(); TCU_FAIL("Compile failed"); } m_testCtx.getLog() << TestLog::Message << "Using GL_RGBA8 framebuffer with " << actualSamples << " samples" << TestLog::EndMessage; m_fbo = MovePtr<FboHelper>(new FboHelper(renderCtx, FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT, FRAMEBUFFER_FORMAT, actualSamples)); m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); } void HelperInvocationValueCase::deinit (void) { m_program.clear(); m_fbo.clear(); } static bool verifyHelperInvocationValue (TestLog& log, const tcu::Surface& result, bool isMultiSample) { const tcu::RGBA bgRef (0, 0, 0, 255); const tcu::RGBA fgRef (0, 255, 0, 255); const tcu::RGBA threshold (1, isMultiSample ? 254 : 1, 1, 1); int numInvalidPixels = 0; bool renderedSomething = false; for (int y = 0; y < result.getHeight(); ++y) { for (int x = 0; x < result.getWidth(); ++x) { const tcu::RGBA resPix = result.getPixel(x, y); const bool isBg = tcu::compareThreshold(resPix, bgRef, threshold); const bool isFg = tcu::compareThreshold(resPix, fgRef, threshold); if (!isBg && !isFg) numInvalidPixels += 1; if (isFg) renderedSomething = true; } } if (numInvalidPixels > 0) { log << TestLog::Image("Result", "Result image", result); log << TestLog::Message << "ERROR: Found " << numInvalidPixels << " invalid result pixels!" << TestLog::EndMessage; return false; } else if (!renderedSomething) { log << TestLog::Image("Result", "Result image", result); log << TestLog::Message << "ERROR: Result image was empty!" << TestLog::EndMessage; return false; } else { log << TestLog::Message << "All result pixels are valid" << TestLog::EndMessage; return true; } } HelperInvocationValueCase::IterateResult HelperInvocationValueCase::iterate (void) { const glu::RenderContext& renderCtx = m_context.getRenderContext(); const glw::Functions& gl = renderCtx.getFunctions(); const string sectionName = string("Iteration ") + de::toString(m_iterNdx+1) + " / " + de::toString(m_numIters); const tcu::ScopedLogSection section (m_testCtx.getLog(), (string("Iter") + de::toString(m_iterNdx)), sectionName); de::Random rnd (deStringHash(getName()) ^ deInt32Hash(m_iterNdx)); tcu::Surface result (FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT); m_fbo->bindForRendering(); gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clear(GL_COLOR_BUFFER_BIT); drawRandomPrimitives(renderCtx, m_program->getProgram(), m_primitiveType, m_numPrimitivesPerIter, &rnd); m_fbo->readPixels(0, 0, result.getAccess()); if (!verifyHelperInvocationValue(m_testCtx.getLog(), result, m_numSamples != 0)) m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid pixels found"); m_iterNdx += 1; return (m_iterNdx < m_numIters) ? CONTINUE : STOP; } //! Checks derivates when value depends on gl_HelperInvocation. class HelperInvocationDerivateCase : public TestCase { public: HelperInvocationDerivateCase (Context& context, const char* name, const char* description, PrimitiveType primType, int numSamples, const char* derivateFunc, bool checkAbsoluteValue); ~HelperInvocationDerivateCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: const PrimitiveType m_primitiveType; const int m_numSamples; const std::string m_derivateFunc; const bool m_checkAbsoluteValue; const int m_numIters; MovePtr<ShaderProgram> m_program; MovePtr<FboHelper> m_fbo; int m_iterNdx; }; HelperInvocationDerivateCase::HelperInvocationDerivateCase (Context& context, const char* name, const char* description, PrimitiveType primType, int numSamples, const char* derivateFunc, bool checkAbsoluteValue) : TestCase (context, name, description) , m_primitiveType (primType) , m_numSamples (numSamples) , m_derivateFunc (derivateFunc) , m_checkAbsoluteValue (checkAbsoluteValue) , m_numIters (16) , m_iterNdx (0) { } HelperInvocationDerivateCase::~HelperInvocationDerivateCase (void) { deinit(); } void HelperInvocationDerivateCase::init (void) { const glu::RenderContext& renderCtx = m_context.getRenderContext(); const glw::Functions& gl = renderCtx.getFunctions(); const int maxSamples = getInteger(gl, GL_MAX_SAMPLES); const int actualSamples = m_numSamples == NUM_SAMPLES_MAX ? maxSamples : m_numSamples; const std::string funcSource = (m_checkAbsoluteValue) ? ("abs(" + m_derivateFunc + "(value))") : (m_derivateFunc + "(value)"); m_program = MovePtr<ShaderProgram>(new ShaderProgram(m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource( "#version 310 es\n" "in highp vec2 a_position;\n" "uniform highp float u_pointSize;\n" "void main (void)\n" "{\n" " gl_Position = vec4(a_position, 0.0, 1.0);\n" " gl_PointSize = u_pointSize;\n" "}\n") << glu::FragmentSource(string( "#version 310 es\n" "out mediump vec4 o_color;\n" "void main (void)\n" "{\n" " highp float value = gl_HelperInvocation ? 1.0 : 0.0;\n" " highp float derivate = ") + funcSource + ";\n" " if (gl_HelperInvocation)\n" " o_color = vec4(1.0, 0.0, derivate, 1.0);\n" " else\n" " o_color = vec4(0.0, 1.0, derivate, 1.0);\n" "}\n"))); m_testCtx.getLog() << *m_program; if (!m_program->isOk()) { m_program.clear(); TCU_FAIL("Compile failed"); } m_testCtx.getLog() << TestLog::Message << "Using GL_RGBA8 framebuffer with " << actualSamples << " samples" << TestLog::EndMessage; m_fbo = MovePtr<FboHelper>(new FboHelper(renderCtx, FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT, FRAMEBUFFER_FORMAT, actualSamples)); m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); } void HelperInvocationDerivateCase::deinit (void) { m_program.clear(); m_fbo.clear(); } static bool hasNeighborWithColor (const tcu::Surface& surface, int x, int y, tcu::RGBA color, tcu::RGBA threshold) { const int w = surface.getWidth(); const int h = surface.getHeight(); for (int dx = -1; dx < 2; dx++) for (int dy = -1; dy < 2; dy++) { const IVec2 pos = IVec2(x + dx, y + dy); if (dx == 0 && dy == 0) continue; if (de::inBounds(pos.x(), 0, w) && de::inBounds(pos.y(), 0, h)) { const tcu::RGBA neighborColor = surface.getPixel(pos.x(), pos.y()); if (tcu::compareThreshold(color, neighborColor, threshold)) return true; } else return true; // Can't know for certain } return false; } static bool verifyHelperInvocationDerivate (TestLog& log, const tcu::Surface& result, bool isMultiSample) { const tcu::RGBA bgRef (0, 0, 0, 255); const tcu::RGBA fgRef (0, 255, 0, 255); const tcu::RGBA isBgThreshold (1, isMultiSample ? 254 : 1, 0, 1); const tcu::RGBA isFgThreshold (1, isMultiSample ? 254 : 1, 255, 1); int numInvalidPixels = 0; int numNonZeroDeriv = 0; bool renderedSomething = false; for (int y = 0; y < result.getHeight(); ++y) { for (int x = 0; x < result.getWidth(); ++x) { const tcu::RGBA resPix = result.getPixel(x, y); const bool isBg = tcu::compareThreshold(resPix, bgRef, isBgThreshold); const bool isFg = tcu::compareThreshold(resPix, fgRef, isFgThreshold); const bool nonZeroDeriv = resPix.getBlue() > 0; const bool neighborBg = nonZeroDeriv ? hasNeighborWithColor(result, x, y, bgRef, isBgThreshold) : false; if (nonZeroDeriv) numNonZeroDeriv += 1; if ((!isBg && !isFg) || // Neither of valid colors (ignoring blue channel that has derivate) (nonZeroDeriv && !neighborBg && !isFg)) // Has non-zero derivate, but sample not at primitive edge or inside primitive numInvalidPixels += 1; if (isFg) renderedSomething = true; } } log << TestLog::Message << "Found " << numNonZeroDeriv << " pixels with non-zero derivate (neighbor sample has gl_HelperInvocation = true)" << TestLog::EndMessage; if (numInvalidPixels > 0) { log << TestLog::Image("Result", "Result image", result); log << TestLog::Message << "ERROR: Found " << numInvalidPixels << " invalid result pixels!" << TestLog::EndMessage; return false; } else if (!renderedSomething) { log << TestLog::Image("Result", "Result image", result); log << TestLog::Message << "ERROR: Result image was empty!" << TestLog::EndMessage; return false; } else { log << TestLog::Message << "All result pixels are valid" << TestLog::EndMessage; return true; } } HelperInvocationDerivateCase::IterateResult HelperInvocationDerivateCase::iterate (void) { const glu::RenderContext& renderCtx = m_context.getRenderContext(); const glw::Functions& gl = renderCtx.getFunctions(); const string sectionName = string("Iteration ") + de::toString(m_iterNdx+1) + " / " + de::toString(m_numIters); const tcu::ScopedLogSection section (m_testCtx.getLog(), (string("Iter") + de::toString(m_iterNdx)), sectionName); de::Random rnd (deStringHash(getName()) ^ deInt32Hash(m_iterNdx)); tcu::Surface result (FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT); m_fbo->bindForRendering(); gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clear(GL_COLOR_BUFFER_BIT); drawRandomPrimitives(renderCtx, m_program->getProgram(), m_primitiveType, 1, &rnd); m_fbo->readPixels(0, 0, result.getAccess()); if (!verifyHelperInvocationDerivate(m_testCtx.getLog(), result, m_numSamples != 0)) m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid pixels found"); m_iterNdx += 1; return (m_iterNdx < m_numIters) ? CONTINUE : STOP; } } // anonymous ShaderHelperInvocationTests::ShaderHelperInvocationTests (Context& context) : TestCaseGroup(context, "helper_invocation", "gl_HelperInvocation tests") { } ShaderHelperInvocationTests::~ShaderHelperInvocationTests (void) { } void ShaderHelperInvocationTests::init (void) { static const struct { const char* caseName; PrimitiveType primType; } s_primTypes[] = { { "triangles", PRIMITIVETYPE_TRIANGLE }, { "lines", PRIMITIVETYPE_LINE }, { "wide_lines", PRIMITIVETYPE_WIDE_LINE }, { "points", PRIMITIVETYPE_POINT }, { "wide_points", PRIMITIVETYPE_WIDE_POINT } }; static const struct { const char* suffix; int numSamples; } s_sampleCounts[] = { { "", 0 }, { "_4_samples", 4 }, { "_8_samples", 8 }, { "_max_samples", NUM_SAMPLES_MAX } }; // value { tcu::TestCaseGroup* const valueGroup = new tcu::TestCaseGroup(m_testCtx, "value", "gl_HelperInvocation value in rendered pixels"); addChild(valueGroup); for (int sampleCountNdx = 0; sampleCountNdx < DE_LENGTH_OF_ARRAY(s_sampleCounts); sampleCountNdx++) { for (int primTypeNdx = 0; primTypeNdx < DE_LENGTH_OF_ARRAY(s_primTypes); primTypeNdx++) { const string name = string(s_primTypes[primTypeNdx].caseName) + s_sampleCounts[sampleCountNdx].suffix; const PrimitiveType primType = s_primTypes[primTypeNdx].primType; const int numSamples = s_sampleCounts[sampleCountNdx].numSamples; valueGroup->addChild(new HelperInvocationValueCase(m_context, name.c_str(), "", primType, numSamples)); } } } // derivate { tcu::TestCaseGroup* const derivateGroup = new tcu::TestCaseGroup(m_testCtx, "derivate", "Derivate of gl_HelperInvocation-dependent value"); addChild(derivateGroup); for (int sampleCountNdx = 0; sampleCountNdx < DE_LENGTH_OF_ARRAY(s_sampleCounts); sampleCountNdx++) { for (int primTypeNdx = 0; primTypeNdx < DE_LENGTH_OF_ARRAY(s_primTypes); primTypeNdx++) { const string name = string(s_primTypes[primTypeNdx].caseName) + s_sampleCounts[sampleCountNdx].suffix; const PrimitiveType primType = s_primTypes[primTypeNdx].primType; const int numSamples = s_sampleCounts[sampleCountNdx].numSamples; derivateGroup->addChild(new HelperInvocationDerivateCase(m_context, (name + "_dfdx").c_str(), "", primType, numSamples, "dFdx", true)); derivateGroup->addChild(new HelperInvocationDerivateCase(m_context, (name + "_dfdy").c_str(), "", primType, numSamples, "dFdy", true)); derivateGroup->addChild(new HelperInvocationDerivateCase(m_context, (name + "_fwidth").c_str(), "", primType, numSamples, "fwidth", false)); } } } } } // Functional } // gles31 } // deqp
32.137552
211
0.704503
TinkerBoard-Android
a17730682a148b2803cd0c22cf338342ed22fd5c
77,288
cpp
C++
B2G/gecko/content/media/MediaStreamGraph.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/content/media/MediaStreamGraph.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/content/media/MediaStreamGraph.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "MediaStreamGraph.h" #include "mozilla/Monitor.h" #include "mozilla/TimeStamp.h" #include "AudioSegment.h" #include "VideoSegment.h" #include "nsContentUtils.h" #include "nsIAppShell.h" #include "nsIObserver.h" #include "nsServiceManagerUtils.h" #include "nsWidgetsCID.h" #include "nsXPCOMCIDInternal.h" #include "prlog.h" #include "VideoUtils.h" #include "mozilla/Attributes.h" #include "TrackUnionStream.h" #include "ImageContainer.h" #include "AudioChannelCommon.h" using namespace mozilla::layers; using namespace mozilla::dom; namespace mozilla { #ifdef PR_LOGGING PRLogModuleInfo* gMediaStreamGraphLog; #define LOG(type, msg) PR_LOG(gMediaStreamGraphLog, type, msg) #else #define LOG(type, msg) #endif namespace { /** * Assume we can run an iteration of the MediaStreamGraph loop in this much time * or less. * We try to run the control loop at this rate. */ const int MEDIA_GRAPH_TARGET_PERIOD_MS = 10; /** * Assume that we might miss our scheduled wakeup of the MediaStreamGraph by * this much. */ const int SCHEDULE_SAFETY_MARGIN_MS = 10; /** * Try have this much audio buffered in streams and queued to the hardware. * The maximum delay to the end of the next control loop * is 2*MEDIA_GRAPH_TARGET_PERIOD_MS + SCHEDULE_SAFETY_MARGIN_MS. * There is no point in buffering more audio than this in a stream at any * given time (until we add processing). * This is not optimal yet. */ const int AUDIO_TARGET_MS = 2*MEDIA_GRAPH_TARGET_PERIOD_MS + SCHEDULE_SAFETY_MARGIN_MS; /** * Try have this much video buffered. Video frames are set * near the end of the iteration of the control loop. The maximum delay * to the setting of the next video frame is 2*MEDIA_GRAPH_TARGET_PERIOD_MS + * SCHEDULE_SAFETY_MARGIN_MS. This is not optimal yet. */ const int VIDEO_TARGET_MS = 2*MEDIA_GRAPH_TARGET_PERIOD_MS + SCHEDULE_SAFETY_MARGIN_MS; /** * A per-stream update message passed from the media graph thread to the * main thread. */ struct StreamUpdate { int64_t mGraphUpdateIndex; nsRefPtr<MediaStream> mStream; StreamTime mNextMainThreadCurrentTime; bool mNextMainThreadFinished; }; /** * This represents a message passed from the main thread to the graph thread. * A ControlMessage always references a particular affected stream. */ class ControlMessage { public: ControlMessage(MediaStream* aStream) : mStream(aStream) { MOZ_COUNT_CTOR(ControlMessage); } // All these run on the graph thread virtual ~ControlMessage() { MOZ_COUNT_DTOR(ControlMessage); } // Do the action of this message on the MediaStreamGraph thread. Any actions // affecting graph processing should take effect at mStateComputedTime. // All stream data for times < mStateComputedTime has already been // computed. virtual void Run() = 0; // When we're shutting down the application, most messages are ignored but // some cleanup messages should still be processed (on the main thread). virtual void RunDuringShutdown() {} MediaStream* GetStream() { return mStream; } protected: // We do not hold a reference to mStream. The graph will be holding // a reference to the stream until the Destroy message is processed. The // last message referencing a stream is the Destroy message for that stream. MediaStream* mStream; }; } /** * The implementation of a media stream graph. This class is private to this * file. It's not in the anonymous namespace because MediaStream needs to * be able to friend it. * * Currently we only have one per process. */ class MediaStreamGraphImpl : public MediaStreamGraph { public: MediaStreamGraphImpl(); ~MediaStreamGraphImpl() { NS_ASSERTION(IsEmpty(), "All streams should have been destroyed by messages from the main thread"); LOG(PR_LOG_DEBUG, ("MediaStreamGraph %p destroyed", this)); } // Main thread only. /** * This runs every time we need to sync state from the media graph thread * to the main thread while the main thread is not in the middle * of a script. It runs during a "stable state" (per HTML5) or during * an event posted to the main thread. */ void RunInStableState(); /** * Ensure a runnable to run RunInStableState is posted to the appshell to * run at the next stable state (per HTML5). * See EnsureStableStateEventPosted. */ void EnsureRunInStableState(); /** * Called to apply a StreamUpdate to its stream. */ void ApplyStreamUpdate(StreamUpdate* aUpdate); /** * Append a ControlMessage to the message queue. This queue is drained * during RunInStableState; the messages will run on the graph thread. */ void AppendMessage(ControlMessage* aMessage); /** * Make this MediaStreamGraph enter forced-shutdown state. This state * will be noticed by the media graph thread, which will shut down all streams * and other state controlled by the media graph thread. * This is called during application shutdown. */ void ForceShutDown(); /** * Shutdown() this MediaStreamGraph's threads and return when they've shut down. */ void ShutdownThreads(); // The following methods run on the graph thread (or possibly the main thread if // mLifecycleState > LIFECYCLE_RUNNING) /** * Runs main control loop on the graph thread. Normally a single invocation * of this runs for the entire lifetime of the graph thread. */ void RunThread(); /** * Call this to indicate that another iteration of the control loop is * required on its regular schedule. The monitor must not be held. */ void EnsureNextIteration(); /** * As above, but with the monitor already held. */ void EnsureNextIterationLocked(MonitorAutoLock& aLock); /** * Call this to indicate that another iteration of the control loop is * required immediately. The monitor must already be held. */ void EnsureImmediateWakeUpLocked(MonitorAutoLock& aLock); /** * Ensure there is an event posted to the main thread to run RunInStableState. * mMonitor must be held. * See EnsureRunInStableState */ void EnsureStableStateEventPosted(); /** * Generate messages to the main thread to update it for all state changes. * mMonitor must be held. */ void PrepareUpdatesToMainThreadState(); // The following methods are the various stages of RunThread processing. /** * Compute a new current time for the graph and advance all on-graph-thread * state to the new current time. */ void UpdateCurrentTime(); /** * Update the consumption state of aStream to reflect whether its data * is needed or not. */ void UpdateConsumptionState(SourceMediaStream* aStream); /** * Extract any state updates pending in aStream, and apply them. */ void ExtractPendingInput(SourceMediaStream* aStream, GraphTime aDesiredUpToTime, bool* aEnsureNextIteration); /** * Update "have enough data" flags in aStream. */ void UpdateBufferSufficiencyState(SourceMediaStream* aStream); /* * If aStream hasn't already been ordered, push it onto aStack and order * its children. */ void UpdateStreamOrderForStream(nsTArray<MediaStream*>* aStack, already_AddRefed<MediaStream> aStream); /** * Compute aStream's mIsConsumed. */ static void DetermineWhetherStreamIsConsumed(MediaStream* aStream); /** * Sort mStreams so that every stream not in a cycle is after any streams * it depends on, and every stream in a cycle is marked as being in a cycle. * Also sets mIsConsumed on every stream. */ void UpdateStreamOrder(); /** * Compute the blocking states of streams from mStateComputedTime * until the desired future time aEndBlockingDecisions. * Updates mStateComputedTime and sets MediaStream::mBlocked * for all streams. */ void RecomputeBlocking(GraphTime aEndBlockingDecisions); // The following methods are used to help RecomputeBlocking. /** * If aStream isn't already in aStreams, add it and recursively call * AddBlockingRelatedStreamsToSet on all the streams whose blocking * status could depend on or affect the state of aStream. */ void AddBlockingRelatedStreamsToSet(nsTArray<MediaStream*>* aStreams, MediaStream* aStream); /** * Mark a stream blocked at time aTime. If this results in decisions that need * to be revisited at some point in the future, *aEnd will be reduced to the * first time in the future to recompute those decisions. */ void MarkStreamBlocking(MediaStream* aStream); /** * Recompute blocking for the streams in aStreams for the interval starting at aTime. * If this results in decisions that need to be revisited at some point * in the future, *aEnd will be reduced to the first time in the future to * recompute those decisions. */ void RecomputeBlockingAt(const nsTArray<MediaStream*>& aStreams, GraphTime aTime, GraphTime aEndBlockingDecisions, GraphTime* aEnd); /** * Returns true if aStream will underrun at aTime for its own playback. * aEndBlockingDecisions is when we plan to stop making blocking decisions. * *aEnd will be reduced to the first time in the future to recompute these * decisions. */ bool WillUnderrun(MediaStream* aStream, GraphTime aTime, GraphTime aEndBlockingDecisions, GraphTime* aEnd); /** * Given a graph time aTime, convert it to a stream time taking into * account the time during which aStream is scheduled to be blocked. */ StreamTime GraphTimeToStreamTime(MediaStream* aStream, GraphTime aTime); enum { INCLUDE_TRAILING_BLOCKED_INTERVAL = 0x01 }; /** * Given a stream time aTime, convert it to a graph time taking into * account the time during which aStream is scheduled to be blocked. * aTime must be <= mStateComputedTime since blocking decisions * are only known up to that point. * If aTime is exactly at the start of a blocked interval, then the blocked * interval is included in the time returned if and only if * aFlags includes INCLUDE_TRAILING_BLOCKED_INTERVAL. */ GraphTime StreamTimeToGraphTime(MediaStream* aStream, StreamTime aTime, uint32_t aFlags = 0); /** * Get the current audio position of the stream's audio output. */ GraphTime GetAudioPosition(MediaStream* aStream); /** * Call NotifyHaveCurrentData on aStream's listeners. */ void NotifyHasCurrentData(MediaStream* aStream); /** * If aStream needs an audio stream but doesn't have one, create it. * If aStream doesn't need an audio stream but has one, destroy it. */ void CreateOrDestroyAudioStreams(GraphTime aAudioOutputStartTime, MediaStream* aStream); /** * Queue audio (mix of stream audio and silence for blocked intervals) * to the audio output stream. */ void PlayAudio(MediaStream* aStream, GraphTime aFrom, GraphTime aTo); /** * Set the correct current video frame for stream aStream. */ void PlayVideo(MediaStream* aStream); /** * No more data will be forthcoming for aStream. The stream will end * at the current buffer end point. The StreamBuffer's tracks must be * explicitly set to finished by the caller. */ void FinishStream(MediaStream* aStream); /** * Compute how much stream data we would like to buffer for aStream. */ StreamTime GetDesiredBufferEnd(MediaStream* aStream); /** * Returns true when there are no active streams. */ bool IsEmpty() { return mStreams.IsEmpty() && mPortCount == 0; } // For use by control messages /** * Identify which graph update index we are currently processing. */ int64_t GetProcessingGraphUpdateIndex() { return mProcessingGraphUpdateIndex; } /** * Add aStream to the graph and initializes its graph-specific state. */ void AddStream(MediaStream* aStream); /** * Remove aStream from the graph. Ensures that pending messages about the * stream back to the main thread are flushed. */ void RemoveStream(MediaStream* aStream); /** * Remove aPort from the graph and release it. */ void DestroyPort(MediaInputPort* aPort); // Data members /** * Media graph thread. * Readonly after initialization on the main thread. */ nsCOMPtr<nsIThread> mThread; // The following state is managed on the graph thread only, unless // mLifecycleState > LIFECYCLE_RUNNING in which case the graph thread // is not running and this state can be used from the main thread. nsTArray<nsRefPtr<MediaStream> > mStreams; /** * The current graph time for the current iteration of the RunThread control * loop. */ GraphTime mCurrentTime; /** * Blocking decisions and all stream contents have been computed up to this * time. The next batch of updates from the main thread will be processed * at this time. Always >= mCurrentTime. */ GraphTime mStateComputedTime; /** * This is only used for logging. */ TimeStamp mInitialTimeStamp; /** * The real timestamp of the latest run of UpdateCurrentTime. */ TimeStamp mCurrentTimeStamp; /** * Which update batch we are currently processing. */ int64_t mProcessingGraphUpdateIndex; /** * Number of active MediaInputPorts */ int32_t mPortCount; // mMonitor guards the data below. // MediaStreamGraph normally does its work without holding mMonitor, so it is // not safe to just grab mMonitor from some thread and start monkeying with // the graph. Instead, communicate with the graph thread using provided // mechanisms such as the ControlMessage queue. Monitor mMonitor; // Data guarded by mMonitor (must always be accessed with mMonitor held, // regardless of the value of mLifecycleState. /** * State to copy to main thread */ nsTArray<StreamUpdate> mStreamUpdates; /** * Runnables to run after the next update to main thread state. */ nsTArray<nsCOMPtr<nsIRunnable> > mUpdateRunnables; struct MessageBlock { int64_t mGraphUpdateIndex; nsTArray<nsAutoPtr<ControlMessage> > mMessages; }; /** * A list of batches of messages to process. Each batch is processed * as an atomic unit. */ nsTArray<MessageBlock> mMessageQueue; /** * This enum specifies where this graph is in its lifecycle. This is used * to control shutdown. * Shutdown is tricky because it can happen in two different ways: * 1) Shutdown due to inactivity. RunThread() detects that it has no * pending messages and no streams, and exits. The next RunInStableState() * checks if there are new pending messages from the main thread (true only * if new stream creation raced with shutdown); if there are, it revives * RunThread(), otherwise it commits to shutting down the graph. New stream * creation after this point will create a new graph. An async event is * dispatched to Shutdown() the graph's threads and then delete the graph * object. * 2) Forced shutdown at application shutdown. A flag is set, RunThread() * detects the flag and exits, the next RunInStableState() detects the flag, * and dispatches the async event to Shutdown() the graph's threads. However * the graph object is not deleted. New messages for the graph are processed * synchronously on the main thread if necessary. When the last stream is * destroyed, the graph object is deleted. */ enum LifecycleState { // The graph thread hasn't started yet. LIFECYCLE_THREAD_NOT_STARTED, // RunThread() is running normally. LIFECYCLE_RUNNING, // In the following states, the graph thread is not running so // all "graph thread only" state in this class can be used safely // on the main thread. // RunThread() has exited and we're waiting for the next // RunInStableState(), at which point we can clean up the main-thread // side of the graph. LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP, // RunInStableState() posted a ShutdownRunnable, and we're waiting for it // to shut down the graph thread(s). LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN, // Graph threads have shut down but we're waiting for remaining streams // to be destroyed. Only happens during application shutdown since normally // we'd only shut down a graph when it has no streams. LIFECYCLE_WAITING_FOR_STREAM_DESTRUCTION }; LifecycleState mLifecycleState; /** * This enum specifies the wait state of the graph thread. */ enum WaitState { // RunThread() is running normally WAITSTATE_RUNNING, // RunThread() is paused waiting for its next iteration, which will // happen soon WAITSTATE_WAITING_FOR_NEXT_ITERATION, // RunThread() is paused indefinitely waiting for something to change WAITSTATE_WAITING_INDEFINITELY, // Something has signaled RunThread() to wake up immediately, // but it hasn't done so yet WAITSTATE_WAKING_UP }; WaitState mWaitState; /** * True when another iteration of the control loop is required. */ bool mNeedAnotherIteration; /** * True when we need to do a forced shutdown during application shutdown. */ bool mForceShutDown; /** * True when we have posted an event to the main thread to run * RunInStableState() and the event hasn't run yet. */ bool mPostedRunInStableStateEvent; // Main thread only /** * Messages posted by the current event loop task. These are forwarded to * the media graph thread during RunInStableState. We can't forward them * immediately because we want all messages between stable states to be * processed as an atomic batch. */ nsTArray<nsAutoPtr<ControlMessage> > mCurrentTaskMessageQueue; /** * True when RunInStableState has determined that mLifecycleState is > * LIFECYCLE_RUNNING. Since only the main thread can reset mLifecycleState to * LIFECYCLE_RUNNING, this can be relied on to not change unexpectedly. */ bool mDetectedNotRunning; /** * True when a stable state runner has been posted to the appshell to run * RunInStableState at the next stable state. */ bool mPostedRunInStableState; }; /** * The singleton graph instance. */ static MediaStreamGraphImpl* gGraph; StreamTime MediaStreamGraphImpl::GetDesiredBufferEnd(MediaStream* aStream) { StreamTime current = mCurrentTime - aStream->mBufferStartTime; return current + MillisecondsToMediaTime(NS_MAX(AUDIO_TARGET_MS, VIDEO_TARGET_MS)); } void MediaStreamGraphImpl::FinishStream(MediaStream* aStream) { if (aStream->mFinished) return; printf("MediaStreamGraphImpl::FinishStream\n"); LOG(PR_LOG_DEBUG, ("MediaStream %p will finish", aStream)); aStream->mFinished = true; // Force at least one more iteration of the control loop, since we rely // on UpdateCurrentTime to notify our listeners once the stream end // has been reached. EnsureNextIteration(); } void MediaStreamGraphImpl::AddStream(MediaStream* aStream) { aStream->mBufferStartTime = mCurrentTime; *mStreams.AppendElement() = already_AddRefed<MediaStream>(aStream); LOG(PR_LOG_DEBUG, ("Adding media stream %p to the graph", aStream)); } void MediaStreamGraphImpl::RemoveStream(MediaStream* aStream) { // Remove references in mStreamUpdates before we allow aStream to die. // Pending updates are not needed (since the main thread has already given // up the stream) so we will just drop them. { MonitorAutoLock lock(mMonitor); for (uint32_t i = 0; i < mStreamUpdates.Length(); ++i) { if (mStreamUpdates[i].mStream == aStream) { mStreamUpdates[i].mStream = nullptr; } } } // This unrefs the stream, probably destroying it mStreams.RemoveElement(aStream); LOG(PR_LOG_DEBUG, ("Removing media stream %p from the graph", aStream)); } void MediaStreamGraphImpl::UpdateConsumptionState(SourceMediaStream* aStream) { MediaStreamListener::Consumption state = aStream->mIsConsumed ? MediaStreamListener::CONSUMED : MediaStreamListener::NOT_CONSUMED; if (state != aStream->mLastConsumptionState) { aStream->mLastConsumptionState = state; for (uint32_t j = 0; j < aStream->mListeners.Length(); ++j) { MediaStreamListener* l = aStream->mListeners[j]; l->NotifyConsumptionChanged(this, state); } } } void MediaStreamGraphImpl::ExtractPendingInput(SourceMediaStream* aStream, GraphTime aDesiredUpToTime, bool* aEnsureNextIteration) { bool finished; { MutexAutoLock lock(aStream->mMutex); if (aStream->mPullEnabled) { for (uint32_t j = 0; j < aStream->mListeners.Length(); ++j) { MediaStreamListener* l = aStream->mListeners[j]; { // Compute how much stream time we'll need assuming we don't block // the stream at all between mBlockingDecisionsMadeUntilTime and // aDesiredUpToTime. StreamTime t = GraphTimeToStreamTime(aStream, mStateComputedTime) + (aDesiredUpToTime - mStateComputedTime); MutexAutoUnlock unlock(aStream->mMutex); l->NotifyPull(this, t); *aEnsureNextIteration = true; } } } finished = aStream->mUpdateFinished; for (int32_t i = aStream->mUpdateTracks.Length() - 1; i >= 0; --i) { SourceMediaStream::TrackData* data = &aStream->mUpdateTracks[i]; for (uint32_t j = 0; j < aStream->mListeners.Length(); ++j) { MediaStreamListener* l = aStream->mListeners[j]; TrackTicks offset = (data->mCommands & SourceMediaStream::TRACK_CREATE) ? data->mStart : aStream->mBuffer.FindTrack(data->mID)->GetSegment()->GetDuration(); l->NotifyQueuedTrackChanges(this, data->mID, data->mRate, offset, data->mCommands, *data->mData); } if (data->mCommands & SourceMediaStream::TRACK_CREATE) { MediaSegment* segment = data->mData.forget(); LOG(PR_LOG_DEBUG, ("SourceMediaStream %p creating track %d, rate %d, start %lld, initial end %lld", aStream, data->mID, data->mRate, int64_t(data->mStart), int64_t(segment->GetDuration()))); aStream->mBuffer.AddTrack(data->mID, data->mRate, data->mStart, segment); // The track has taken ownership of data->mData, so let's replace // data->mData with an empty clone. data->mData = segment->CreateEmptyClone(); data->mCommands &= ~SourceMediaStream::TRACK_CREATE; } else if (data->mData->GetDuration() > 0) { MediaSegment* dest = aStream->mBuffer.FindTrack(data->mID)->GetSegment(); LOG(PR_LOG_DEBUG, ("SourceMediaStream %p track %d, advancing end from %lld to %lld", aStream, data->mID, int64_t(dest->GetDuration()), int64_t(dest->GetDuration() + data->mData->GetDuration()))); dest->AppendFrom(data->mData); } if (data->mCommands & SourceMediaStream::TRACK_END) { aStream->mBuffer.FindTrack(data->mID)->SetEnded(); aStream->mUpdateTracks.RemoveElementAt(i); } } aStream->mBuffer.AdvanceKnownTracksTime(aStream->mUpdateKnownTracksTime); } if (finished) { FinishStream(aStream); } } void MediaStreamGraphImpl::UpdateBufferSufficiencyState(SourceMediaStream* aStream) { StreamTime desiredEnd = GetDesiredBufferEnd(aStream); nsTArray<SourceMediaStream::ThreadAndRunnable> runnables; { MutexAutoLock lock(aStream->mMutex); for (uint32_t i = 0; i < aStream->mUpdateTracks.Length(); ++i) { SourceMediaStream::TrackData* data = &aStream->mUpdateTracks[i]; if (data->mCommands & SourceMediaStream::TRACK_CREATE) { // This track hasn't been created yet, so we have no sufficiency // data. The track will be created in the next iteration of the // control loop and then we'll fire insufficiency notifications // if necessary. continue; } if (data->mCommands & SourceMediaStream::TRACK_END) { // This track will end, so no point in firing not-enough-data // callbacks. continue; } StreamBuffer::Track* track = aStream->mBuffer.FindTrack(data->mID); // Note that track->IsEnded() must be false, otherwise we would have // removed the track from mUpdateTracks already. NS_ASSERTION(!track->IsEnded(), "What is this track doing here?"); data->mHaveEnough = track->GetEndTimeRoundDown() >= desiredEnd; if (!data->mHaveEnough) { runnables.MoveElementsFrom(data->mDispatchWhenNotEnough); } } } for (uint32_t i = 0; i < runnables.Length(); ++i) { runnables[i].mThread->Dispatch(runnables[i].mRunnable, 0); } } StreamTime MediaStreamGraphImpl::GraphTimeToStreamTime(MediaStream* aStream, GraphTime aTime) { NS_ASSERTION(aTime <= mStateComputedTime, "Don't ask about times where we haven't made blocking decisions yet"); if (aTime <= mCurrentTime) { return NS_MAX<StreamTime>(0, aTime - aStream->mBufferStartTime); } GraphTime t = mCurrentTime; StreamTime s = t - aStream->mBufferStartTime; while (t < aTime) { GraphTime end; if (!aStream->mBlocked.GetAt(t, &end)) { s += NS_MIN(aTime, end) - t; } t = end; } return NS_MAX<StreamTime>(0, s); } GraphTime MediaStreamGraphImpl::StreamTimeToGraphTime(MediaStream* aStream, StreamTime aTime, uint32_t aFlags) { if (aTime >= STREAM_TIME_MAX) { return GRAPH_TIME_MAX; } MediaTime bufferElapsedToCurrentTime = mCurrentTime - aStream->mBufferStartTime; if (aTime < bufferElapsedToCurrentTime || (aTime == bufferElapsedToCurrentTime && !(aFlags & INCLUDE_TRAILING_BLOCKED_INTERVAL))) { return aTime + aStream->mBufferStartTime; } MediaTime streamAmount = aTime - bufferElapsedToCurrentTime; NS_ASSERTION(streamAmount >= 0, "Can't answer queries before current time"); GraphTime t = mCurrentTime; while (t < GRAPH_TIME_MAX) { bool blocked; GraphTime end; if (t < mStateComputedTime) { blocked = aStream->mBlocked.GetAt(t, &end); end = NS_MIN(end, mStateComputedTime); } else { blocked = false; end = GRAPH_TIME_MAX; } if (blocked) { t = end; } else { if (streamAmount == 0) { // No more stream time to consume at time t, so we're done. break; } MediaTime consume = NS_MIN(end - t, streamAmount); streamAmount -= consume; t += consume; } } return t; } GraphTime MediaStreamGraphImpl::GetAudioPosition(MediaStream* aStream) { if (aStream->mAudioOutputStreams.IsEmpty()) { return mCurrentTime; } int64_t positionInFrames = aStream->mAudioOutputStreams[0].mStream->GetPositionInFrames(); if (positionInFrames < 0) { return mCurrentTime; } return aStream->mAudioOutputStreams[0].mAudioPlaybackStartTime + TicksToTimeRoundDown(aStream->mAudioOutputStreams[0].mStream->GetRate(), positionInFrames); } void MediaStreamGraphImpl::UpdateCurrentTime() { GraphTime prevCurrentTime = mCurrentTime; TimeStamp now = TimeStamp::Now(); GraphTime nextCurrentTime = SecondsToMediaTime((now - mCurrentTimeStamp).ToSeconds()) + mCurrentTime; if (mStateComputedTime < nextCurrentTime) { LOG(PR_LOG_WARNING, ("Media graph global underrun detected")); LOG(PR_LOG_DEBUG, ("Advancing mStateComputedTime from %f to %f", MediaTimeToSeconds(mStateComputedTime), MediaTimeToSeconds(nextCurrentTime))); // Advance mStateComputedTime to nextCurrentTime by // adding blocked time to all streams starting at mStateComputedTime for (uint32_t i = 0; i < mStreams.Length(); ++i) { mStreams[i]->mBlocked.SetAtAndAfter(mStateComputedTime, true); } mStateComputedTime = nextCurrentTime; } mCurrentTimeStamp = now; LOG(PR_LOG_DEBUG, ("Updating current time to %f (real %f, mStateComputedTime %f)", MediaTimeToSeconds(nextCurrentTime), (now - mInitialTimeStamp).ToSeconds(), MediaTimeToSeconds(mStateComputedTime))); if (prevCurrentTime >= nextCurrentTime) { NS_ASSERTION(prevCurrentTime == nextCurrentTime, "Time can't go backwards!"); // This could happen due to low clock resolution, maybe? LOG(PR_LOG_DEBUG, ("Time did not advance")); // There's not much left to do here, but the code below that notifies // listeners that streams have ended still needs to run. } for (uint32_t i = 0; i < mStreams.Length(); ++i) { MediaStream* stream = mStreams[i]; // Calculate blocked time and fire Blocked/Unblocked events GraphTime blockedTime = 0; GraphTime t = prevCurrentTime; // Save current blocked status bool wasBlocked = stream->mBlocked.GetAt(prevCurrentTime); while (t < nextCurrentTime) { GraphTime end; bool blocked = stream->mBlocked.GetAt(t, &end); if (blocked) { blockedTime += NS_MIN(end, nextCurrentTime) - t; } if (blocked != wasBlocked) { for (uint32_t j = 0; j < stream->mListeners.Length(); ++j) { MediaStreamListener* l = stream->mListeners[j]; l->NotifyBlockingChanged(this, blocked ? MediaStreamListener::BLOCKED : MediaStreamListener::UNBLOCKED); } wasBlocked = blocked; } t = end; } stream->AdvanceTimeVaryingValuesToCurrentTime(nextCurrentTime, blockedTime); // Advance mBlocked last so that implementations of // AdvanceTimeVaryingValuesToCurrentTime can rely on the value of mBlocked. stream->mBlocked.AdvanceCurrentTime(nextCurrentTime); if (blockedTime < nextCurrentTime - prevCurrentTime) { for (uint32_t i = 0; i < stream->mListeners.Length(); ++i) { MediaStreamListener* l = stream->mListeners[i]; l->NotifyOutput(this); } } if (stream->mFinished && !stream->mNotifiedFinished && stream->mBufferStartTime + stream->GetBufferEnd() <= nextCurrentTime) { stream->mNotifiedFinished = true; stream->mLastPlayedVideoFrame.SetNull(); for (uint32_t j = 0; j < stream->mListeners.Length(); ++j) { MediaStreamListener* l = stream->mListeners[j]; l->NotifyFinished(this); } } LOG(PR_LOG_DEBUG, ("MediaStream %p bufferStartTime=%f blockedTime=%f", stream, MediaTimeToSeconds(stream->mBufferStartTime), MediaTimeToSeconds(blockedTime))); } mCurrentTime = nextCurrentTime; } bool MediaStreamGraphImpl::WillUnderrun(MediaStream* aStream, GraphTime aTime, GraphTime aEndBlockingDecisions, GraphTime* aEnd) { // Finished streams can't underrun. ProcessedMediaStreams also can't cause // underrun currently, since we'll always be able to produce data for them // unless they block on some other stream. if (aStream->mFinished || aStream->AsProcessedStream()) { return false; } GraphTime bufferEnd = StreamTimeToGraphTime(aStream, aStream->GetBufferEnd(), INCLUDE_TRAILING_BLOCKED_INTERVAL); NS_ASSERTION(bufferEnd >= mCurrentTime, "Buffer underran"); // We should block after bufferEnd. if (bufferEnd <= aTime) { LOG(PR_LOG_DEBUG, ("MediaStream %p will block due to data underrun, " "bufferEnd %f", aStream, MediaTimeToSeconds(bufferEnd))); return true; } // We should keep blocking if we're currently blocked and we don't have // data all the way through to aEndBlockingDecisions. If we don't have // data all the way through to aEndBlockingDecisions, we'll block soon, // but we might as well remain unblocked and play the data we've got while // we can. if (bufferEnd <= aEndBlockingDecisions && aStream->mBlocked.GetBefore(aTime)) { LOG(PR_LOG_DEBUG, ("MediaStream %p will block due to speculative data underrun, " "bufferEnd %f", aStream, MediaTimeToSeconds(bufferEnd))); return true; } // Reconsider decisions at bufferEnd *aEnd = NS_MIN(*aEnd, bufferEnd); return false; } void MediaStreamGraphImpl::DetermineWhetherStreamIsConsumed(MediaStream* aStream) { if (aStream->mKnowIsConsumed) return; aStream->mKnowIsConsumed = true; if (!aStream->mAudioOutputs.IsEmpty() || !aStream->mVideoOutputs.IsEmpty()) { aStream->mIsConsumed = true; return; } for (uint32_t i = 0; i < aStream->mConsumers.Length(); ++i) { MediaStream* dest = aStream->mConsumers[i]->mDest; DetermineWhetherStreamIsConsumed(dest); if (dest->mIsConsumed) { aStream->mIsConsumed = true; return; } } } void MediaStreamGraphImpl::UpdateStreamOrderForStream(nsTArray<MediaStream*>* aStack, already_AddRefed<MediaStream> aStream) { nsRefPtr<MediaStream> stream = aStream; NS_ASSERTION(!stream->mHasBeenOrdered, "stream should not have already been ordered"); if (stream->mIsOnOrderingStack) { for (int32_t i = aStack->Length() - 1; ; --i) { aStack->ElementAt(i)->AsProcessedStream()->mInCycle = true; if (aStack->ElementAt(i) == stream) break; } return; } DetermineWhetherStreamIsConsumed(stream); ProcessedMediaStream* ps = stream->AsProcessedStream(); if (ps) { aStack->AppendElement(stream); stream->mIsOnOrderingStack = true; for (uint32_t i = 0; i < ps->mInputs.Length(); ++i) { MediaStream* source = ps->mInputs[i]->mSource; if (!source->mHasBeenOrdered) { nsRefPtr<MediaStream> s = source; UpdateStreamOrderForStream(aStack, s.forget()); } } aStack->RemoveElementAt(aStack->Length() - 1); stream->mIsOnOrderingStack = false; } stream->mHasBeenOrdered = true; *mStreams.AppendElement() = stream.forget(); } void MediaStreamGraphImpl::UpdateStreamOrder() { nsTArray<nsRefPtr<MediaStream> > oldStreams; oldStreams.SwapElements(mStreams); for (uint32_t i = 0; i < oldStreams.Length(); ++i) { MediaStream* stream = oldStreams[i]; stream->mHasBeenOrdered = false; stream->mKnowIsConsumed = false; stream->mIsConsumed = false; stream->mIsOnOrderingStack = false; stream->mInBlockingSet = false; ProcessedMediaStream* ps = stream->AsProcessedStream(); if (ps) { ps->mInCycle = false; } } nsAutoTArray<MediaStream*,10> stack; for (uint32_t i = 0; i < oldStreams.Length(); ++i) { if (!oldStreams[i]->mHasBeenOrdered) { UpdateStreamOrderForStream(&stack, oldStreams[i].forget()); } } } void MediaStreamGraphImpl::RecomputeBlocking(GraphTime aEndBlockingDecisions) { bool blockingDecisionsWillChange = false; LOG(PR_LOG_DEBUG, ("Media graph %p computing blocking for time %f", this, MediaTimeToSeconds(mStateComputedTime))); for (uint32_t i = 0; i < mStreams.Length(); ++i) { MediaStream* stream = mStreams[i]; if (!stream->mInBlockingSet) { // Compute a partition of the streams containing 'stream' such that we can // compute the blocking status of each subset independently. nsAutoTArray<MediaStream*,10> streamSet; AddBlockingRelatedStreamsToSet(&streamSet, stream); GraphTime end; for (GraphTime t = mStateComputedTime; t < aEndBlockingDecisions; t = end) { end = GRAPH_TIME_MAX; RecomputeBlockingAt(streamSet, t, aEndBlockingDecisions, &end); if (end < GRAPH_TIME_MAX) { blockingDecisionsWillChange = true; } } } GraphTime end; stream->mBlocked.GetAt(mCurrentTime, &end); if (end < GRAPH_TIME_MAX) { blockingDecisionsWillChange = true; } } LOG(PR_LOG_DEBUG, ("Media graph %p computed blocking for interval %f to %f", this, MediaTimeToSeconds(mStateComputedTime), MediaTimeToSeconds(aEndBlockingDecisions))); mStateComputedTime = aEndBlockingDecisions; if (blockingDecisionsWillChange) { // Make sure we wake up to notify listeners about these changes. EnsureNextIteration(); } } void MediaStreamGraphImpl::AddBlockingRelatedStreamsToSet(nsTArray<MediaStream*>* aStreams, MediaStream* aStream) { if (aStream->mInBlockingSet) return; aStream->mInBlockingSet = true; aStreams->AppendElement(aStream); for (uint32_t i = 0; i < aStream->mConsumers.Length(); ++i) { MediaInputPort* port = aStream->mConsumers[i]; if (port->mFlags & (MediaInputPort::FLAG_BLOCK_INPUT | MediaInputPort::FLAG_BLOCK_OUTPUT)) { AddBlockingRelatedStreamsToSet(aStreams, port->mDest); } } ProcessedMediaStream* ps = aStream->AsProcessedStream(); if (ps) { for (uint32_t i = 0; i < ps->mInputs.Length(); ++i) { MediaInputPort* port = ps->mInputs[i]; if (port->mFlags & (MediaInputPort::FLAG_BLOCK_INPUT | MediaInputPort::FLAG_BLOCK_OUTPUT)) { AddBlockingRelatedStreamsToSet(aStreams, port->mSource); } } } } void MediaStreamGraphImpl::MarkStreamBlocking(MediaStream* aStream) { if (aStream->mBlockInThisPhase) return; aStream->mBlockInThisPhase = true; for (uint32_t i = 0; i < aStream->mConsumers.Length(); ++i) { MediaInputPort* port = aStream->mConsumers[i]; if (port->mFlags & MediaInputPort::FLAG_BLOCK_OUTPUT) { MarkStreamBlocking(port->mDest); } } ProcessedMediaStream* ps = aStream->AsProcessedStream(); if (ps) { for (uint32_t i = 0; i < ps->mInputs.Length(); ++i) { MediaInputPort* port = ps->mInputs[i]; if (port->mFlags & MediaInputPort::FLAG_BLOCK_INPUT) { MarkStreamBlocking(port->mSource); } } } } void MediaStreamGraphImpl::RecomputeBlockingAt(const nsTArray<MediaStream*>& aStreams, GraphTime aTime, GraphTime aEndBlockingDecisions, GraphTime* aEnd) { for (uint32_t i = 0; i < aStreams.Length(); ++i) { MediaStream* stream = aStreams[i]; stream->mBlockInThisPhase = false; } for (uint32_t i = 0; i < aStreams.Length(); ++i) { MediaStream* stream = aStreams[i]; if (stream->mFinished) { GraphTime endTime = StreamTimeToGraphTime(stream, stream->GetBufferEnd()); if (endTime <= aTime) { LOG(PR_LOG_DEBUG, ("MediaStream %p is blocked due to being finished", stream)); // We'll block indefinitely MarkStreamBlocking(stream); *aEnd = aEndBlockingDecisions; continue; } else { LOG(PR_LOG_DEBUG, ("MediaStream %p is finished, but not blocked yet (end at %f, with blocking at %f)", stream, MediaTimeToSeconds(stream->GetBufferEnd()), MediaTimeToSeconds(endTime))); *aEnd = NS_MIN(*aEnd, endTime); } } GraphTime end; bool explicitBlock = stream->mExplicitBlockerCount.GetAt(aTime, &end) > 0; *aEnd = NS_MIN(*aEnd, end); if (explicitBlock) { LOG(PR_LOG_DEBUG, ("MediaStream %p is blocked due to explicit blocker", stream)); MarkStreamBlocking(stream); continue; } bool underrun = WillUnderrun(stream, aTime, aEndBlockingDecisions, aEnd); if (underrun) { // We'll block indefinitely MarkStreamBlocking(stream); *aEnd = aEndBlockingDecisions; continue; } } NS_ASSERTION(*aEnd > aTime, "Failed to advance!"); for (uint32_t i = 0; i < aStreams.Length(); ++i) { MediaStream* stream = aStreams[i]; stream->mBlocked.SetAtAndAfter(aTime, stream->mBlockInThisPhase); } } void MediaStreamGraphImpl::NotifyHasCurrentData(MediaStream* aStream) { for (uint32_t j = 0; j < aStream->mListeners.Length(); ++j) { MediaStreamListener* l = aStream->mListeners[j]; l->NotifyHasCurrentData(this, GraphTimeToStreamTime(aStream, mCurrentTime) < aStream->mBuffer.GetEnd()); } } void MediaStreamGraphImpl::CreateOrDestroyAudioStreams(GraphTime aAudioOutputStartTime, MediaStream* aStream) { nsAutoTArray<bool,2> audioOutputStreamsFound; for (uint32_t i = 0; i < aStream->mAudioOutputStreams.Length(); ++i) { audioOutputStreamsFound.AppendElement(false); } if (!aStream->mAudioOutputs.IsEmpty()) { for (StreamBuffer::TrackIter tracks(aStream->GetStreamBuffer(), MediaSegment::AUDIO); !tracks.IsEnded(); tracks.Next()) { uint32_t i; for (i = 0; i < audioOutputStreamsFound.Length(); ++i) { if (aStream->mAudioOutputStreams[i].mTrackID == tracks->GetID()) { break; } } if (i < audioOutputStreamsFound.Length()) { audioOutputStreamsFound[i] = true; } else { // No output stream created for this track yet. Check if it's time to // create one. GraphTime startTime = StreamTimeToGraphTime(aStream, tracks->GetStartTimeRoundDown(), INCLUDE_TRAILING_BLOCKED_INTERVAL); if (startTime >= mStateComputedTime) { // The stream wants to play audio, but nothing will play for the forseeable // future, so don't create the stream. continue; } // XXX allocating a nsAudioStream could be slow so we're going to have to do // something here ... preallocation, async allocation, multiplexing onto a single // stream ... AudioSegment* audio = tracks->Get<AudioSegment>(); MediaStream::AudioOutputStream* audioOutputStream = aStream->mAudioOutputStreams.AppendElement(); audioOutputStream->mAudioPlaybackStartTime = aAudioOutputStartTime; audioOutputStream->mBlockedAudioTime = 0; audioOutputStream->mStream = nsAudioStream::AllocateStream(); audioOutputStream->mStream->Init(audio->GetChannels(), tracks->GetRate(), AUDIO_CHANNEL_NORMAL); audioOutputStream->mTrackID = tracks->GetID(); } } } for (int32_t i = audioOutputStreamsFound.Length() - 1; i >= 0; --i) { if (!audioOutputStreamsFound[i]) { aStream->mAudioOutputStreams[i].mStream->Shutdown(); aStream->mAudioOutputStreams.RemoveElementAt(i); } } } void MediaStreamGraphImpl::PlayAudio(MediaStream* aStream, GraphTime aFrom, GraphTime aTo) { if (aStream->mAudioOutputStreams.IsEmpty()) { return; } // When we're playing multiple copies of this stream at the same time, they're // perfectly correlated so adding volumes is the right thing to do. float volume = 0.0f; for (uint32_t i = 0; i < aStream->mAudioOutputs.Length(); ++i) { volume += aStream->mAudioOutputs[i].mVolume; } for (uint32_t i = 0; i < aStream->mAudioOutputStreams.Length(); ++i) { MediaStream::AudioOutputStream& audioOutput = aStream->mAudioOutputStreams[i]; StreamBuffer::Track* track = aStream->mBuffer.FindTrack(audioOutput.mTrackID); AudioSegment* audio = track->Get<AudioSegment>(); // We don't update aStream->mBufferStartTime here to account for // time spent blocked. Instead, we'll update it in UpdateCurrentTime after the // blocked period has completed. But we do need to make sure we play from the // right offsets in the stream buffer, even if we've already written silence for // some amount of blocked time after the current time. GraphTime t = aFrom; while (t < aTo) { GraphTime end; bool blocked = aStream->mBlocked.GetAt(t, &end); end = NS_MIN(end, aTo); AudioSegment output; output.InitFrom(*audio); if (blocked) { // Track total blocked time in aStream->mBlockedAudioTime so that // the amount of silent samples we've inserted for blocking never gets // more than one sample away from the ideal amount. TrackTicks startTicks = TimeToTicksRoundDown(track->GetRate(), audioOutput.mBlockedAudioTime); audioOutput.mBlockedAudioTime += end - t; TrackTicks endTicks = TimeToTicksRoundDown(track->GetRate(), audioOutput.mBlockedAudioTime); output.InsertNullDataAtStart(endTicks - startTicks); LOG(PR_LOG_DEBUG, ("MediaStream %p writing blocking-silence samples for %f to %f", aStream, MediaTimeToSeconds(t), MediaTimeToSeconds(end))); } else { TrackTicks startTicks = track->TimeToTicksRoundDown(GraphTimeToStreamTime(aStream, t)); TrackTicks endTicks = track->TimeToTicksRoundDown(GraphTimeToStreamTime(aStream, end)); // If startTicks is before the track start, then that part of 'audio' // will just be silence, which is fine here. But if endTicks is after // the track end, then 'audio' won't be long enough, so we'll need // to explicitly play silence. TrackTicks sliceEnd = NS_MIN(endTicks, audio->GetDuration()); if (sliceEnd > startTicks) { output.AppendSlice(*audio, startTicks, sliceEnd); } // Play silence where the track has ended output.AppendNullData(endTicks - sliceEnd); NS_ASSERTION(endTicks == sliceEnd || track->IsEnded(), "Ran out of data but track not ended?"); output.ApplyVolume(volume); LOG(PR_LOG_DEBUG, ("MediaStream %p writing samples for %f to %f (samples %lld to %lld)", aStream, MediaTimeToSeconds(t), MediaTimeToSeconds(end), startTicks, endTicks)); } output.WriteTo(audioOutput.mStream); t = end; } } } void MediaStreamGraphImpl::PlayVideo(MediaStream* aStream) { if (aStream->mVideoOutputs.IsEmpty()) return; // Display the next frame a bit early. This is better than letting the current // frame be displayed for too long. GraphTime framePosition = mCurrentTime + MEDIA_GRAPH_TARGET_PERIOD_MS; NS_ASSERTION(framePosition >= aStream->mBufferStartTime, "frame position before buffer?"); StreamTime frameBufferTime = GraphTimeToStreamTime(aStream, framePosition); TrackTicks start; const VideoFrame* frame = nullptr; StreamBuffer::Track* track; for (StreamBuffer::TrackIter tracks(aStream->GetStreamBuffer(), MediaSegment::VIDEO); !tracks.IsEnded(); tracks.Next()) { VideoSegment* segment = tracks->Get<VideoSegment>(); TrackTicks thisStart; const VideoFrame* thisFrame = segment->GetFrameAt(tracks->TimeToTicksRoundDown(frameBufferTime), &thisStart); if (thisFrame && thisFrame->GetImage()) { start = thisStart; frame = thisFrame; track = tracks.get(); } } if (!frame || *frame == aStream->mLastPlayedVideoFrame) return; LOG(PR_LOG_DEBUG, ("MediaStream %p writing video frame %p (%dx%d)", aStream, frame->GetImage(), frame->GetIntrinsicSize().width, frame->GetIntrinsicSize().height)); GraphTime startTime = StreamTimeToGraphTime(aStream, track->TicksToTimeRoundDown(start), INCLUDE_TRAILING_BLOCKED_INTERVAL); TimeStamp targetTime = mCurrentTimeStamp + TimeDuration::FromMilliseconds(double(startTime - mCurrentTime)); for (uint32_t i = 0; i < aStream->mVideoOutputs.Length(); ++i) { VideoFrameContainer* output = aStream->mVideoOutputs[i]; output->SetCurrentFrame(frame->GetIntrinsicSize(), frame->GetImage(), targetTime); nsCOMPtr<nsIRunnable> event = NS_NewRunnableMethod(output, &VideoFrameContainer::Invalidate); NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL); } if (!aStream->mNotifiedFinished) { aStream->mLastPlayedVideoFrame = *frame; } } void MediaStreamGraphImpl::PrepareUpdatesToMainThreadState() { mMonitor.AssertCurrentThreadOwns(); for (uint32_t i = 0; i < mStreams.Length(); ++i) { MediaStream* stream = mStreams[i]; StreamUpdate* update = mStreamUpdates.AppendElement(); update->mGraphUpdateIndex = stream->mGraphUpdateIndices.GetAt(mCurrentTime); update->mStream = stream; update->mNextMainThreadCurrentTime = GraphTimeToStreamTime(stream, mCurrentTime); update->mNextMainThreadFinished = stream->mFinished && StreamTimeToGraphTime(stream, stream->GetBufferEnd()) <= mCurrentTime; } mUpdateRunnables.MoveElementsFrom(mPendingUpdateRunnables); EnsureStableStateEventPosted(); } void MediaStreamGraphImpl::EnsureImmediateWakeUpLocked(MonitorAutoLock& aLock) { if (mWaitState == WAITSTATE_WAITING_FOR_NEXT_ITERATION || mWaitState == WAITSTATE_WAITING_INDEFINITELY) { mWaitState = WAITSTATE_WAKING_UP; aLock.Notify(); } } void MediaStreamGraphImpl::EnsureNextIteration() { MonitorAutoLock lock(mMonitor); EnsureNextIterationLocked(lock); } void MediaStreamGraphImpl::EnsureNextIterationLocked(MonitorAutoLock& aLock) { if (mNeedAnotherIteration) return; mNeedAnotherIteration = true; if (mWaitState == WAITSTATE_WAITING_INDEFINITELY) { mWaitState = WAITSTATE_WAKING_UP; aLock.Notify(); } } void MediaStreamGraphImpl::RunThread() { nsTArray<MessageBlock> messageQueue; { MonitorAutoLock lock(mMonitor); messageQueue.SwapElements(mMessageQueue); } NS_ASSERTION(!messageQueue.IsEmpty(), "Shouldn't have started a graph with empty message queue!"); for (;;) { // Update mCurrentTime to the min of the playing audio times, or using the // wall-clock time change if no audio is playing. UpdateCurrentTime(); // Calculate independent action times for each batch of messages (each // batch corresponding to an event loop task). This isolates the performance // of different scripts to some extent. for (uint32_t i = 0; i < messageQueue.Length(); ++i) { mProcessingGraphUpdateIndex = messageQueue[i].mGraphUpdateIndex; nsTArray<nsAutoPtr<ControlMessage> >& messages = messageQueue[i].mMessages; for (uint32_t j = 0; j < messages.Length(); ++j) { messages[j]->Run(); } } messageQueue.Clear(); UpdateStreamOrder(); int32_t writeAudioUpTo = AUDIO_TARGET_MS; GraphTime endBlockingDecisions = mCurrentTime + MillisecondsToMediaTime(writeAudioUpTo); bool ensureNextIteration = false; // Grab pending stream input. for (uint32_t i = 0; i < mStreams.Length(); ++i) { SourceMediaStream* is = mStreams[i]->AsSourceStream(); if (is) { UpdateConsumptionState(is); ExtractPendingInput(is, endBlockingDecisions, &ensureNextIteration); } } // Figure out which streams are blocked and when. GraphTime prevComputedTime = mStateComputedTime; RecomputeBlocking(endBlockingDecisions); // Play stream contents. uint32_t audioStreamsActive = 0; bool allBlockedForever = true; // Figure out what each stream wants to do for (uint32_t i = 0; i < mStreams.Length(); ++i) { MediaStream* stream = mStreams[i]; ProcessedMediaStream* ps = stream->AsProcessedStream(); if (ps && !ps->mFinished) { ps->ProduceOutput(prevComputedTime, mStateComputedTime); NS_ASSERTION(stream->mBuffer.GetEnd() >= GraphTimeToStreamTime(stream, mStateComputedTime), "Stream did not produce enough data"); } NotifyHasCurrentData(stream); CreateOrDestroyAudioStreams(prevComputedTime, stream); PlayAudio(stream, prevComputedTime, mStateComputedTime); audioStreamsActive += stream->mAudioOutputStreams.Length(); PlayVideo(stream); SourceMediaStream* is = stream->AsSourceStream(); if (is) { UpdateBufferSufficiencyState(is); } GraphTime end; if (!stream->mBlocked.GetAt(mCurrentTime, &end) || end < GRAPH_TIME_MAX) { allBlockedForever = false; } } if (ensureNextIteration || !allBlockedForever || audioStreamsActive > 0) { EnsureNextIteration(); } // Send updates to the main thread and wait for the next control loop // iteration. { // Not using MonitorAutoLock since we need to unlock in a way // that doesn't match lexical scopes. MonitorAutoLock lock(mMonitor); PrepareUpdatesToMainThreadState(); if (mForceShutDown || (IsEmpty() && mMessageQueue.IsEmpty())) { // Enter shutdown mode. The stable-state handler will detect this // and complete shutdown. Destroy any streams immediately. LOG(PR_LOG_DEBUG, ("MediaStreamGraph %p waiting for main thread cleanup", this)); // Commit to shutting down this graph object. mLifecycleState = LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP; // No need to Destroy streams here. The main-thread owner of each // stream is responsible for calling Destroy them. return; } PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT; TimeStamp now = TimeStamp::Now(); if (mNeedAnotherIteration) { int64_t timeoutMS = MEDIA_GRAPH_TARGET_PERIOD_MS - int64_t((now - mCurrentTimeStamp).ToMilliseconds()); // Make sure timeoutMS doesn't overflow 32 bits by waking up at // least once a minute, if we need to wake up at all timeoutMS = NS_MAX<int64_t>(0, NS_MIN<int64_t>(timeoutMS, 60*1000)); timeout = PR_MillisecondsToInterval(uint32_t(timeoutMS)); LOG(PR_LOG_DEBUG, ("Waiting for next iteration; at %f, timeout=%f", (now - mInitialTimeStamp).ToSeconds(), timeoutMS/1000.0)); mWaitState = WAITSTATE_WAITING_FOR_NEXT_ITERATION; } else { mWaitState = WAITSTATE_WAITING_INDEFINITELY; } if (timeout > 0) { mMonitor.Wait(timeout); LOG(PR_LOG_DEBUG, ("Resuming after timeout; at %f, elapsed=%f", (TimeStamp::Now() - mInitialTimeStamp).ToSeconds(), (TimeStamp::Now() - now).ToSeconds())); } mWaitState = WAITSTATE_RUNNING; mNeedAnotherIteration = false; messageQueue.SwapElements(mMessageQueue); } } } void MediaStreamGraphImpl::ApplyStreamUpdate(StreamUpdate* aUpdate) { mMonitor.AssertCurrentThreadOwns(); MediaStream* stream = aUpdate->mStream; if (!stream) return; stream->mMainThreadCurrentTime = aUpdate->mNextMainThreadCurrentTime; stream->mMainThreadFinished = aUpdate->mNextMainThreadFinished; for (int32_t i = stream->mMainThreadListeners.Length() - 1; i >= 0; --i) { stream->mMainThreadListeners[i]->NotifyMainThreadStateChanged(); } } void MediaStreamGraphImpl::ShutdownThreads() { NS_ASSERTION(NS_IsMainThread(), "Must be called on main thread"); // mGraph's thread is not running so it's OK to do whatever here LOG(PR_LOG_DEBUG, ("Stopping threads for MediaStreamGraph %p", this)); if (mThread) { mThread->Shutdown(); mThread = nullptr; } } void MediaStreamGraphImpl::ForceShutDown() { NS_ASSERTION(NS_IsMainThread(), "Must be called on main thread"); LOG(PR_LOG_DEBUG, ("MediaStreamGraph %p ForceShutdown", this)); { MonitorAutoLock lock(mMonitor); mForceShutDown = true; EnsureImmediateWakeUpLocked(lock); } } namespace { class MediaStreamGraphThreadRunnable : public nsRunnable { public: NS_IMETHOD Run() { gGraph->RunThread(); return NS_OK; } }; class MediaStreamGraphShutDownRunnable : public nsRunnable { public: MediaStreamGraphShutDownRunnable(MediaStreamGraphImpl* aGraph) : mGraph(aGraph) {} NS_IMETHOD Run() { NS_ASSERTION(mGraph->mDetectedNotRunning, "We should know the graph thread control loop isn't running!"); // mGraph's thread is not running so it's OK to do whatever here if (mGraph->IsEmpty()) { // mGraph is no longer needed, so delete it. If the graph is not empty // then we must be in a forced shutdown and some later AppendMessage will // detect that the manager has been emptied, and delete it. delete mGraph; } else { NS_ASSERTION(mGraph->mForceShutDown, "Not in forced shutdown?"); mGraph->mLifecycleState = MediaStreamGraphImpl::LIFECYCLE_WAITING_FOR_STREAM_DESTRUCTION; } return NS_OK; } private: MediaStreamGraphImpl* mGraph; }; class MediaStreamGraphStableStateRunnable : public nsRunnable { public: NS_IMETHOD Run() { if (gGraph) { gGraph->RunInStableState(); } return NS_OK; } }; /* * Control messages forwarded from main thread to graph manager thread */ class CreateMessage : public ControlMessage { public: CreateMessage(MediaStream* aStream) : ControlMessage(aStream) {} virtual void Run() { mStream->GraphImpl()->AddStream(mStream); mStream->Init(); } }; class MediaStreamGraphShutdownObserver MOZ_FINAL : public nsIObserver { public: NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER }; } void MediaStreamGraphImpl::RunInStableState() { NS_ASSERTION(NS_IsMainThread(), "Must be called on main thread"); nsTArray<nsCOMPtr<nsIRunnable> > runnables; // When we're doing a forced shutdown, pending control messages may be // run on the main thread via RunDuringShutdown. Those messages must // run without the graph monitor being held. So, we collect them here. nsTArray<nsAutoPtr<ControlMessage> > controlMessagesToRunDuringShutdown; { MonitorAutoLock lock(mMonitor); mPostedRunInStableStateEvent = false; runnables.SwapElements(mUpdateRunnables); for (uint32_t i = 0; i < mStreamUpdates.Length(); ++i) { StreamUpdate* update = &mStreamUpdates[i]; if (update->mStream) { ApplyStreamUpdate(update); } } mStreamUpdates.Clear(); if (mLifecycleState == LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP && mForceShutDown) { // Defer calls to RunDuringShutdown() to happen while mMonitor is not held. for (uint32_t i = 0; i < mMessageQueue.Length(); ++i) { MessageBlock& mb = mMessageQueue[i]; controlMessagesToRunDuringShutdown.MoveElementsFrom(mb.mMessages); } mMessageQueue.Clear(); controlMessagesToRunDuringShutdown.MoveElementsFrom(mCurrentTaskMessageQueue); // Stop MediaStreamGraph threads. Do not clear gGraph since // we have outstanding DOM objects that may need it. mLifecycleState = LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN; nsCOMPtr<nsIRunnable> event = new MediaStreamGraphShutDownRunnable(this); NS_DispatchToMainThread(event); } if (mLifecycleState == LIFECYCLE_THREAD_NOT_STARTED) { mLifecycleState = LIFECYCLE_RUNNING; // Start the thread now. We couldn't start it earlier because // the graph might exit immediately on finding it has no streams. The // first message for a new graph must create a stream. nsCOMPtr<nsIRunnable> event = new MediaStreamGraphThreadRunnable(); NS_NewThread(getter_AddRefs(mThread), event); } if (mCurrentTaskMessageQueue.IsEmpty()) { if (mLifecycleState == LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP && IsEmpty()) { NS_ASSERTION(gGraph == this, "Not current graph??"); // Complete shutdown. First, ensure that this graph is no longer used. // A new graph graph will be created if one is needed. LOG(PR_LOG_DEBUG, ("Disconnecting MediaStreamGraph %p", gGraph)); gGraph = nullptr; // Asynchronously clean up old graph. We don't want to do this // synchronously because it spins the event loop waiting for threads // to shut down, and we don't want to do that in a stable state handler. mLifecycleState = LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN; nsCOMPtr<nsIRunnable> event = new MediaStreamGraphShutDownRunnable(this); NS_DispatchToMainThread(event); } } else { if (mLifecycleState <= LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP) { MessageBlock* block = mMessageQueue.AppendElement(); block->mMessages.SwapElements(mCurrentTaskMessageQueue); block->mGraphUpdateIndex = mGraphUpdatesSent; ++mGraphUpdatesSent; EnsureNextIterationLocked(lock); } if (mLifecycleState == LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP) { mLifecycleState = LIFECYCLE_RUNNING; // Revive the MediaStreamGraph since we have more messages going to it. // Note that we need to put messages into its queue before reviving it, // or it might exit immediately. nsCOMPtr<nsIRunnable> event = new MediaStreamGraphThreadRunnable(); mThread->Dispatch(event, 0); } } mDetectedNotRunning = mLifecycleState > LIFECYCLE_RUNNING; } // Make sure we get a new current time in the next event loop task mPostedRunInStableState = false; for (uint32_t i = 0; i < runnables.Length(); ++i) { runnables[i]->Run(); } for (uint32_t i = 0; i < controlMessagesToRunDuringShutdown.Length(); ++i) { controlMessagesToRunDuringShutdown[i]->RunDuringShutdown(); } } static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID); void MediaStreamGraphImpl::EnsureRunInStableState() { NS_ASSERTION(NS_IsMainThread(), "main thread only"); if (mPostedRunInStableState) return; mPostedRunInStableState = true; nsCOMPtr<nsIRunnable> event = new MediaStreamGraphStableStateRunnable(); nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID); if (appShell) { appShell->RunInStableState(event); } else { NS_ERROR("Appshell already destroyed?"); } } void MediaStreamGraphImpl::EnsureStableStateEventPosted() { mMonitor.AssertCurrentThreadOwns(); if (mPostedRunInStableStateEvent) return; mPostedRunInStableStateEvent = true; nsCOMPtr<nsIRunnable> event = new MediaStreamGraphStableStateRunnable(); NS_DispatchToMainThread(event); } void MediaStreamGraphImpl::AppendMessage(ControlMessage* aMessage) { NS_ASSERTION(NS_IsMainThread(), "main thread only"); NS_ASSERTION(!aMessage->GetStream() || !aMessage->GetStream()->IsDestroyed(), "Stream already destroyed"); if (mDetectedNotRunning && mLifecycleState > LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP) { // The graph control loop is not running and main thread cleanup has // happened. From now on we can't append messages to mCurrentTaskMessageQueue, // because that will never be processed again, so just RunDuringShutdown // this message. // This should only happen during forced shutdown. aMessage->RunDuringShutdown(); delete aMessage; if (IsEmpty()) { NS_ASSERTION(gGraph == this, "Switched managers during forced shutdown?"); gGraph = nullptr; delete this; } return; } mCurrentTaskMessageQueue.AppendElement(aMessage); EnsureRunInStableState(); } void MediaStream::Init() { MediaStreamGraphImpl* graph = GraphImpl(); mBlocked.SetAtAndAfter(graph->mCurrentTime, true); mExplicitBlockerCount.SetAtAndAfter(graph->mCurrentTime, true); mExplicitBlockerCount.SetAtAndAfter(graph->mStateComputedTime, false); } MediaStreamGraphImpl* MediaStream::GraphImpl() { return gGraph; } MediaStreamGraph* MediaStream::Graph() { return gGraph; } StreamTime MediaStream::GraphTimeToStreamTime(GraphTime aTime) { return GraphImpl()->GraphTimeToStreamTime(this, aTime); } void MediaStream::FinishOnGraphThread() { GraphImpl()->FinishStream(this); } void MediaStream::DestroyImpl() { for (int32_t i = mConsumers.Length() - 1; i >= 0; --i) { mConsumers[i]->Disconnect(); } for (uint32_t i = 0; i < mAudioOutputStreams.Length(); ++i) { mAudioOutputStreams[i].mStream->Shutdown(); } mAudioOutputStreams.Clear(); } void MediaStream::Destroy() { // Keep this stream alive until we leave this method nsRefPtr<MediaStream> kungFuDeathGrip = this; class Message : public ControlMessage { public: Message(MediaStream* aStream) : ControlMessage(aStream) {} virtual void Run() { mStream->DestroyImpl(); mStream->GraphImpl()->RemoveStream(mStream); } virtual void RunDuringShutdown() { Run(); } }; mWrapper = nullptr; GraphImpl()->AppendMessage(new Message(this)); // Message::RunDuringShutdown may have removed this stream from the graph, // but our kungFuDeathGrip above will have kept this stream alive if // necessary. mMainThreadDestroyed = true; } void MediaStream::AddAudioOutput(void* aKey) { class Message : public ControlMessage { public: Message(MediaStream* aStream, void* aKey) : ControlMessage(aStream), mKey(aKey) {} virtual void Run() { mStream->AddAudioOutputImpl(mKey); } void* mKey; }; GraphImpl()->AppendMessage(new Message(this, aKey)); } void MediaStream::SetAudioOutputVolumeImpl(void* aKey, float aVolume) { for (uint32_t i = 0; i < mAudioOutputs.Length(); ++i) { if (mAudioOutputs[i].mKey == aKey) { mAudioOutputs[i].mVolume = aVolume; return; } } NS_ERROR("Audio output key not found"); } void MediaStream::SetAudioOutputVolume(void* aKey, float aVolume) { class Message : public ControlMessage { public: Message(MediaStream* aStream, void* aKey, float aVolume) : ControlMessage(aStream), mKey(aKey), mVolume(aVolume) {} virtual void Run() { mStream->SetAudioOutputVolumeImpl(mKey, mVolume); } void* mKey; float mVolume; }; GraphImpl()->AppendMessage(new Message(this, aKey, aVolume)); } void MediaStream::RemoveAudioOutputImpl(void* aKey) { for (uint32_t i = 0; i < mAudioOutputs.Length(); ++i) { if (mAudioOutputs[i].mKey == aKey) { mAudioOutputs.RemoveElementAt(i); return; } } NS_ERROR("Audio output key not found"); } void MediaStream::RemoveAudioOutput(void* aKey) { class Message : public ControlMessage { public: Message(MediaStream* aStream, void* aKey) : ControlMessage(aStream), mKey(aKey) {} virtual void Run() { mStream->RemoveAudioOutputImpl(mKey); } void* mKey; }; GraphImpl()->AppendMessage(new Message(this, aKey)); } void MediaStream::AddVideoOutput(VideoFrameContainer* aContainer) { class Message : public ControlMessage { public: Message(MediaStream* aStream, VideoFrameContainer* aContainer) : ControlMessage(aStream), mContainer(aContainer) {} virtual void Run() { mStream->AddVideoOutputImpl(mContainer.forget()); } nsRefPtr<VideoFrameContainer> mContainer; }; GraphImpl()->AppendMessage(new Message(this, aContainer)); } void MediaStream::RemoveVideoOutput(VideoFrameContainer* aContainer) { class Message : public ControlMessage { public: Message(MediaStream* aStream, VideoFrameContainer* aContainer) : ControlMessage(aStream), mContainer(aContainer) {} virtual void Run() { mStream->RemoveVideoOutputImpl(mContainer); } nsRefPtr<VideoFrameContainer> mContainer; }; GraphImpl()->AppendMessage(new Message(this, aContainer)); } void MediaStream::ChangeExplicitBlockerCount(int32_t aDelta) { class Message : public ControlMessage { public: Message(MediaStream* aStream, int32_t aDelta) : ControlMessage(aStream), mDelta(aDelta) {} virtual void Run() { mStream->ChangeExplicitBlockerCountImpl( mStream->GraphImpl()->mStateComputedTime, mDelta); } int32_t mDelta; }; GraphImpl()->AppendMessage(new Message(this, aDelta)); } void MediaStream::AddListenerImpl(already_AddRefed<MediaStreamListener> aListener) { MediaStreamListener* listener = *mListeners.AppendElement() = aListener; listener->NotifyBlockingChanged(GraphImpl(), mBlocked.GetAt(GraphImpl()->mCurrentTime) ? MediaStreamListener::BLOCKED : MediaStreamListener::UNBLOCKED); if (mNotifiedFinished) { listener->NotifyFinished(GraphImpl()); } } void MediaStream::AddListener(MediaStreamListener* aListener) { class Message : public ControlMessage { public: Message(MediaStream* aStream, MediaStreamListener* aListener) : ControlMessage(aStream), mListener(aListener) {} virtual void Run() { mStream->AddListenerImpl(mListener.forget()); } nsRefPtr<MediaStreamListener> mListener; }; GraphImpl()->AppendMessage(new Message(this, aListener)); } void MediaStream::RemoveListener(MediaStreamListener* aListener) { class Message : public ControlMessage { public: Message(MediaStream* aStream, MediaStreamListener* aListener) : ControlMessage(aStream), mListener(aListener) {} virtual void Run() { mStream->RemoveListenerImpl(mListener); } nsRefPtr<MediaStreamListener> mListener; }; GraphImpl()->AppendMessage(new Message(this, aListener)); } void SourceMediaStream::DestroyImpl() { { MutexAutoLock lock(mMutex); mDestroyed = true; } MediaStream::DestroyImpl(); } void SourceMediaStream::SetPullEnabled(bool aEnabled) { MutexAutoLock lock(mMutex); mPullEnabled = aEnabled; if (mPullEnabled && !mDestroyed) { GraphImpl()->EnsureNextIteration(); } } void SourceMediaStream::AddTrack(TrackID aID, TrackRate aRate, TrackTicks aStart, MediaSegment* aSegment) { MutexAutoLock lock(mMutex); TrackData* data = mUpdateTracks.AppendElement(); data->mID = aID; data->mRate = aRate; data->mStart = aStart; data->mCommands = TRACK_CREATE; data->mData = aSegment; data->mHaveEnough = false; if (!mDestroyed) { GraphImpl()->EnsureNextIteration(); } } void SourceMediaStream::AppendToTrack(TrackID aID, MediaSegment* aSegment) { MutexAutoLock lock(mMutex); TrackData *track = FindDataForTrack(aID); if (track) { track->mData->AppendFrom(aSegment); } else { NS_ERROR("Append to non-existent track!"); } if (!mDestroyed) { GraphImpl()->EnsureNextIteration(); } } bool SourceMediaStream::HaveEnoughBuffered(TrackID aID) { MutexAutoLock lock(mMutex); TrackData *track = FindDataForTrack(aID); if (track) { return track->mHaveEnough; } NS_ERROR("No track in HaveEnoughBuffered!"); return true; } void SourceMediaStream::DispatchWhenNotEnoughBuffered(TrackID aID, nsIThread* aSignalThread, nsIRunnable* aSignalRunnable) { MutexAutoLock lock(mMutex); TrackData* data = FindDataForTrack(aID); if (!data) { NS_ERROR("No track in DispatchWhenNotEnoughBuffered"); return; } if (data->mHaveEnough) { data->mDispatchWhenNotEnough.AppendElement()->Init(aSignalThread, aSignalRunnable); } else { aSignalThread->Dispatch(aSignalRunnable, 0); } } void SourceMediaStream::EndTrack(TrackID aID) { MutexAutoLock lock(mMutex); TrackData *track = FindDataForTrack(aID); if (track) { track->mCommands |= TRACK_END; } else { NS_ERROR("End of non-existant track"); } if (!mDestroyed) { GraphImpl()->EnsureNextIteration(); } } void SourceMediaStream::AdvanceKnownTracksTime(StreamTime aKnownTime) { MutexAutoLock lock(mMutex); mUpdateKnownTracksTime = aKnownTime; if (!mDestroyed) { GraphImpl()->EnsureNextIteration(); } } void SourceMediaStream::Finish() { MutexAutoLock lock(mMutex); mUpdateFinished = true; if (!mDestroyed) { GraphImpl()->EnsureNextIteration(); } } void MediaInputPort::Init() { LOG(PR_LOG_DEBUG, ("Adding MediaInputPort %p (from %p to %p) to the graph", this, mSource, mDest)); mSource->AddConsumer(this); mDest->AddInput(this); // mPortCount decremented via MediaInputPort::Destroy's message ++mDest->GraphImpl()->mPortCount; } void MediaInputPort::Disconnect() { NS_ASSERTION(!mSource == !mDest, "mSource must either both be null or both non-null"); if (!mSource) return; mSource->RemoveConsumer(this); mSource = nullptr; mDest->RemoveInput(this); mDest = nullptr; } MediaInputPort::InputInterval MediaInputPort::GetNextInputInterval(GraphTime aTime) { InputInterval result = { GRAPH_TIME_MAX, GRAPH_TIME_MAX, false }; GraphTime t = aTime; GraphTime end; for (;;) { if (!mDest->mBlocked.GetAt(t, &end)) break; if (end == GRAPH_TIME_MAX) return result; t = end; } result.mStart = t; GraphTime sourceEnd; result.mInputIsBlocked = mSource->mBlocked.GetAt(t, &sourceEnd); result.mEnd = NS_MIN(end, sourceEnd); return result; } void MediaInputPort::Destroy() { class Message : public ControlMessage { public: Message(MediaInputPort* aPort) : ControlMessage(nullptr), mPort(aPort) {} virtual void Run() { mPort->Disconnect(); --mPort->GraphImpl()->mPortCount; NS_RELEASE(mPort); } virtual void RunDuringShutdown() { Run(); } // This does not need to be strongly referenced; the graph is holding // a strong reference to the port, which we will remove. This will be the // last message for the port. MediaInputPort* mPort; }; GraphImpl()->AppendMessage(new Message(this)); } MediaStreamGraphImpl* MediaInputPort::GraphImpl() { return gGraph; } MediaStreamGraph* MediaInputPort::Graph() { return gGraph; } MediaInputPort* ProcessedMediaStream::AllocateInputPort(MediaStream* aStream, uint32_t aFlags) { class Message : public ControlMessage { public: Message(MediaInputPort* aPort) : ControlMessage(aPort->GetDestination()), mPort(aPort) {} virtual void Run() { mPort->Init(); } MediaInputPort* mPort; }; MediaInputPort* port = new MediaInputPort(aStream, this, aFlags); NS_ADDREF(port); GraphImpl()->AppendMessage(new Message(port)); return port; } void ProcessedMediaStream::Finish() { class Message : public ControlMessage { public: Message(ProcessedMediaStream* aStream) : ControlMessage(aStream) {} virtual void Run() { mStream->GraphImpl()->FinishStream(mStream); } }; GraphImpl()->AppendMessage(new Message(this)); } void ProcessedMediaStream::SetAutofinish(bool aAutofinish) { class Message : public ControlMessage { public: Message(ProcessedMediaStream* aStream, bool aAutofinish) : ControlMessage(aStream), mAutofinish(aAutofinish) {} virtual void Run() { mStream->AsProcessedStream()->SetAutofinishImpl(mAutofinish); } bool mAutofinish; }; GraphImpl()->AppendMessage(new Message(this, aAutofinish)); } void ProcessedMediaStream::DestroyImpl() { for (int32_t i = mInputs.Length() - 1; i >= 0; --i) { mInputs[i]->Disconnect(); } MediaStream::DestroyImpl(); } /** * We make the initial mCurrentTime nonzero so that zero times can have * special meaning if necessary. */ static const int32_t INITIAL_CURRENT_TIME = 1; MediaStreamGraphImpl::MediaStreamGraphImpl() : mCurrentTime(INITIAL_CURRENT_TIME) , mStateComputedTime(INITIAL_CURRENT_TIME) , mProcessingGraphUpdateIndex(0) , mPortCount(0) , mMonitor("MediaStreamGraphImpl") , mLifecycleState(LIFECYCLE_THREAD_NOT_STARTED) , mWaitState(WAITSTATE_RUNNING) , mNeedAnotherIteration(false) , mForceShutDown(false) , mPostedRunInStableStateEvent(false) , mDetectedNotRunning(false) , mPostedRunInStableState(false) { #ifdef PR_LOGGING if (!gMediaStreamGraphLog) { gMediaStreamGraphLog = PR_NewLogModule("MediaStreamGraph"); } #endif mCurrentTimeStamp = mInitialTimeStamp = TimeStamp::Now(); } NS_IMPL_ISUPPORTS1(MediaStreamGraphShutdownObserver, nsIObserver) static bool gShutdownObserverRegistered = false; NS_IMETHODIMP MediaStreamGraphShutdownObserver::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { if (strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) { if (gGraph) { gGraph->ForceShutDown(); } nsContentUtils::UnregisterShutdownObserver(this); gShutdownObserverRegistered = false; } return NS_OK; } MediaStreamGraph* MediaStreamGraph::GetInstance() { NS_ASSERTION(NS_IsMainThread(), "Main thread only"); if (!gGraph) { if (!gShutdownObserverRegistered) { gShutdownObserverRegistered = true; nsContentUtils::RegisterShutdownObserver(new MediaStreamGraphShutdownObserver()); } gGraph = new MediaStreamGraphImpl(); LOG(PR_LOG_DEBUG, ("Starting up MediaStreamGraph %p", gGraph)); } return gGraph; } SourceMediaStream* MediaStreamGraph::CreateInputStream(nsDOMMediaStream* aWrapper) { SourceMediaStream* stream = new SourceMediaStream(aWrapper); NS_ADDREF(stream); static_cast<MediaStreamGraphImpl*>(this)->AppendMessage(new CreateMessage(stream)); return stream; } ProcessedMediaStream* MediaStreamGraph::CreateTrackUnionStream(nsDOMMediaStream* aWrapper) { TrackUnionStream* stream = new TrackUnionStream(aWrapper); NS_ADDREF(stream); static_cast<MediaStreamGraphImpl*>(this)->AppendMessage(new CreateMessage(stream)); return stream; } }
33.242151
111
0.687506
wilebeast
a177afd778c2c8658ac4c0e155a6e4f60fd502c5
1,420
hpp
C++
iceoryx_examples/iceperf/base.hpp
kwallner/iceoryx
f7fee3c237bfe8ae15da434aa78937dba0b0c8ec
[ "Apache-2.0" ]
null
null
null
iceoryx_examples/iceperf/base.hpp
kwallner/iceoryx
f7fee3c237bfe8ae15da434aa78937dba0b0c8ec
[ "Apache-2.0" ]
null
null
null
iceoryx_examples/iceperf/base.hpp
kwallner/iceoryx
f7fee3c237bfe8ae15da434aa78937dba0b0c8ec
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_EXAMPLES_ICEPERF_BASE_HPP #define IOX_EXAMPLES_ICEPERF_BASE_HPP #include "topic_data.hpp" #include <chrono> #include <iostream> class IcePerfBase { public: static constexpr uint32_t ONE_KILOBYTE = 1024U; virtual void initLeader() noexcept = 0; virtual void initFollower() noexcept = 0; virtual void shutdown() noexcept = 0; void prePingPongLeader(uint32_t payloadSizeInBytes) noexcept; void postPingPongLeader() noexcept; void releaseFollower() noexcept; double pingPongLeader(uint64_t numRoundTrips) noexcept; void pingPongFollower() noexcept; private: virtual void sendPerfTopic(uint32_t payloadSizeInBytes, bool runFlag) noexcept = 0; virtual PerfTopic receivePerfTopic() noexcept = 0; }; #endif // IOX_EXAMPLES_ICEPERF_BASE_HPP
34.634146
87
0.757042
kwallner
a17a64c91b43e614bf6b36375f887d65184bb7bc
1,322
cpp
C++
src/Test/src/TestSyncModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/Test/src/TestSyncModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/Test/src/TestSyncModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "SyncModel.h" #include "EnNoteTranslator.h" #include "MockEnService.h" #include "MockMessagePump.h" #include "MockLogger.h" #include "MockUserModel.h" #include "SignalCheck.h" #include <boost/ref.hpp> using namespace boost; using namespace std; //----------------------- // auxilliary definitions //----------------------- struct SyncModelFixture { EnNoteTranslator enNoteTranslator; MockEnService enService; MockMessagePump messagePump; MockLogger logger; MockUserModel userModel; SyncModel syncModel; SyncModelFixture() : syncModel ( enNoteTranslator , enService , messagePump , userModel , logger ) { enService.userStore->authenticationResult.IsGood = true; } }; //----------- // test cases //----------- BOOST_FIXTURE_TEST_CASE(SyncModel_Test, SyncModelFixture) { BOOST_CHECK(!messagePump.wokeUp); SignalCheck signalSyncCompleteCheck; syncModel.ConnectSyncComplete(ref(signalSyncCompleteCheck)); syncModel.BeginSync(L"username", L"password", Guid("guid")); ::Sleep(20); BOOST_CHECK(!signalSyncCompleteCheck); BOOST_CHECK(messagePump.wokeUp); syncModel.ProcessMessages(); BOOST_CHECK(signalSyncCompleteCheck); BOOST_CHECK_EQUAL(userModel.loadCount, 1); }
20.030303
62
0.68003
don-reba
a17b2ac897ad5ac9635b06565708a71c19962db8
21,937
cpp
C++
emulator/src/mame/machine/ms7004.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/machine/ms7004.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/machine/ms7004.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Sergey Svishchev /* Elektronika MS 7004 keyboard (DEC LK-201 workalike with extra keys for Cyrillic characters). To do: - connect LEDs and speaker */ #include "emu.h" #include "ms7004.h" #include "speaker.h" #define VERBOSE_DBG 1 /* general debug messages */ #define DBG_LOG(N,M,A) \ do { \ if(VERBOSE_DBG>=N) \ { \ logerror("%11.6f at %s: ",machine().time().as_double(),machine().describe_context()); \ logerror A; \ } \ } while (0) //************************************************************************** // MACROS / CONSTANTS //************************************************************************** #define MS7004_CPU_TAG "i8035" #define MS7004_SPK_TAG "beeper" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** DEFINE_DEVICE_TYPE(MS7004, ms7004_device, "ms7004", "MS7004 keyboard") ROM_START( ms7004 ) ROM_REGION (0x800, MS7004_CPU_TAG, 0) ROM_LOAD ("mc7004_keyboard_original.rom", 0x0000, 0x800, CRC(69fcab53) SHA1(2d7cc7cd182f2ee09ecf2c539e33db3c2195f778)) ROM_END //------------------------------------------------- // ADDRESS_MAP //------------------------------------------------- void ms7004_device::ms7004_map(address_map &map) { map(0x0000, 0x07ff).rom(); } //------------------------------------------------- // device_add_mconfig - add device configuration //------------------------------------------------- MACHINE_CONFIG_START(ms7004_device::device_add_mconfig) MCFG_CPU_ADD(MS7004_CPU_TAG, I8035, XTAL(4'608'000)) MCFG_CPU_PROGRAM_MAP(ms7004_map) MCFG_MCS48_PORT_P1_OUT_CB(WRITE8(ms7004_device, p1_w)) MCFG_MCS48_PORT_P2_OUT_CB(WRITE8(ms7004_device, p2_w)) MCFG_MCS48_PORT_T1_IN_CB(READLINE(ms7004_device, t1_r)) MCFG_MCS48_PORT_PROG_OUT_CB(DEVWRITELINE("i8243", i8243_device, prog_w)) MCFG_I8243_ADD("i8243", NOOP, WRITE8(ms7004_device, i8243_port_w)) MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_SOUND_ADD(MS7004_SPK_TAG, BEEP, 3250) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.50) MACHINE_CONFIG_END const tiny_rom_entry *ms7004_device::device_rom_region() const { return ROM_NAME( ms7004 ); } //------------------------------------------------- // INPUT_PORTS( ms7004 ) //------------------------------------------------- /* bit sig XSn ????n --- --- --- --- 0 8 16 15 1 9 15 14 2 10 14 13 3 11 13 12 4 12 19 16 5 13 12 11 6 14 11 10 7 15 10 9 8 16 9 8 9 17 8 7 10 18 7 6 11 19 6 5 12 20 3 1 13 21 1 2 14 22 4 3 15 23 5 4 0xc9 KEY_LANGLE_RANGLE '?????????????????? ??????????????' 0xbc KEY_DELETE ???? 0xbd KEY_RETURN ???? 0xbf KEY_TILDE '; +' 0xc4 - '??' 0xca - '/ ?' 0xed KEY_PERIOD '?? @' 0xf1 - '_' <...> 0x56 KEY_F1 ???????? ???????? 0x57 KEY_F2 ???????????? ?????????? 0x58 KEY_F3 ?????????? 0x59 KEY_F4 ?????? ???????????? 0x5a KEY_F5 ??5 0x64 KEY_F6 ???????????? 0x65 KEY_F7 ?????????????? 0x66 KEY_F8 ?????????? 0x67 KEY_F9 ???????????? ???????? 0x69 KEY_F10 ?????????? 0x71 KEY_F11 ??11 (????2) 0x72 KEY_F12 ??12 (????) 0x73 KEY_F13 ??13 (????) 0x74 KEY_F14 ?????? ?????????????? 0x7c KEY_HELP ???? 0x7d KEY_MENU ?????? 0x80 KEY_F17 ??17 0x81 KEY_F18 ??18 0x82 KEY_F19 ??19 0x83 KEY_F20 ??20 0xb0 KEY_LOCK ?????? 0xae KEY_SHIFT ???? 0xaf KEY_CTRL ???? 0xb1 KEY_META ?????? 0xb2 - ??????/?????? 0x8a KEY_FIND ???? 0x8b KEY_INSERT_HERE ?????? 0x8c KEY_REMOVE ???????? 0x8d KEY_SELECT ???????? 0x8e KEY_PREV_SCREEN ???????? ???????? 0x8f KEY_NEXT_SCREEN ???????? ???????? nothing sends '@' or '`' `/~ sends ^/~ 2/@ sends 2/" 6/^ sends 6/& 7/& sends 7/' 8 * sends 8/( 9/( sends 9/) 0/) sends 0/0 -/_ sends _/_ +/= sends -/= ;/: sends ;/+ '/" sends : * F10 sends ^C F11 sends ESC F12 sends ^H */ INPUT_PORTS_START( ms7004 ) PORT_START("KBD12") // vertical row 1 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F2") PORT_CODE(KEYCODE_F2) PORT_CHAR(UCHAR_MAMEKEY(F2)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Hold Screen (F1)") PORT_CODE(KEYCODE_F1) PORT_CHAR(UCHAR_MAMEKEY(F1)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_UNUSED ) // '{' / '|' PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("; +") PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+') // '+' PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Tab") PORT_CODE(KEYCODE_TAB) PORT_CHAR('\t') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Ctrl") PORT_CODE(KEYCODE_LCONTROL) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL)) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Shift Lock") PORT_CODE(KEYCODE_CAPSLOCK) PORT_CHAR(UCHAR_MAMEKEY(CAPSLOCK)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("LShift") PORT_CODE(KEYCODE_LSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_START("KBD13") // vertical row 2 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Setup (F3)") PORT_CODE(KEYCODE_F3) PORT_CHAR(UCHAR_MAMEKEY(F3)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Data / Talk (F4)") PORT_CODE(KEYCODE_F4) PORT_CHAR(UCHAR_MAMEKEY(F4)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("1 !") PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("J") PORT_CODE(KEYCODE_J) PORT_CHAR('j') PORT_CHAR('J') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('c') PORT_CHAR('C') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('f') PORT_CHAR('F') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Rus/Lat") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Compose") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(LALT)) PORT_START("KBD14") // vertical row 3 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Break (F5)") PORT_CODE(KEYCODE_F5) PORT_CHAR(UCHAR_MAMEKEY(F5)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("2 \"") PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("U") PORT_CODE(KEYCODE_U) PORT_CHAR('u') PORT_CHAR('U') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Y") PORT_CODE(KEYCODE_Y) PORT_CHAR('y') PORT_CHAR('Y') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("` ~") PORT_CODE(KEYCODE_TILDE) PORT_CHAR('`') PORT_CHAR('~') // ^ PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Q") PORT_CODE(KEYCODE_Q) PORT_CHAR('q') PORT_CHAR('Q') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD15") // vertical row 4 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("3 #") PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#') PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("4 $") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("K") PORT_CODE(KEYCODE_K) PORT_CHAR('k') PORT_CHAR('K') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("W") PORT_CODE(KEYCODE_W) PORT_CHAR('w') PORT_CHAR('W') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("S") PORT_CODE(KEYCODE_S) PORT_CHAR('s') PORT_CHAR('S') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD11") // vertical row 5 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Interrupt (F6)") PORT_CODE(KEYCODE_F6) PORT_CHAR(UCHAR_MAMEKEY(F6)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("5 %") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%') PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('e') PORT_CHAR('E') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("P") PORT_CODE(KEYCODE_P) PORT_CHAR('p') PORT_CHAR('P') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('a') PORT_CHAR('A') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("M") PORT_CODE(KEYCODE_M) PORT_CHAR('m') PORT_CHAR('M') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD10") // vertical row 6 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Resume (F7)") PORT_CODE(KEYCODE_F7) PORT_CHAR(UCHAR_MAMEKEY(F7)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("6 &") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&') PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("N") PORT_CODE(KEYCODE_N) PORT_CHAR('n') PORT_CHAR('N') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("G") PORT_CODE(KEYCODE_G) PORT_CHAR('g') PORT_CHAR('G') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("R") PORT_CODE(KEYCODE_R) PORT_CHAR('r') PORT_CHAR('R') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("T") PORT_CODE(KEYCODE_T) PORT_CHAR('t') PORT_CHAR('T') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("I") PORT_CODE(KEYCODE_I) PORT_CHAR('i') PORT_CHAR('I') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Space") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_START("KBD9") // vertical row 7 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Cancel (F8)") PORT_CODE(KEYCODE_F8) PORT_CHAR(UCHAR_MAMEKEY(F8)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Main Screen (F9)") PORT_CODE(KEYCODE_F9) PORT_CHAR(UCHAR_MAMEKEY(F9)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("7 '") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("[ {") PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('[') PORT_CHAR('{') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("] }") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(']') PORT_CHAR('}') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("O") PORT_CODE(KEYCODE_O) PORT_CHAR('o') PORT_CHAR('O') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("X") PORT_CODE(KEYCODE_X) PORT_CHAR('x') PORT_CHAR('X') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('b') PORT_CHAR('B') PORT_START("KBD8") // vertical row 8 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Exit (F10)") PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("9 )") PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')') PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("8 (") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Z") PORT_CODE(KEYCODE_Z) PORT_CHAR('z') PORT_CHAR('Z') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('d') PORT_CHAR('D') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("L") PORT_CODE(KEYCODE_L) PORT_CHAR('l') PORT_CHAR('L') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("@") // '@' PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(", <") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<') PORT_START("KBD7") // vertical row 9 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("ESC (F11)") PORT_CODE(KEYCODE_F11) PORT_CHAR(UCHAR_MAMEKEY(F11)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("- =") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('=') PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("H") PORT_CODE(KEYCODE_H) PORT_CHAR('h') PORT_CHAR('H') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("V") PORT_CODE(KEYCODE_V) PORT_CHAR('v') PORT_CHAR('V') PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("\\ |") PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('\\') PORT_CHAR('|') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("/ ?") PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?') PORT_START("KBD6") // vertical row 10 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("BS (F12)") PORT_CODE(KEYCODE_F12) PORT_CHAR(UCHAR_MAMEKEY(F12)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("LF (F13)") PORT_CODE(KEYCODE_PRTSCR) PORT_CHAR(UCHAR_MAMEKEY(PRTSCR)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_UNUSED ) // '}' PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(": *") PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*') PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED ) // '??' PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME(". >") PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("_") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('_') PORT_START("KBD5") // vertical row 11 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Additional Options (F14)") PORT_CODE(KEYCODE_PAUSE) PORT_CHAR(UCHAR_MAMEKEY(PAUSE)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Delete <X") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED ) // ??? PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Return") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("RShift") PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD3") // vertical row 12 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Help (F15)") PORT_CODE(KEYCODE_RALT) PORT_CHAR(UCHAR_MAMEKEY(RALT)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Insert Here") PORT_CODE(KEYCODE_HOME) PORT_CHAR(UCHAR_MAMEKEY(HOME)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Find") PORT_CODE(KEYCODE_INSERT) PORT_CHAR(UCHAR_MAMEKEY(INSERT)) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Select") PORT_CODE(KEYCODE_DEL) PORT_CHAR(UCHAR_MAMEKEY(DEL)) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Up") PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP)) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Left") PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD2") // vertical row 13 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Remove") PORT_CODE(KEYCODE_PGUP) PORT_CHAR(UCHAR_MAMEKEY(PGUP)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Next [v]") PORT_CODE(KEYCODE_PGDN) PORT_CHAR(UCHAR_MAMEKEY(PGDN)) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Previous [^]") PORT_CODE(KEYCODE_END) PORT_CHAR(UCHAR_MAMEKEY(END)) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Right") PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT)) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Down") PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KBD1") // vertical row 14 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Do (F16)") PORT_CODE(KEYCODE_RCONTROL) PORT_CHAR(UCHAR_MAMEKEY(RCONTROL)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("PF1") PORT_CODE(KEYCODE_NUMLOCK) PORT_CHAR(UCHAR_MAMEKEY(NUMLOCK)) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 7") PORT_CODE(KEYCODE_7_PAD) PORT_CHAR(UCHAR_MAMEKEY(7_PAD)) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 4") PORT_CODE(KEYCODE_4_PAD) PORT_CHAR(UCHAR_MAMEKEY(4_PAD)) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 1") PORT_CODE(KEYCODE_1_PAD) PORT_CHAR(UCHAR_MAMEKEY(1_PAD)) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 2") PORT_CODE(KEYCODE_2_PAD) PORT_CHAR(UCHAR_MAMEKEY(2_PAD)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 0") PORT_CODE(KEYCODE_0_PAD) PORT_CHAR(UCHAR_MAMEKEY(0_PAD)) PORT_START("KBD0") // vertical row 15 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F17") PORT_CODE(KEYCODE_F17) PORT_CHAR(UCHAR_MAMEKEY(F17)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F18") PORT_CODE(KEYCODE_F18) PORT_CHAR(UCHAR_MAMEKEY(F18)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("PF2") PORT_CODE(KEYCODE_SLASH_PAD) PORT_CHAR(UCHAR_MAMEKEY(SLASH_PAD)) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("PF3") PORT_CODE(KEYCODE_ASTERISK) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 8") PORT_CODE(KEYCODE_8_PAD) PORT_CHAR(UCHAR_MAMEKEY(8_PAD)) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 5") PORT_CODE(KEYCODE_5_PAD) PORT_CHAR(UCHAR_MAMEKEY(5_PAD)) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 6") PORT_CODE(KEYCODE_6_PAD) PORT_CHAR(UCHAR_MAMEKEY(6_PAD)) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 3") PORT_CODE(KEYCODE_3_PAD) PORT_CHAR(UCHAR_MAMEKEY(3_PAD)) PORT_START("KBD4") // vertical row 16 PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F19") PORT_CODE(KEYCODE_F19) PORT_CHAR(UCHAR_MAMEKEY(F19)) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("F20") PORT_CODE(KEYCODE_F20) PORT_CHAR(UCHAR_MAMEKEY(F20)) PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("PF4") PORT_CODE(KEYCODE_MINUS_PAD) PORT_CHAR(UCHAR_MAMEKEY(MINUS_PAD)) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num 9") PORT_CODE(KEYCODE_9_PAD) PORT_CHAR(UCHAR_MAMEKEY(9_PAD)) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num ,") PORT_CODE(KEYCODE_PLUS_PAD) PORT_CHAR(UCHAR_MAMEKEY(PLUS_PAD)) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num -") PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Num .") PORT_CODE(KEYCODE_DEL_PAD) PORT_CHAR(UCHAR_MAMEKEY(DEL_PAD)) // "." on num.pad PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_NAME("Enter") PORT_CODE(KEYCODE_ENTER_PAD) PORT_CHAR(UCHAR_MAMEKEY(ENTER_PAD)) INPUT_PORTS_END //------------------------------------------------- // input_ports - device-specific input ports //------------------------------------------------- ioport_constructor ms7004_device::device_input_ports() const { return INPUT_PORTS_NAME( ms7004 ); } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // ms7004_device - constructor //------------------------------------------------- ms7004_device::ms7004_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, MS7004, tag, owner, clock), m_maincpu(*this, MS7004_CPU_TAG), m_speaker(*this, MS7004_SPK_TAG), m_i8243(*this, "i8243"), m_kbd(*this, "KBD%u", 0), m_tx_handler(*this), m_rts_handler(*this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void ms7004_device::device_start() { m_tx_handler.resolve_safe(); m_rts_handler.resolve_safe(); } //------------------------------------------------- // device_reset - device-specific reset //------------------------------------------------- void ms7004_device::device_reset() { m_rts_handler(0); } WRITE_LINE_MEMBER( ms7004_device::write_rxd ) { m_maincpu->set_input_line(MCS48_INPUT_IRQ, state ? CLEAR_LINE : ASSERT_LINE); } //------------------------------------------------- // p1_w - //------------------------------------------------- WRITE8_MEMBER( ms7004_device::p1_w ) { /* bit description 0 Matrix row bit 0 1 Matrix row bit 1 2 Matrix row bit 2 3 Speaker 4 -STROBE (to matrix mux) 5 LED "Latin" 6 7 Serial TX */ DBG_LOG(2,0,( "%s: p1_w %02x = send %d\n", tag(), data, BIT(data, 7))); m_p1 = data; m_tx_handler(BIT(data, 7)); } //------------------------------------------------- // p2_w - //------------------------------------------------- WRITE8_MEMBER( ms7004_device::p2_w ) { /* bit description 0 Matrix columns, to 8243 (port 4) 1 Matrix columns, to 8243 (port 5) 2 Matrix columns, to 8243 (port 6) 3 Matrix columns, to 8243 (port 7) 4 LED "Wait" 5 LED "Compose" 6 LED "Caps" 7 LED "Hold" */ DBG_LOG(2,0,( "p2_w %02x = col %d\n", data, data&15)); m_p2 = data; m_i8243->p2_w(space, offset, data); } //------------------------------------------------- // prog_w - //------------------------------------------------- WRITE8_MEMBER( ms7004_device::i8243_port_w ) { int sense = 0; DBG_LOG(2,0,( "8243 port %d data %02xH\n", offset + 4, data)); if (data) { switch(data) { case 0x01: sense = m_kbd[(offset << 2) + 0]->read(); break; case 0x02: sense = m_kbd[(offset << 2) + 1]->read(); break; case 0x04: sense = m_kbd[(offset << 2) + 2]->read(); break; case 0x08: sense = m_kbd[(offset << 2) + 3]->read(); break; } m_keylatch = BIT(sense, (m_p1 & 7)); if (m_keylatch) DBG_LOG(1,0,( "row %d col %02x t1 %d\n", (m_p1 & 7), (offset << 4 | data), m_keylatch)); } } //------------------------------------------------- // t1_r - //------------------------------------------------- READ_LINE_MEMBER( ms7004_device::t1_r ) { if (!BIT(m_p1,4)) return m_keylatch; else return 0; }
46.378436
146
0.665405
rjw57
a17b841b28943f028b469353b4832dd177a45977
299
cpp
C++
contest/AtCoder/abc033/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AtCoder/abc033/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AtCoder/abc033/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "string.hpp" #include "vector.hpp" int main() { int n(in); Vector<String> s(n); Vector<int> p(n); read(s, p); int sum = p.accumulate(); for (int i = 0; i < n; ++i) { if (sum < p[i] * 2) { cout << s[i] << endl; return 0; } } cout << "atcoder" << endl; }
16.611111
31
0.481605
not522
a17bcaea4791de2ec15c5c76dc866948f453bda6
8,026
cc
C++
L1Trigger/L1TMuonEndCap/src/PtAssignment.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/L1TMuonEndCap/src/PtAssignment.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/L1TMuonEndCap/src/PtAssignment.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "L1Trigger/L1TMuonEndCap/interface/PtAssignment.h" #include "L1Trigger/L1TMuonEndCap/interface/PtAssignmentEngine.h" #include "L1Trigger/L1TMuonEndCap/interface/PtAssignmentEngineDxy.h" void PtAssignment::configure(PtAssignmentEngine* pt_assign_engine, PtAssignmentEngineDxy* pt_assign_engine_dxy, int verbose, int endcap, int sector, int bx, bool readPtLUTFile, bool fixMode15HighPt, bool bug9BitDPhi, bool bugMode7CLCT, bool bugNegPt, bool bugGMTPhi, bool promoteMode7, int modeQualVer, std::string pbFileName) { emtf_assert(pt_assign_engine != nullptr); emtf_assert(pt_assign_engine_dxy != nullptr); pt_assign_engine_ = pt_assign_engine; pt_assign_engine_dxy_ = pt_assign_engine_dxy; verbose_ = verbose; endcap_ = endcap; sector_ = sector; bx_ = bx; pt_assign_engine_->configure(verbose_, readPtLUTFile, fixMode15HighPt, bug9BitDPhi, bugMode7CLCT, bugNegPt); pt_assign_engine_dxy_->configure(verbose_, pbFileName); bugGMTPhi_ = bugGMTPhi; promoteMode7_ = promoteMode7; modeQualVer_ = modeQualVer; } void PtAssignment::process(EMTFTrackCollection& best_tracks) { using address_t = PtAssignmentEngine::address_t; EMTFTrackCollection::iterator best_tracks_it = best_tracks.begin(); EMTFTrackCollection::iterator best_tracks_end = best_tracks.end(); for (; best_tracks_it != best_tracks_end; ++best_tracks_it) { EMTFTrack& track = *best_tracks_it; // pass by reference // Assign GMT eta and phi int gmt_phi = aux().getGMTPhi(track.Phi_fp()); if (!bugGMTPhi_) { gmt_phi = aux().getGMTPhiV2(track.Phi_fp()); } int gmt_eta = aux().getGMTEta(track.Theta_fp(), track.Endcap()); // Convert to integer eta using FW LUT // Notes from Alex (2016-09-28): // // When using two's complement, you get two eta bins with zero coordinate. // This peculiarity is created because positive and negative endcaps are // processed by separate processors, so each of them gets its own zero bin. // With simple inversion, the eta scale becomes uniform, one bin for one // eta value. bool use_ones_complem_gmt_eta = true; if (use_ones_complem_gmt_eta) { gmt_eta = (gmt_eta < 0) ? ~(-gmt_eta) : gmt_eta; } // Assign prompt & displaced pT address_t address = 0; float xmlpt = 0.; float pt = 0.; int gmt_pt = 0; float pt_dxy = 0.; float dxy = 0.; int gmt_pt_dxy = 0; int gmt_dxy = 0; if (track.Mode() != 1) { address = pt_assign_engine_->calculate_address(track); xmlpt = pt_assign_engine_->calculate_pt(address); // Check address packing / unpacking using PtAssignmentEngine2017::calculate_pt_xml(const EMTFTrack& track) if (pt_assign_engine_->get_pt_lut_version() > 5 && not(fabs(xmlpt - pt_assign_engine_->calculate_pt(track)) < 0.001)) { edm::LogError("L1T") << "EMTF pT assignment mismatch: xmlpt = " << xmlpt << ", pt_assign_engine_->calculate_pt(track)) = " << pt_assign_engine_->calculate_pt(track); } pt = (xmlpt < 0.) ? 1. : xmlpt; // Matt used fabs(-1) when mode is invalid pt *= pt_assign_engine_->scale_pt( pt, track.Mode()); // Multiply by some factor to achieve 90% efficiency at threshold gmt_pt = aux().getGMTPt(pt); // Encode integer pT in GMT format } // End if (track.Mode() != 1) else { gmt_pt = 10 - (abs(gmt_eta) / 32); } pt = (gmt_pt <= 0) ? 0 : (gmt_pt - 1) * 0.5; // Decode integer pT (result is in 0.5 GeV step) // Calculate displaced pT and d0 using NN emtf::Feature feature; emtf::Prediction prediction; feature.fill(0); prediction.fill(0); pt_assign_engine_dxy_->calculate_pt_dxy(track, feature, prediction); pt_dxy = std::abs(1.0 / prediction.at(0)); dxy = prediction.at(1); gmt_pt_dxy = aux().getGMTPtDxy(pt_dxy); gmt_dxy = aux().getGMTDxy(dxy); pt_dxy = aux().getPtFromGMTPtDxy(gmt_pt_dxy); int gmt_quality = 0; if (track.Mode() != 1) { gmt_quality = aux().getGMTQuality(track.Mode(), track.Theta_fp(), promoteMode7_, modeQualVer_); } else { // Special quality for single-hit tracks from ME1/1 gmt_quality = track.Hits().front().Pattern() / 4; } std::pair<int, int> gmt_charge = std::make_pair(0, 0); if (track.Mode() != 1) { std::vector<int> phidiffs; for (int i = 0; i < emtf::NUM_STATION_PAIRS; ++i) { int phidiff = (track.PtLUT().sign_ph[i] == 1) ? track.PtLUT().delta_ph[i] : -track.PtLUT().delta_ph[i]; phidiffs.push_back(phidiff); } gmt_charge = aux().getGMTCharge(track.Mode(), phidiffs); } else { // Special charge assignment for single-hit tracks from ME1/1 int CLCT = track.Hits().front().Pattern(); if (CLCT != 10) { if (endcap_ == 1) gmt_charge = std::make_pair((CLCT % 2) == 0 ? 0 : 1, 1); else gmt_charge = std::make_pair((CLCT % 2) == 0 ? 1 : 0, 1); } } // _________________________________________________________________________ // Output EMTFPtLUT tmp_LUT = track.PtLUT(); tmp_LUT.address = address; track.set_PtLUT(tmp_LUT); track.set_pt_XML(xmlpt); track.set_pt(pt); track.set_pt_dxy(pt_dxy); track.set_dxy(dxy); track.set_charge((gmt_charge.second == 1) ? ((gmt_charge.first == 1) ? -1 : +1) : 0); track.set_gmt_pt(gmt_pt); track.set_gmt_pt_dxy(gmt_pt_dxy); track.set_gmt_dxy(gmt_dxy); track.set_gmt_phi(gmt_phi); track.set_gmt_eta(gmt_eta); track.set_gmt_quality(gmt_quality); track.set_gmt_charge(gmt_charge.first); track.set_gmt_charge_valid(gmt_charge.second); } // Remove worst track if it addresses the same bank as one of two best tracks bool disable_worst_track_in_same_bank = true; if (disable_worst_track_in_same_bank) { // FW macro for detecting same bank address // bank and chip must match, and valid flags must be set // a and b are indexes 0,1,2 // `define sb(a,b) (ptlut_addr[a][29:26] == ptlut_addr[b][29:26] && ptlut_addr[a][5:2] == ptlut_addr[b][5:2] && ptlut_addr_val[a] && ptlut_addr_val[b]) auto is_in_same_bank = [](const EMTFTrack& lhs, const EMTFTrack& rhs) { unsigned lhs_addr = lhs.PtLUT().address; unsigned rhs_addr = rhs.PtLUT().address; unsigned lhs_addr_1 = (lhs_addr >> 26) & 0xF; unsigned rhs_addr_1 = (rhs_addr >> 26) & 0xF; unsigned lhs_addr_2 = (lhs_addr >> 2) & 0xF; unsigned rhs_addr_2 = (rhs_addr >> 2) & 0xF; return (lhs_addr_1 == rhs_addr_1) && (lhs_addr_2 == rhs_addr_2); }; emtf_assert(best_tracks.size() <= 3); if (best_tracks.size() == 3) { bool same_bank = is_in_same_bank(best_tracks.at(0), best_tracks.at(2)) || is_in_same_bank(best_tracks.at(1), best_tracks.at(2)); if (same_bank) { // Set worst track pT to zero best_tracks.at(2).set_pt(0); best_tracks.at(2).set_gmt_pt(0); } } } if (verbose_ > 0) { // debug for (const auto& track : best_tracks) { std::cout << "track: " << track.Winner() << " pt address: " << track.PtLUT().address << " GMT pt: " << track.GMT_pt() << " pt: " << track.Pt() << " mode: " << track.Mode() << " GMT charge: " << track.GMT_charge() << " quality: " << track.GMT_quality() << " eta: " << track.GMT_eta() << " phi: " << track.GMT_phi() << std::endl; } } } const PtAssignmentEngineAux& PtAssignment::aux() const { return pt_assign_engine_->aux(); }
37.858491
155
0.611637
ckamtsikis
a17fe363176498410537a0ebeeb01e55614b19c6
2,857
cpp
C++
test/algebra/test_linear_polynomial.cpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
test/algebra/test_linear_polynomial.cpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
test/algebra/test_linear_polynomial.cpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
#ifndef _ALGEBRA_TEST_LINEAR_POLYNOMIAL_HPP_ #define _ALGEBRA_TEST_LINEAR_POLYNOMIAL_HPP_ #include "gtest/gtest.h" #include "algebra/misc/linear_polynomial.hpp" namespace carpio{ TEST(linear_polynomial, lp){ typedef LinearPolynomial_<double, std::string> Poly; Poly poly; poly["a"] = 1; poly["b"] = 2; poly["b"] +=3; Poly pb; pb = poly; ASSERT_EQ(pb.value(), 0.0); pb += 3; ASSERT_EQ(pb.value(), 3.0); pb -= 5; ASSERT_EQ(pb.value(), -2.0); pb *= 2; ASSERT_EQ(pb.value(), -4.0); ASSERT_EQ(pb["a"], 2.0); pb /= 3; ASSERT_EQ(pb["a"], 2.0/3.0); } TEST(linear_polynomial, op_add){ typedef LinearPolynomial_<double, std::string> Poly; Poly poly; poly["a"] = 1; poly["b"] = 2; poly["c"] = 3; Poly pb; pb = poly; pb += 3; pb["c"] = 5; pb["d"] =-2; ASSERT_EQ(pb["c"] , 5.0); ASSERT_EQ(pb["d"] ,-2.0); pb += poly; ASSERT_EQ(pb["c"], 8.0); ASSERT_EQ(pb["d"],-2.0); pb -= poly; pb -= poly; ASSERT_EQ(pb["c"], 2.0); ASSERT_EQ(pb["d"],-2.0); } TEST(linear_polynomial, op_add2){ typedef LinearPolynomial_<double, std::string> Poly; Poly poly; poly["a"] = 1; poly["b"] = 2; poly["c"] = 3; std::cout << "poly :\n"; std::cout << poly << std::endl; Poly pb; pb = poly; pb += 3; pb["c"] = 5; pb["d"] =-2; std::cout << "pb :\n"; std::cout << pb << std::endl; std::cout << " pb + poly \n"; std::cout << pb + poly << std::endl; std::cout << " pb - poly \n"; std::cout << pb - poly << std::endl; std::cout << " poly - pb \n"; std::cout << poly - pb << std::endl; std::cout << " pb - 3 \n"; std::cout << pb - 300.0 << std::endl; std::cout << " 100 - pb \n"; std::cout << 100.0 - pb << std::endl; } TEST(linear_polynomial, op_multi){ typedef LinearPolynomial_<double, std::string> Poly; Poly poly; poly["a"] = 1; poly["b"] = 2; poly["c"] = 3; std::cout << "poly :\n"; std::cout << poly << std::endl; Poly pb; pb = poly; pb += 3; pb["c"] = 5; pb["d"] =-2; std::cout << "pb :\n"; std::cout << pb << std::endl; std::cout << " pb * 2\n"; std::cout << pb * 2.0 << std::endl; std::cout << " 3 * pb\n"; std::cout << 3.0 * pb << std::endl; std::cout << " pb / 2\n"; std::cout << pb / 2.0 << std::endl; } TEST(linear_polynomial, op_add_term){ typedef LinearPolynomial_<double, std::string> Poly; Poly poly; poly["a"] = 1; poly["b"] = 2; poly["c"] = 3; std::cout << "poly :\n"; std::cout << poly << std::endl; Poly pb; pb = poly; pb += 3; pb["c"] = 5; pb["d"] =-2; std::cout << "pb :\n"; std::cout << pb << std::endl; std::cout << " pb + \"c\"\n"; std::string str = "c"; std::cout << pb + str << std::endl; std::cout << " pb + \"e\"\n"; str = "e"; std::cout << pb + str << std::endl; std::cout << " \"c\" + pb\n"; str = "c"; std::cout << str + pb << std::endl; std::cout << " \"e\" + pb\n"; str = "e"; std::cout << str + pb << std::endl; } } #endif
18.432258
53
0.535527
hyperpower
a1801bb58f2b27d40ff849ce8de2c833463e291f
1,249
cc
C++
CPPQEDscripts/PTLA_Evolved.cc
vukics/cppqed
a933375f53b982b14cebf7cb63de300996ddd00b
[ "BSL-1.0" ]
5
2021-02-21T14:00:54.000Z
2021-07-29T15:12:11.000Z
CPPQEDscripts/PTLA_Evolved.cc
vukics/cppqed
a933375f53b982b14cebf7cb63de300996ddd00b
[ "BSL-1.0" ]
10
2020-04-14T11:18:02.000Z
2021-07-04T20:11:23.000Z
CPPQEDscripts/PTLA_Evolved.cc
vukics/cppqed
a933375f53b982b14cebf7cb63de300996ddd00b
[ "BSL-1.0" ]
2
2021-01-25T10:16:35.000Z
2021-01-28T18:29:01.000Z
// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt) #include "Evolution_.h" #include "PumpedTwoLevelAtom.h" #include "Qbit.h" #include "StateVector.h" #include "DensityOperator.h" #include "Simulated.h" using namespace std ; using namespace cppqedutils ; using namespace trajectory; using namespace qbit ; typedef DArray<1> Array; int main(int argc, char* argv[]) { ParameterTable p; evolution::Pars<> pt(p); ParsPumpedLossy pp2la(p); // Parameter finalization update(p,argc,argv,"--"); PumpedTwoLevelAtomSch atom(pp2la); double dtinit=.1/atom.highestFrequency(); Array zxy(3); { quantumdata::DensityOperator<1> rho(qbit::init(pp2la)); zxy= 2*real(rho(0)(0))-1, 2*real(rho(0)(1)) , -2*imag(rho(0)(1)) ; } run(simulated::makeBoost(zxy,[&](const Array& b, Array& dbdt, double) { double z=b(0); dcomp Omega(-pp2la.gamma,pp2la.delta), s(b(1),-b(2)); dcomp temp(-2.*conj(pp2la.eta)*z+conj(Omega)*s); dbdt= 2.*real(pp2la.eta*s)+2*pp2la.gamma*(1-z), real(temp), -imag(temp); },{"2*real(rho00)-1","2*real(rho01)","-2*imag(rho01)"},dtinit,pt),pt); }
21.169492
132
0.638911
vukics
a189472ebd6dca27ed8af391104a4b3c674074bf
492
cpp
C++
Source/Inventory/Private/Main/HBGameInstance.cpp
DeltaTimeDev/Inventory
a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284
[ "MIT" ]
null
null
null
Source/Inventory/Private/Main/HBGameInstance.cpp
DeltaTimeDev/Inventory
a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284
[ "MIT" ]
null
null
null
Source/Inventory/Private/Main/HBGameInstance.cpp
DeltaTimeDev/Inventory
a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Main/HBGameInstance.h" UHBGameInstance::UHBGameInstance() { //SoundManager = CreateDefaultSubobject<UHBSoundManager>(TEXT("ItemConfig")); } void UHBGameInstance::Init() { //SoundManager = NewObject<UHBSoundManager>(this,SoundManagerClass); SoundManager = GetWorld()->SpawnActor<AHBSoundManager>(SoundManagerClass); } AHBSoundManager* UHBGameInstance::GetSoundManager() { return SoundManager; }
23.428571
78
0.786585
DeltaTimeDev
a18b75261b0a48786230e2df4b08adff993f2d1c
10,714
cpp
C++
templates/ros_msg_io.cpp
shuklaayush/v_repExtRosInterface
d4bd7cb8e1079f9506af18381db7632da6237a33
[ "BSD-3-Clause" ]
19
2017-06-29T07:41:26.000Z
2021-11-03T18:48:48.000Z
templates/ros_msg_io.cpp
kasperg3/vrep_ros_interface
8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e
[ "BSD-3-Clause" ]
175
2017-06-29T09:37:43.000Z
2021-07-09T12:55:28.000Z
templates/ros_msg_io.cpp
kasperg3/vrep_ros_interface
8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e
[ "BSD-3-Clause" ]
8
2017-10-31T08:53:12.000Z
2021-07-21T06:14:43.000Z
#include <ros_msg_io.h> #include <v_repLib.h> #include <stubs.h> #include <cstring> #py from parse_messages_and_services import get_msgs_info, get_msgs_srvs_info, TypeSpec #py msgs = get_msgs_srvs_info(pycpp.params['messages_file'], pycpp.params['services_file']) #py for msg, info in msgs.items(): void write__`info.typespec.normalized()`(const `info.typespec.ctype()`& msg, int stack, const WriteOptions *opt) { try { simPushTableOntoStackE(stack); #py for n, t in info.fields.items(): #py if t.array: #py if t.builtin and t.mtype in TypeSpec.fast_write_types: try { // write field '`n`' (using fast specialized function) simPushStringOntoStackE(stack, "`n`", 0); simPush`TypeSpec.fast_write_types[t.mtype]`TableOntoStackE(stack, &(msg.`n`[0]), msg.`n`.size()); simInsertDataIntoStackTableE(stack); } catch(exception& ex) { std::string msg = "field '`n`': "; msg += ex.what(); throw exception(msg); } #py elif t.builtin and t.mtype == 'uint8': try { // write field '`n`' (using fast specialized function) simPushStringOntoStackE(stack, "`n`", 0); if(opt && opt->uint8array_as_string) simPushStringOntoStackE(stack, (simChar*)&(msg.`n`[0]), msg.`n`.size()); else simPushUInt8TableOntoStackE(stack, &(msg.`n`[0]), msg.`n`.size()); simInsertDataIntoStackTableE(stack); } catch(exception& ex) { std::string msg = "field '`n`': "; msg += ex.what(); throw exception(msg); } #py else: try { // write field '`n`' simPushStringOntoStackE(stack, "`n`", 0); simPushTableOntoStackE(stack); for(int i = 0; i < msg.`n`.size(); i++) { write__int32(i + 1, stack, opt); write__`t.normalized()`(msg.`n`[i], stack, opt); simInsertDataIntoStackTableE(stack); } simInsertDataIntoStackTableE(stack); } catch(exception& ex) { std::string msg = "field '`n`': "; msg += ex.what(); throw exception(msg); } #py endif #py else: try { // write field '`n`' simPushStringOntoStackE(stack, "`n`", 0); write__`t.normalized()`(msg.`n`, stack, opt); simInsertDataIntoStackTableE(stack); } catch(exception& ex) { std::string msg = "field '`n`': "; msg += ex.what(); throw exception(msg); } #py endif #py endfor } catch(exception& ex) { std::string msg = "write__`info.typespec.normalized()`: "; msg += ex.what(); throw exception(msg); } } void read__`info.typespec.normalized()`(int stack, `info.typespec.ctype()` *msg, const ReadOptions *opt) { try { int r = simGetStackTableInfoE(stack, 0); if(r != sim_stack_table_map && r != sim_stack_table_empty) throw exception("expected a table"); int oldsz = simGetStackSizeE(stack); simUnfoldStackTableE(stack); int numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2; char *str; int strSz; while(numItems >= 1) { simMoveStackItemToTopE(stack, oldsz - 1); // move key to top if((str = simGetStackStringValueE(stack, &strSz)) != NULL && strSz > 0) { simPopStackItemE(stack, 1); simMoveStackItemToTopE(stack, oldsz - 1); // move value to top if(0) {} #py for n, t in info.fields.items(): #py if t.array: #py if t.builtin and t.mtype in TypeSpec.fast_write_types: else if(strcmp(str, "`n`") == 0) { try { // read field '`n`' (using fast specialized function) int sz = simGetStackTableInfoE(stack, 0); if(sz < 0) throw exception("expected array"); if(simGetStackTableInfoE(stack, 2) != 1) throw exception("fast_write_type reader exception #1"); #py if t.array_size: // field has fixed size -> no need to reserve space into vector #py else: msg->`n`.resize(sz); #py endif simGetStack`TypeSpec.fast_write_types[t.mtype]`TableE(stack, &(msg->`n`[0]), sz); simPopStackItemE(stack, 1); } catch(exception& ex) { std::string msg = "field `n`: "; msg += ex.what(); throw exception(msg); } } #py elif t.builtin and t.mtype == 'uint8': else if(strcmp(str, "`n`") == 0) { try { if(opt && opt->uint8array_as_string) { // read field '`n`' (uint8[]) as string simChar *str; simInt sz; if((str = simGetStackStringValueE(stack, &sz)) != NULL && sz > 0) { /* * XXX: if an alternative version of simGetStackStringValue woudl exist * working on an externally allocated buffer, we won't need this memcpy: */ #py if t.array_size: // field has fixed size -> no need to reserve space into vector #py else: msg->`n`.resize(sz); #py endif std::memcpy(&(msg->`n`[0]), str, sz); simReleaseBufferE(str); } else throw exception("string read error when trying to read uint8[]"); } else { // read field '`n`' (using fast specialized function) int sz = simGetStackTableInfoE(stack, 0); if(sz < 0) throw exception("expected uint8 array"); if(simGetStackTableInfoE(stack, 2) != 1) throw exception("fast_write_type uint8[] reader exception #1"); #py if t.array_size: // field has fixed size -> no need to reserve space into vector #py else: msg->`n`.resize(sz); #py endif simGetStackUInt8TableE(stack, &(msg->`n`[0]), sz); simPopStackItemE(stack, 1); } } catch(exception& ex) { std::string msg = "field `n`: "; msg += ex.what(); throw exception(msg); } } #py else: # array not fast func else if(strcmp(str, "`n`") == 0) { try { // read field '`n`' if(simGetStackTableInfoE(stack, 0) < 0) throw exception("expected array"); int oldsz1 = simGetStackSizeE(stack); simUnfoldStackTableE(stack); int numItems1 = (simGetStackSizeE(stack) - oldsz1 + 1) / 2; for(int i = 0; i < numItems1; i++) { simMoveStackItemToTopE(stack, oldsz1 - 1); // move key to top int j; read__int32(stack, &j, opt); simMoveStackItemToTopE(stack, oldsz1 - 1); // move value to top `t.ctype()` v; read__`t.normalized()`(stack, &v, opt); #py if t.array_size: msg->`n`[i] = (v); #py else: msg->`n`.push_back(v); #py endif } } catch(exception& ex) { std::string msg = "field `n`: "; msg += ex.what(); throw exception(msg); } } #py endif #py else: # not array else if(strcmp(str, "`n`") == 0) { try { // read field '`n`' read__`t.normalized()`(stack, &(msg->`n`), opt); } catch(exception& ex) { std::string msg = "field `n`: "; msg += ex.what(); throw exception(msg); } } #py endif #py endfor else { std::string msg = "unexpected key: "; msg += str; throw exception(msg); } simReleaseBuffer(str); } else { throw exception("malformed table (bad key type)"); } numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2; } } catch(exception& ex) { std::string msg = "read__`info.typespec.normalized()`: "; msg += ex.what(); throw exception(msg); } } #py endfor #py msgs = get_msgs_info(pycpp.params['messages_file']) #py for msg, info in msgs.items(): void ros_callback__`info.typespec.normalized()`(const boost::shared_ptr<`info.typespec.ctype()` const>& msg, SubscriberProxy *proxy) { int stack = -1; try { stack = simCreateStackE(); write__`info.typespec.normalized()`(*msg, stack, &(proxy->wr_opt)); simCallScriptFunctionExE(proxy->topicCallback.scriptId, proxy->topicCallback.name.c_str(), stack); simReleaseStackE(stack); stack = -1; } catch(exception& ex) { if(stack != -1) simReleaseStack(stack); // don't throw std::string msg = "ros_callback__`info.typespec.normalized()`: "; msg += ex.what(); simSetLastError(proxy->topicCallback.name.c_str(), msg.c_str()); } } #py endfor
36.074074
132
0.444932
shuklaayush
a18df0c3b4b67cd95f755754268d3a84d951b7a5
2,247
cpp
C++
export/windows/obj/src/lime/system/Endian.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/system/Endian.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/system/Endian.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_lime_system_Endian #include <lime/system/Endian.h> #endif namespace lime{ namespace _hx_system{ ::lime::_hx_system::Endian Endian_obj::_hx_BIG_ENDIAN; ::lime::_hx_system::Endian Endian_obj::_hx_LITTLE_ENDIAN; bool Endian_obj::__GetStatic(const ::String &inName, ::Dynamic &outValue, hx::PropertyAccess inCallProp) { if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) { outValue = Endian_obj::_hx_BIG_ENDIAN; return true; } if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) { outValue = Endian_obj::_hx_LITTLE_ENDIAN; return true; } return super::__GetStatic(inName, outValue, inCallProp); } HX_DEFINE_CREATE_ENUM(Endian_obj) int Endian_obj::__FindIndex(::String inName) { if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return 1; if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return 0; return super::__FindIndex(inName); } int Endian_obj::__FindArgCount(::String inName) { if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return 0; if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return 0; return super::__FindArgCount(inName); } hx::Val Endian_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return _hx_BIG_ENDIAN; if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return _hx_LITTLE_ENDIAN; return super::__Field(inName,inCallProp); } static ::String Endian_obj_sStaticFields[] = { HX_("LITTLE_ENDIAN",04,50,ec,fb), HX_("BIG_ENDIAN",9a,d5,89,b2), ::String(null()) }; hx::Class Endian_obj::__mClass; Dynamic __Create_Endian_obj() { return new Endian_obj; } void Endian_obj::__register() { hx::Static(__mClass) = hx::_hx_RegisterClass(HX_("lime.system.Endian",41,85,63,b4), hx::TCanCast< Endian_obj >,Endian_obj_sStaticFields,0, &__Create_Endian_obj, &__Create, &super::__SGetClass(), &CreateEndian_obj, 0 #ifdef HXCPP_VISIT_ALLOCS , 0 #endif #ifdef HXCPP_SCRIPTABLE , 0 #endif ); __mClass->mGetStaticField = &Endian_obj::__GetStatic; } void Endian_obj::__boot() { _hx_BIG_ENDIAN = hx::CreateConstEnum< Endian_obj >(HX_("BIG_ENDIAN",9a,d5,89,b2),1); _hx_LITTLE_ENDIAN = hx::CreateConstEnum< Endian_obj >(HX_("LITTLE_ENDIAN",04,50,ec,fb),0); } } // end namespace lime } // end namespace system
28.443038
138
0.739208
arturspon
a1908feffb8171fd5f6210bf4b4a4cb84ce27dc5
411
cpp
C++
test/screen/screen2/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
1
2020-10-01T14:52:45.000Z
2020-10-01T14:52:45.000Z
test/screen/screen2/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
3
2020-06-19T01:24:51.000Z
2020-07-16T14:00:30.000Z
test/screen/screen2/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
null
null
null
#include "screen.h" #include <iostream> using namespace std; void test1() { Screen myscreen; //char ch = myscreen.get(); //ch = myscreen.get(0, 0); myscreen.move(4, 0).set('#'); } void test2() { Screen myScreen(5, 5, 'X'); myScreen.move(4, 0).set('#').display(cout); cout << "\n"; myScreen.display(cout); cout << endl; } int main(int argc, char **argv) { test2(); }
14.678571
47
0.562044
6923403
08487d3497d5d5c73e51fa16d195cbde96c231cf
952
cpp
C++
Backtracking/CombinationSum2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Backtracking/CombinationSum2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Backtracking/CombinationSum2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void backtrack(int start, vector<int> &row, int sum, set<vector<int>> &res, vector<int> &A, int B) { if (sum >= B) { if (sum == B) res.insert(row); return; } if (start == A.size()) return; row.push_back(A[start]); sum += A[start]; backtrack(start + 1, row, sum, res, A, B); sum -= row[row.size() - 1]; row.pop_back(); backtrack(start + 1, row, sum, res, A, B); } vector<vector<int>> combinationSum(vector<int> &A, int B) { set<vector<int>> res; vector<int> row; sort(A.begin(), A.end()); backtrack(0, row, 0, res, A, B); vector<vector<int>> v(res.begin(), res.end()); return v; } int main() { vector<int> v1{10, 1, 2, 7, 6, 1, 5}; vector<vector<int>> v2 = combinationSum(v1, 8); for (int i = 0; i < v2.size(); i++) { for (int j = 0; j < v2[i].size(); j++) { cout << v2[i][j] << " "; } cout << endl; } return 0; }
18.307692
98
0.534664
aviral243
084d70e1266daa9ebdef51884042946721dea121
4,898
cpp
C++
src/transport_catalogue.cpp
BigBoyMato/CityRouter
5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b
[ "MIT" ]
null
null
null
src/transport_catalogue.cpp
BigBoyMato/CityRouter
5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b
[ "MIT" ]
null
null
null
src/transport_catalogue.cpp
BigBoyMato/CityRouter
5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b
[ "MIT" ]
null
null
null
#include "transport_catalogue.h" #include <algorithm> #include <utility> #include <iostream> namespace transport_catalogue{ namespace detail{ size_t StringPairHash::operator() (const std::pair<std::string, std::string>& stops) const { return hash_s(stops.first) + hash_s(stops.second) * 101; } size_t StopHash::operator() (const std::pair<Stop*, Stop*>& stops) const { return hash_v(stops.first) + hash_v(stops.second) * 101; } } void TransportCatalogue::AddRoute(const Bus& bus){ buses.push_back(bus); // calculate length double length_c = 0; double length_f = 0; // one stop on route handler if (buses.back().stops.size() == 1){ const auto stop = FindStop(buses.back().stops[0]->name); auto found_stop = stop_to_buses.find(stop->name); if (found_stop != stop_to_buses.end()){ found_stop->second.insert(&buses.back()); } } // if route stops is equal to 1 -> doesnt reach here for(size_t i = 1; i < buses.back().stops.size(); i++){ const auto prev_stop = FindStop(buses.back().stops[i - 1]->name); const auto stop = FindStop(buses.back().stops[i]->name); length_c += geo::ComputeDistance(prev_stop->coordinates, stop->coordinates); const auto prev_stop_to_stop_distance = GetDistance(std::make_pair(prev_stop, stop)); const auto stop_to_prev_stop_distance = GetDistance(std::make_pair(stop, prev_stop)); if (!prev_stop_to_stop_distance.has_value() && !stop_to_prev_stop_distance.has_value()){ length_f += -1; // set by authors }else{ if (prev_stop_to_stop_distance.has_value()){ length_f += prev_stop_to_stop_distance.value(); }else{ length_f += stop_to_prev_stop_distance.value(); } } auto found_stop = stop_to_buses.find(stop->name); if (found_stop != stop_to_buses.end()){ found_stop->second.insert(&buses.back()); } } buses.back().factual_length = length_f; buses.back().length_by_coordinates = length_c; routes[buses.back().name] = &buses.back(); } void TransportCatalogue::AddStop(const Stop& stop){ stops.push_back(stop); stops_by_names[stops.back().name] = &stops.back(); if (stop_to_buses.find(stops.back().name) == stop_to_buses.end()){ stop_to_buses[stops.back().name] = {}; } } Stop* TransportCatalogue::FindStop(const std::string_view stop_name) const { if (stops_by_names.count(stop_name) != 0){ return stops_by_names.at(stop_name); } return nullptr; } Bus* TransportCatalogue::FindRoute(const std::string_view bus_name) const { if (routes.count(bus_name) != 0){ return routes.at(bus_name); } return nullptr; } std::pair<std::string_view, const std::optional<Bus*>> TransportCatalogue::GetRouteInfo(const std::string_view bus_name) const { if (routes.count(bus_name)){ return {bus_name, FindRoute(bus_name)}; } return {bus_name, std::nullopt}; } std::pair<std::string_view, const std::optional<std::set<std::string_view>>> TransportCatalogue::GetStopInfo(const std::string_view stop_name) const { if (stop_to_buses.count(stop_name)){ std::set<std::string_view> buses; for (const auto& bus : stop_to_buses.at(stop_name)){ buses.insert(bus->name); } return {stop_name, buses}; } return {stop_name, std::nullopt}; } void TransportCatalogue::SetDistances(const std::unordered_map<std::pair<std::string, std::string>, int, detail::StringPairHash>& pair_from_to) { for (const auto& [key, val] : pair_from_to) { distances[std::make_pair(FindStop(key.first), FindStop(key.second))] = val; } } std::optional<int> TransportCatalogue::GetDistance(const std::pair<Stop*, Stop*>& pair_from_to) const { const auto elem = distances.find(pair_from_to); if (elem != distances.end()){ return (*elem).second; } return {}; } std::unordered_map<std::pair<Stop*, Stop*>, int, detail::StopHash> TransportCatalogue::GetDistances() const{ return distances; } std::unordered_set<Bus*> TransportCatalogue::GetBusesOnStop(const std::string& stop_name) const { return stop_to_buses.at(stop_name); } std::map<std::string, Bus*> TransportCatalogue::GetSortedBuses() const{ std::map<std::string, Bus*> buses_sorted; for (const auto& [bus_name_view, bus] : routes) { buses_sorted.emplace(std::make_pair( std::string(bus_name_view.begin(), bus_name_view.end()), bus)); } return buses_sorted; } std::deque<Stop> TransportCatalogue::GetStops() const{ return stops; } std::deque<Bus> TransportCatalogue::GetBuses() const{ return buses; } std::unordered_map<std::string_view, Stop*> TransportCatalogue::GetStopsByNames() const{ return stops_by_names; } std::unordered_map<std::string_view, Bus*> TransportCatalogue::GetRoutes() const{ return routes; } }
31
113
0.675174
BigBoyMato
084f92f4353a681b1c460b1ffd4d40d29a287145
5,496
cc
C++
common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc
swapnil119/chromeos_smart_card_connector
c01ec7e9aad61ede90f1eeaf8554540ede988d2d
[ "Apache-2.0" ]
79
2017-09-22T05:09:54.000Z
2022-03-13T01:11:06.000Z
common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc
QPC-database/chromeos_smart_card_connector
3ced08b30ce3f2a557487c3bfba1d1cd36c5011c
[ "Apache-2.0" ]
191
2017-10-23T22:34:58.000Z
2022-03-05T18:10:06.000Z
common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc
QPC-database/chromeos_smart_card_connector
3ced08b30ce3f2a557487c3bfba1d1cd36c5011c
[ "Apache-2.0" ]
32
2017-10-21T07:39:59.000Z
2021-11-10T22:55:32.000Z
// Copyright 2016 Google Inc. 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. #include <google_smart_card_common/requesting/async_request.h> #include <chrono> #include <functional> #include <thread> #include <utility> #include <vector> #include <gtest/gtest.h> #include <google_smart_card_common/requesting/request_result.h> #include <google_smart_card_common/value.h> namespace google_smart_card { namespace { class TestAsyncRequestCallback { public: void operator()(GenericRequestResult request_result) { request_result_ = std::move(request_result); ++call_count_; } int call_count() const { return call_count_; } const GenericRequestResult& request_result() const { return request_result_; } private: int call_count_ = 0; GenericRequestResult request_result_; }; } // namespace TEST(RequestingAsyncRequestTest, AsyncRequestStateBasic) { TestAsyncRequestCallback callback; // Initially the request state is constructed with no request result, and the // callback is not executed GenericAsyncRequestState request_state(std::ref(callback)); ASSERT_EQ(0, callback.call_count()); // The first set of the request result is successful and triggers the callback const int kValue = 123; ASSERT_TRUE(request_state.SetResult( GenericRequestResult::CreateSuccessful(Value(kValue)))); ASSERT_EQ(1, callback.call_count()); ASSERT_TRUE(callback.request_result().payload().is_integer()); EXPECT_EQ(callback.request_result().payload().GetInteger(), kValue); // The subsequent set of the request result does not change the stored value // and does not trigger the callback ASSERT_FALSE(request_state.SetResult(GenericRequestResult::CreateFailed(""))); ASSERT_EQ(1, callback.call_count()); ASSERT_TRUE(callback.request_result().payload().is_integer()); EXPECT_EQ(callback.request_result().payload().GetInteger(), kValue); } #ifdef __EMSCRIPTEN__ // TODO(#185): Crashes in Emscripten due to out-of-memory. #define MAYBE_AsyncRequestStateMultiThreading \ DISABLED_AsyncRequestStateMultiThreading #else #define MAYBE_AsyncRequestStateMultiThreading AsyncRequestStateMultiThreading #endif TEST(RequestingAsyncRequestTest, MAYBE_AsyncRequestStateMultiThreading) { const int kIterationCount = 300; const int kStateCount = 100; const int kThreadCount = 10; const auto kThreadsStartTimeout = std::chrono::milliseconds(10); for (int iteration = 0; iteration < kIterationCount; ++iteration) { std::vector<TestAsyncRequestCallback> callbacks(kStateCount); std::vector<std::unique_ptr<GenericAsyncRequestState>> states; for (int index = 0; index < kStateCount; ++index) { states.emplace_back( new GenericAsyncRequestState(std::ref(callbacks[index]))); } std::vector<std::thread> threads; const auto threads_start_time = std::chrono::high_resolution_clock::now() + kThreadsStartTimeout; for (int thread_index = 0; thread_index < kThreadCount; ++thread_index) { threads.emplace_back([&states, threads_start_time] { std::this_thread::sleep_until(threads_start_time); for (int index = 0; index < kStateCount; ++index) states[index]->SetResult(GenericRequestResult::CreateFailed("")); }); } for (int thread_index = 0; thread_index < kThreadCount; ++thread_index) threads[thread_index].join(); for (int index = 0; index < kStateCount; ++index) EXPECT_EQ(1, callbacks[index].call_count()); } } TEST(RequestingAsyncRequestTest, AsyncRequestBasic) { TestAsyncRequestCallback callback; // Initially the request is constructed with an empty request state const auto request_state = std::make_shared<GenericAsyncRequestState>(std::ref(callback)); GenericAsyncRequest request(request_state); ASSERT_EQ(0, callback.call_count()); // The request state receives the result, which triggers the callback ASSERT_TRUE(request_state->SetResult(GenericRequestResult::CreateFailed(""))); ASSERT_EQ(1, callback.call_count()); // After the result is already set, request cancellation has no effect request.Cancel(); ASSERT_EQ(1, callback.call_count()); } TEST(RequestingAsyncRequestTest, AsyncRequestCancellation) { TestAsyncRequestCallback callback; // Initially the request is constructed with an empty request state const auto request_state = std::make_shared<GenericAsyncRequestState>(std::ref(callback)); GenericAsyncRequest request(request_state); ASSERT_EQ(0, callback.call_count()); // The request is canceled, which sets the result to "canceled" request.Cancel(); ASSERT_EQ(1, callback.call_count()); EXPECT_TRUE(callback.request_result().status() == RequestResultStatus::kCanceled); // After the request is canceled, request result assignment has no effect ASSERT_FALSE( request_state->SetResult(GenericRequestResult::CreateFailed(""))); ASSERT_EQ(1, callback.call_count()); } } // namespace google_smart_card
35.921569
80
0.75091
swapnil119
085421df1899e82807b32c078f1ce197ead31708
3,503
cc
C++
bitmap_bench_sdsl.cc
timjb/rankselect
566182d9e2f5861b34dde0807d95c806776baf0d
[ "Apache-2.0" ]
15
2017-06-06T20:04:34.000Z
2020-06-29T21:33:29.000Z
bitmap_bench_sdsl.cc
timjb/rankselect
566182d9e2f5861b34dde0807d95c806776baf0d
[ "Apache-2.0" ]
null
null
null
bitmap_bench_sdsl.cc
timjb/rankselect
566182d9e2f5861b34dde0807d95c806776baf0d
[ "Apache-2.0" ]
4
2017-11-02T18:00:08.000Z
2022-02-03T18:37:52.000Z
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #define __STDC_LIMIT_MACROS #include <stdint.h> #include <unistd.h> #include <sys/time.h> #include "rank_support.hpp" #include "select_support_scan.hpp" #include "select_support_mcl.hpp" #include "bitmap.h" #include "shared.h" using namespace sdsl; double densityL = 0.1; double densityR = 0.1; uint64 numOnesL = 0; uint64 numOnesR = 0; const int numIters = 10; const int numQueries = 10000000; uint64 queries[numQueries]; uint64 indices[numQueries]; uint64 queries64[numQueries]; uint32 seed = 1; inline uint32 xRand() { return seed = (279470273ULL * seed) % 4294967291ULL; } inline uint64 xRand64() { return (uint64) xRand() << 32 | xRand(); } void intVectorRandomBit(uint64 nbits, bit_vector &vector, uint32 thresholdL, uint32 thresholdR) { fprintf(stderr, "nbits to create: %" PRIu64 "\n", nbits); fprintf(stderr, "allocated bits: %" PRIu64 " bytes\n", nbits/8); for (uint64 i = 0; i < nbits / 2; i++) { if (xRand() < thresholdL) { uint64 val = vector.get_int(i / 64, 64); val |= 1ul << (i % 64); vector.set_int(i / 64, val, 64); ++numOnesL; } else { uint64 val = vector.get_int(i / 64, 64); val &= ~(1ull << (i % 64)); vector.set_int(i / 64, val, 64); } } for (uint64 i = nbits / 2; i < nbits; i++) { if (xRand() < thresholdR) { uint64 val = vector.get_int(i / 64, 64); val |= 1ull << (i % 64); vector.set_int(i / 64, val, 64); ++numOnesR; } else { uint64 val = vector.get_int(i / 64, 64); val &= ~(1ull << (i % 64)); vector.set_int(i / 64, val, 64); } } } enum benchmode { BENCH_RANK, BENCH_SELECT, }; int main(int argc, char **argv) { extern int optind; int ch; uint64 nbits; benchmode mode = BENCH_RANK; while ((ch = getopt(argc, argv, "sn:d:")) != -1) { switch (ch) { case 's': mode = BENCH_SELECT; break; case 'n': nbits = atoi(optarg); nbits = 1ULL << nbits; break; case 'd': densityL = densityR = atof(optarg); break; } } printf("benchmode: %s\n", mode == BENCH_RANK ? "rank" : "select"); uint32 thresholdL = (uint32) (UINT32_MAX * densityL); uint32 thresholdR = (uint32) (UINT32_MAX * densityR); uint64 numWords = (nbits + 63)/64; bit_vector vector(nbits, 0, 1); intVectorRandomBit(nbits, vector, thresholdL, thresholdR); uint64 cnt = rank_support_v<0>(&vector)(vector.size()); bit_vector::select_0_type bit_select(&vector); uint64 dummy = 0x1234567890ABCDEF; if (mode == BENCH_RANK) { for (int i = 0; i < numQueries; i++) { queries[i] = xRand64() % nbits + 1; } } else { assert(mode == BENCH_SELECT); for (int i = 0; i < numQueries / 2; i++) { queries[i] = ((xRand64() % numOnesL + 1) % (cnt - 1)) + 1; } for (int i = numQueries / 2; i < numQueries; i++) { queries[i] = ((xRand64() % numOnesR + 1 + numOnesL) % (cnt - 1)) + 1; } } struct timeval tv_start, tv_end; double elapsed_seconds; gettimeofday(&tv_start, NULL); assert(mode == BENCH_SELECT); for (int iter = 0; iter < numIters; iter++) for (int i = 0; i < numQueries; i++) dummy ^= bit_select(queries[i]); gettimeofday(&tv_end, NULL); elapsed_seconds = timeval_diff(&tv_start, &tv_end); printf("%" PRIu64 " ops, %.2f seconds, ns/op: %.2f\n", (uint64) numIters * numQueries, elapsed_seconds, elapsed_seconds * 1000000000 / ((uint64) numIters * numQueries)); if (dummy == 42) printf("42\n"); return 0; }
23.353333
96
0.625178
timjb
08555da4ee2fbf5f8d8ac59b9ed4600b31cea14c
8,522
cpp
C++
modules/audio_coding/main/test/EncodeDecodeTest.cpp
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
1
2017-02-08T09:47:04.000Z
2017-02-08T09:47:04.000Z
modules/audio_coding/main/test/EncodeDecodeTest.cpp
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
null
null
null
modules/audio_coding/main/test/EncodeDecodeTest.cpp
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
5
2015-10-30T17:35:19.000Z
2021-06-04T01:39:27.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "EncodeDecodeTest.h" #include "common_types.h" #include <stdlib.h> #include <string.h> #include "trace.h" #include "utility.h" Receiver::Receiver() : _playoutLengthSmpls(WEBRTC_10MS_PCM_AUDIO), _payloadSizeBytes(MAX_INCOMING_PAYLOAD) { } void Receiver::Setup(AudioCodingModule *acm, RTPStream *rtpStream) { struct CodecInst recvCodec; int noOfCodecs; acm->InitializeReceiver(); noOfCodecs = acm->NumberOfCodecs(); for (int i=0; i < noOfCodecs; i++) { acm->Codec((WebRtc_UWord8)i, recvCodec); if (acm->RegisterReceiveCodec(recvCodec) != 0) { printf("Unable to register codec: for run: codecId: %d\n", codeId); exit(1); } } char filename[128]; _rtpStream = rtpStream; int playSampFreq; if (testMode == 1) { playSampFreq=recvCodec.plfreq; //output file for current run sprintf(filename,"./modules/audio_coding/main/test/res_tests/out%dFile.pcm",codeId); _pcmFile.Open(filename, recvCodec.plfreq, "wb+"); } else if (testMode == 0) { playSampFreq=32000; //output file for current run sprintf(filename,"./modules/audio_coding/main/test/res_autotests/encodeDecode_out%d.pcm",codeId); _pcmFile.Open(filename, 32000/*recvCodec.plfreq*/, "wb+"); } else { printf("\nValid output frequencies:\n"); printf("8000\n16000\n32000\n-1, which means output freq equal to received signal freq"); printf("\n\nChoose output sampling frequency: "); scanf("%d", &playSampFreq); char fileName[] = "./modules/audio_coding/main/test/outFile.pcm"; _pcmFile.Open(fileName, 32000, "wb+"); } _realPayloadSizeBytes = 0; _playoutBuffer = new WebRtc_Word16[WEBRTC_10MS_PCM_AUDIO]; _frequency = playSampFreq; _acm = acm; _firstTime = true; } void Receiver::Teardown() { delete [] _playoutBuffer; _pcmFile.Close(); if (testMode > 1) Trace::ReturnTrace(); } bool Receiver::IncomingPacket() { if (!_rtpStream->EndOfFile()) { if (_firstTime) { _firstTime = false; _realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload, _payloadSizeBytes, &_nextTime); if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile()) { _firstTime = true; return true; } } WebRtc_Word32 ok = _acm->IncomingPacket(_incomingPayload, _realPayloadSizeBytes, _rtpInfo); if (ok != 0) { printf("Error when inserting packet to ACM, for run: codecId: %d\n", codeId); exit(1); } _realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload, _payloadSizeBytes, &_nextTime); if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile()) { _firstTime = true; } } return true; } bool Receiver::PlayoutData() { AudioFrame audioFrame; if (_acm->PlayoutData10Ms(_frequency, audioFrame) != 0) { printf("Error when calling PlayoutData10Ms, for run: codecId: %d\n", codeId); exit(1); } if (_playoutLengthSmpls == 0) { return false; } _pcmFile.Write10MsData(audioFrame._payloadData, audioFrame._payloadDataLengthInSamples); return true; } void Receiver::Run() { WebRtc_UWord8 counter500Ms = 50; WebRtc_UWord32 clock = 0; while (counter500Ms > 0) { if (clock == 0 || clock >= _nextTime) { IncomingPacket(); if (clock == 0) { clock = _nextTime; } } if ((clock % 10) == 0) { if (!PlayoutData()) { clock++; continue; } } if (_rtpStream->EndOfFile()) { counter500Ms--; } clock++; } } EncodeDecodeTest::EncodeDecodeTest() { _testMode = 2; Trace::CreateTrace(); Trace::SetTraceFile("acm_encdec_test.txt"); } EncodeDecodeTest::EncodeDecodeTest(int testMode) { //testMode == 0 for autotest //testMode == 1 for testing all codecs/parameters //testMode > 1 for specific user-input test (as it was used before) _testMode = testMode; if(_testMode != 0) { Trace::CreateTrace(); Trace::SetTraceFile("acm_encdec_test.txt"); } } void EncodeDecodeTest::Perform() { if(_testMode == 0) { printf("Running Encode/Decode Test"); WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceAudioCoding, -1, "---------- EncodeDecodeTest ----------"); } int numCodecs = 1; int codePars[3]; //freq, pacsize, rate int playoutFreq[3]; //8, 16, 32k int numPars[52]; //number of codec parameters sets (rate,freq,pacsize)to test, for a given codec codePars[0]=0; codePars[1]=0; codePars[2]=0; if (_testMode == 1) { AudioCodingModule *acmTmp = AudioCodingModule::Create(0); struct CodecInst sendCodecTmp; numCodecs = acmTmp->NumberOfCodecs(); printf("List of supported codec.\n"); for(int n = 0; n < numCodecs; n++) { acmTmp->Codec(n, sendCodecTmp); if (STR_CASE_CMP(sendCodecTmp.plname, "telephone-event") == 0) { numPars[n] = 0; } else if (STR_CASE_CMP(sendCodecTmp.plname, "cn") == 0) { numPars[n] = 0; } else if (STR_CASE_CMP(sendCodecTmp.plname, "red") == 0) { numPars[n] = 0; } else { numPars[n] = 1; printf("%d %s\n", n, sendCodecTmp.plname); } } AudioCodingModule::Destroy(acmTmp); playoutFreq[1]=16000; } else if (_testMode == 0) { AudioCodingModule *acmTmp = AudioCodingModule::Create(0); numCodecs = acmTmp->NumberOfCodecs(); AudioCodingModule::Destroy(acmTmp); struct CodecInst dummyCodec; //chose range of testing for codecs/parameters for(int i = 0 ; i < numCodecs ; i++) { numPars[i] = 1; acmTmp->Codec(i, dummyCodec); if (STR_CASE_CMP(dummyCodec.plname, "telephone-event") == 0) { numPars[i] = 0; } else if (STR_CASE_CMP(dummyCodec.plname, "cn") == 0) { numPars[i] = 0; } else if (STR_CASE_CMP(dummyCodec.plname, "red") == 0) { numPars[i] = 0; } } playoutFreq[1] = 16000; } else { numCodecs = 1; numPars[0] = 1; playoutFreq[1]=16000; } _receiver.testMode = _testMode; //loop over all codecs: for(int codeId=0;codeId<numCodecs;codeId++) { //only encode using real encoders, not telephone-event anc cn for(int loopPars=1;loopPars<=numPars[codeId];loopPars++) { if (_testMode == 1) { printf("\n"); printf("***FOR RUN: codeId: %d\n",codeId); printf("\n"); } else if (_testMode == 0) { printf("."); } EncodeToFileTest::Perform(1, codeId, codePars, _testMode); AudioCodingModule *acm = AudioCodingModule::Create(10); RTPFile rtpFile; char fileName[] = "outFile.rtp"; rtpFile.Open(fileName, "rb"); _receiver.codeId = codeId; rtpFile.ReadHeader(); _receiver.Setup(acm, &rtpFile); _receiver.Run(); _receiver.Teardown(); rtpFile.Close(); AudioCodingModule::Destroy(acm); if (_testMode == 1) { printf("***COMPLETED RUN FOR: codecID: %d ***\n", codeId); } } } if (_testMode == 0) { printf("Done!\n"); } if (_testMode == 1) Trace::ReturnTrace(); }
28.032895
120
0.553861
stoiczek
08562e8f5fe4b144b3e39ca849ea7d9270686908
1,941
hpp
C++
src/core/voices/vae_voice.hpp
TobiasKozel/VAE
37df7698c560ab7e94d2e69b22166b72602f8860
[ "MIT" ]
1
2022-02-03T21:57:07.000Z
2022-02-03T21:57:07.000Z
src/core/voices/vae_voice.hpp
TobiasKozel/VAE
37df7698c560ab7e94d2e69b22166b72602f8860
[ "MIT" ]
null
null
null
src/core/voices/vae_voice.hpp
TobiasKozel/VAE
37df7698c560ab7e94d2e69b22166b72602f8860
[ "MIT" ]
null
null
null
#ifndef _VAE_VOICE #define _VAE_VOICE #include "../vae_types.hpp" #include "../vae_config.hpp" #include <limits> namespace vae { namespace core { /** * @brief Barebones voice. * Enough to play back a non spatialized and non filtered sound. * Other structs extend this and depend on it * @see VoicePan * @see VoiceHRTF * @see VoiceFilter */ struct Voice { bool spatialized : 1; ///< If the voice has spatialization data bool chainedEvents : 1; ///< If this voice triggers events after it stopped playing bool started : 1; ///< Whether the voice has started playing bool audible : 1; ///< Whether the voice was heard by any listener bool HRTF : 1; ///< If the voice should be rendered using hrtfs bool loop : 1; ///< Voice will loop until killed bool filtered : 1; ///< This will enable high/lowpass filters and variable speed playback. Gets turned on when signal does not match EngineStaticConfig::internalSampleRate bool critical : 1; ///< Voice can't be killed in favor of new voice bool attenuate : 1; ///< Whether distance affects volume BankHandle bank; ///< Which bank it belongs to SourceHandle source = InvalidSourceHandle; ///< If invalid, means voice is not playing. EventHandle event; ///< Which event triggered the voice to be played EmitterHandle emitter; ///< Emitter used to control voice properties MixerHandle mixer; ///< Where the voice should mix to ListenerHandle listener; ///< If it's spatialized it's rendered for this listener Sample gain = 1.0; ///< Volume of the voice SampleIndex time = 0; ///< Current time in samples Voice() { spatialized = false; chainedEvents = false; started = false; audible = false; HRTF = false; loop = false; filtered = false; critical = false; attenuate = false; } }; constexpr int _VAE_VOICE_SIZE = sizeof(Voice); } } // core::vae #endif // _VAE_VOICE
36.622642
174
0.684699
TobiasKozel
085908c7c2a20ad78cb78ac94a61c958210e50be
20,097
cpp
C++
src/mlpack/tests/main_tests/kfn_test.cpp
KimSangYeon-DGU/mlpack
defa29791f43d3372b019f552134abc39def234a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/tests/main_tests/kfn_test.cpp
KimSangYeon-DGU/mlpack
defa29791f43d3372b019f552134abc39def234a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/tests/main_tests/kfn_test.cpp
KimSangYeon-DGU/mlpack
defa29791f43d3372b019f552134abc39def234a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-06-05T13:27:26.000Z
2020-06-23T09:44:31.000Z
/** * @file tests/main_tests/kfn_test.cpp * @author Atharva Khandait * @author Heet Sankesara * * Test mlpackMain() of kfn_main.cpp. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <string> #define BINDING_TYPE BINDING_TYPE_TEST static const std::string testName = "K-FurthestNeighborsSearch"; #include <mlpack/core.hpp> #include <mlpack/core/util/mlpack_main.hpp> #include "test_helper.hpp" #include <mlpack/methods/neighbor_search/kfn_main.cpp> #include <boost/test/unit_test.hpp> #include "../test_tools.hpp" using namespace mlpack; struct KFNTestFixture { public: KFNTestFixture() { // Cache in the options for this program. CLI::RestoreSettings(testName); } ~KFNTestFixture() { // Clear the settings. bindings::tests::CleanMemory(); CLI::ClearSettings(); } }; BOOST_FIXTURE_TEST_SUITE(KFNMainTest, KFNTestFixture); /* * Check that we can't provide reference and query matrices * with different dimensions. */ BOOST_AUTO_TEST_CASE(KFNEqualDimensionTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Now we specify an invalid dimension(2) for the query data. // Note that the number of points in query and reference matrices // are allowed to be different arma::mat queryData; queryData.randu(2, 90); // 90 points in 2 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("query", std::move(queryData)); SetInputParam("k", (int) 10); Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't specify an invalid k when only reference * matrix is given. */ BOOST_AUTO_TEST_CASE(KFNInvalidKTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k > number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 101); Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); delete CLI::GetParam<KFNModel*>("output_model"); CLI::GetParam<KFNModel*>("output_model") = NULL; CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["k"].wasPassed = false; // SetInputParam("reference", referenceData); // SetInputParam("k", (int) 0); // Invalid. // BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); // CLI::GetSingleton().Parameters()["reference"].wasPassed = false; // CLI::GetSingleton().Parameters()["k"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) -1); // Invalid. BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't specify an invalid k when both reference * and query matrices are given. */ BOOST_AUTO_TEST_CASE(KFNInvalidKQueryDataTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. arma::mat queryData; queryData.randu(3, 90); // 90 points in 3 dimensions. // Random input, some k > number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("query", std::move(queryData)); SetInputParam("k", (int) 101); Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /** * Check that we can't specify a negative leaf size. */ BOOST_AUTO_TEST_CASE(KFNLeafSizeTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, negative leaf size. SetInputParam("reference", std::move(referenceData)); SetInputParam("leaf_size", (int) -1); // Invalid. Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't pass both input_model and reference matrix. */ BOOST_AUTO_TEST_CASE(KFNRefModelTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) 10); mlpackMain(); // Input pre-trained model. SetInputParam("input_model", std::move(CLI::GetParam<KFNModel*>("output_model"))); Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't pass an invalid tree type. */ BOOST_AUTO_TEST_CASE(KFNInvalidTreeTypeTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) 10); SetInputParam("tree_type", (string) "min-rp"); // Invalid. Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't pass an invalid algorithm. */ BOOST_AUTO_TEST_CASE(KFNInvalidAlgoTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) 10); SetInputParam("algorithm", (string) "triple_tree"); // Invalid. Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't pass an invalid value of epsilon. */ BOOST_AUTO_TEST_CASE(KFNInvalidEpsilonTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); SetInputParam("epsilon", (double) -1); // Invalid. Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["epsilon"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("epsilon", (double) 2); // Invalid. BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["epsilon"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("epsilon", (double) 1); // Invalid. BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Check that we can't pass an invalid value of percentage. */ BOOST_AUTO_TEST_CASE(KFNInvalidPercentageTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); SetInputParam("percentage", (double) -1); // Invalid. Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["percentage"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("percentage", (double) 0); // Invalid. BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["epsilon"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("percentage", (double) 2); // Invalid. BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /** * Make sure that dimensions of the neighbors and distances * matrices are correct given a value of k. */ BOOST_AUTO_TEST_CASE(KFNOutputDimensionTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) 10); mlpackMain(); // Check the neighbors matrix has 4 points for each input point. BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::Mat<size_t>> ("neighbors").n_rows, 10); BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::Mat<size_t>> ("neighbors").n_cols, 100); // Check the distances matrix has 4 points for each input point. BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::mat>("distances").n_rows, 10); BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::mat>("distances").n_cols, 100); } /** * Ensure that saved model can be used again. */ BOOST_AUTO_TEST_CASE(KFNModelReuseTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. arma::mat queryData; queryData.randu(3, 90); // 90 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", std::move(referenceData)); SetInputParam("query", queryData); SetInputParam("k", (int) 10); mlpackMain(); arma::Mat<size_t> neighbors; arma::mat distances; neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); // bindings::tests::CleanMemory(); // Reset passed parameters. CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["query"].wasPassed = false; // Input saved model, pass the same query and keep k unchanged. SetInputParam("input_model", std::move(CLI::GetParam<KFNModel*>("output_model"))); SetInputParam("query", queryData); mlpackMain(); // Check that initial output matrices and the output matrices using // saved model are equal. CheckMatrices(neighbors, CLI::GetParam<arma::Mat<size_t>>("neighbors")); CheckMatrices(distances, CLI::GetParam<arma::mat>("distances")); } /* * Ensure that changing the value of epsilon gives us different * approximate KFN results. */ BOOST_AUTO_TEST_CASE(KFNDifferentEpsilonTest) { arma::mat referenceData; referenceData.randu(3, 1000); // 1000 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); SetInputParam("epsilon", (double) 0.2); mlpackMain(); arma::Mat<size_t> neighbors; arma::mat distances; neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); bindings::tests::CleanMemory(); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["epsilon"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("epsilon", (double) 0.8); mlpackMain(); CheckMatricesNotEqual(neighbors, CLI::GetParam<arma::Mat<size_t>>("neighbors")); CheckMatricesNotEqual(distances, CLI::GetParam<arma::mat>("distances")); } /* * Ensure that changing the value of percentage gives us different * approximate KFN results. */ BOOST_AUTO_TEST_CASE(KFNDifferentPercentageTest) { arma::mat referenceData; referenceData.randu(3, 1000); // 1000 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); SetInputParam("percentage", (double) 0.2); mlpackMain(); arma::Mat<size_t> neighbors; arma::mat distances; neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); bindings::tests::CleanMemory(); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["percentage"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("percentage", (double) 0.8); mlpackMain(); CheckMatricesNotEqual(neighbors, CLI::GetParam<arma::Mat<size_t>>("neighbors")); CheckMatricesNotEqual(distances, CLI::GetParam<arma::mat>("distances")); } /* * Ensure that we get different results on running twice in greedy * search mode when random_basis is specified. */ BOOST_AUTO_TEST_CASE(KFNRandomBasisTest) { arma::mat referenceData; referenceData.randu(3, 1000); // 1000 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); CLI::SetPassed("random_basis"); mlpackMain(); arma::Mat<size_t> neighbors; arma::mat distances; neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); BOOST_REQUIRE_EQUAL(CLI::GetParam<KFNModel*>("output_model")->RandomBasis(), true); bindings::tests::CleanMemory(); CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["random_basis"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); mlpackMain(); CheckMatrices(neighbors, CLI::GetParam<arma::Mat<size_t>>("neighbors")); CheckMatrices(distances, CLI::GetParam<arma::mat>("distances")); BOOST_REQUIRE_EQUAL(CLI::GetParam<KFNModel*>("output_model")->RandomBasis(), false); } /* * Ensure that the program runs successfully when we pass true_neighbors * and/or true_distances and fails when those matrices have the wrong shape. */ BOOST_AUTO_TEST_CASE(KFNTrueNeighborDistanceTest) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); mlpackMain(); arma::Mat<size_t> neighbors; arma::mat distances; neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); delete CLI::GetParam<KFNModel*>("output_model"); CLI::GetParam<KFNModel*>("output_model") = NULL; SetInputParam("reference", referenceData); SetInputParam("true_neighbors", neighbors); SetInputParam("true_distances", distances); SetInputParam("epsilon", (double) 0.5); BOOST_REQUIRE_NO_THROW(mlpackMain()); // True output matrices have incorrect shape. arma::Mat<size_t> dummyNeighbors; arma::mat dummyDistances; dummyNeighbors.randu(20, 100); dummyDistances.randu(20, 100); delete CLI::GetParam<KFNModel*>("output_model"); CLI::GetParam<KFNModel*>("output_model") = NULL; CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["true_neighbors"].wasPassed = false; CLI::GetSingleton().Parameters()["true_distances"].wasPassed = false; SetInputParam("reference", std::move(referenceData)); SetInputParam("true_neighbors", std::move(dummyNeighbors)); SetInputParam("true_distances", std::move(dummyDistances)); Log::Fatal.ignoreInput = true; BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error); Log::Fatal.ignoreInput = false; } /* * Ensure that different search algorithms give same result. * We do not consider greedy because it is an approximate algorithm. */ BOOST_AUTO_TEST_CASE(KFNAllAlgorithmsTest) { string algorithms[] = {"dual_tree", "naive", "single_tree"}; const int nofalgorithms = 3; arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. arma::mat queryData; queryData.randu(3, 90); // 90 points in 3 dimensions. // Keep some k <= number of reference points same over all. SetInputParam("k", (int) 10); arma::Mat<size_t> neighborsCompare; arma::mat distancesCompare; arma::Mat<size_t> neighbors; arma::mat distances; // Looping over all the algorithms and storing their outputs. for (int i = 0; i < nofalgorithms; i++) { // Same random inputs, different algorithms. SetInputParam("reference", referenceData); SetInputParam("query", queryData); SetInputParam("algorithm", algorithms[i]); mlpackMain(); if (i == 0) { neighborsCompare = std::move (CLI::GetParam<arma::Mat<size_t>>("neighbors")); distancesCompare = std::move(CLI::GetParam<arma::mat>("distances")); } else { neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); CheckMatrices(neighborsCompare, neighbors); CheckMatrices(distancesCompare, distances); } delete CLI::GetParam<KFNModel*>("output_model"); CLI::GetParam<KFNModel*>("output_model") = NULL; // Reset passed parameters. CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["query"].wasPassed = false; CLI::GetSingleton().Parameters()["algorithm"].wasPassed = false; } } /* * Ensure that different tree types give same result. */ BOOST_AUTO_TEST_CASE(KFNAllTreeTypesTest) { string treetypes[] = {"kd", "vp", "rp", "max-rp", "ub", "cover", "r", "r-star", "x", "ball", "hilbert-r", "r-plus", "r-plus-plus", "oct"}; const int noftreetypes = 14; arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. arma::mat queryData; queryData.randu(3, 90); // 90 points in 3 dimensions. // Keep some k <= number of reference points same over all. SetInputParam("k", (int) 10); arma::Mat<size_t> neighborsCompare; arma::mat distancesCompare; arma::Mat<size_t> neighbors; arma::mat distances; // Looping over all the algorithms and storing their outputs. for (int i = 0; i < noftreetypes; i++) { // Same random inputs, different algorithms. SetInputParam("reference", referenceData); SetInputParam("query", queryData); SetInputParam("tree_type", treetypes[i]); mlpackMain(); if (i == 0) { neighborsCompare = std::move( CLI::GetParam<arma::Mat<size_t>>("neighbors")); distancesCompare = std::move(CLI::GetParam<arma::mat>("distances")); } else { neighbors = std::move(CLI::GetParam<arma::Mat<size_t>>("neighbors")); distances = std::move(CLI::GetParam<arma::mat>("distances")); CheckMatrices(neighborsCompare, neighbors); CheckMatrices(distancesCompare, distances); } delete CLI::GetParam<KFNModel*>("output_model"); CLI::GetParam<KFNModel*>("output_model") = NULL; // Reset passed parameters. CLI::GetSingleton().Parameters()["reference"].wasPassed = false; CLI::GetSingleton().Parameters()["query"].wasPassed = false; CLI::GetSingleton().Parameters()["tree_type"].wasPassed = false; } } /** * Ensure that different leaf sizes give different results. */ BOOST_AUTO_TEST_CASE(KFNDifferentLeafSizes) { arma::mat referenceData; referenceData.randu(3, 100); // 100 points in 3 dimensions. // Random input, some k <= number of reference points. SetInputParam("reference", referenceData); SetInputParam("k", (int) 10); SetInputParam("leaf_size", (int) 1); mlpackMain(); BOOST_CHECK_EQUAL(CLI::GetParam<KFNModel*>("output_model")->LeafSize(), (int) 1); bindings::tests::CleanMemory(); // Reset passed parameters. CLI::GetSingleton().Parameters()["reference"].wasPassed = false; // Input saved model, pass the same query and keep k unchanged. SetInputParam("reference", std::move(referenceData)); SetInputParam("k", (int) 10); SetInputParam("leaf_size", (int) 10); mlpackMain(); // Check that initial output matrices and the output matrices using // saved model are equal. BOOST_CHECK_EQUAL(CLI::GetParam<KFNModel*>("output_model")->LeafSize(), (int) 10); } BOOST_AUTO_TEST_SUITE_END();
30.312217
78
0.703438
KimSangYeon-DGU
085a807b135e210d3600bc9628495fcf2f95d4da
1,008
cc
C++
leetcode/ac/215.cc
Shuo626/algorithm-killer
9ca31226b89f096277b9067207001704068a2f89
[ "MIT" ]
null
null
null
leetcode/ac/215.cc
Shuo626/algorithm-killer
9ca31226b89f096277b9067207001704068a2f89
[ "MIT" ]
null
null
null
leetcode/ac/215.cc
Shuo626/algorithm-killer
9ca31226b89f096277b9067207001704068a2f89
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: int findKthLargest(vector<int>& nums, int k) { int l, r; l = 0; r = nums.size() - 1; k -= 1; while (true) { int mid; mid = sort(nums, l, r); if (mid == k) { return nums[mid]; } else if (mid < k) { l = mid + 1; } else { r = mid - 1; } } } int sort(vector<int>& nums, int l, int r) { int i, j; i = l; j = l; int tmp; tmp = nums[r]; while (j < r) { if (nums[j] > tmp) { swap(nums, i, j); i++; } j++; } nums[r] = nums[i]; nums[i] = tmp; return i; } void swap(vector<int>& nums, int i, int j) { int tmp; tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } };
17.37931
50
0.339286
Shuo626
085bb94713b361dc2d9ff2c71932646f2aa86425
2,992
hpp
C++
doc/quickbook/oglplus/quickref/bound/buffer.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
doc/quickbook/oglplus/quickref/bound/buffer.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
doc/quickbook/oglplus/quickref/bound/buffer.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
/* * Automatically generated file, do not edit manually! * * Copyright 2010-2019 Matus Chochlik. 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) */ //[oglplus_object_BoundObjOps_Buffer template <> class __BoundObjOps<__tag_Buffer> { private: using ExplicitOps = typename __ObjectOps_Explicit_Buffer<__tag_ExplicitSel, __tag_Buffer>; public: using Target = typename ExplicitOps::Target; Target target; BoundObjOps(); BoundObjOps(Target init_tgt); GLint GetIntParam(GLenum query) const; __Boolean Mapped() const; const BoundObjOps& Resize( __BufferSize size, __BufferUsage usage = BufferUsage::StaticDraw) const; const BoundObjOps& Data( const __BufferData& data, __BufferUsage usage = BufferUsage::StaticDraw) const; const BoundObjOps& RawData( __BufferSize size, const GLvoid* data, __BufferUsage usage = BufferUsage::StaticDraw) const; template <typename GLtype> const BoundObjOps& Data( __SizeType count, const GLtype* data, __BufferUsage usage = BufferUsage::StaticDraw) const; const BoundObjOps& SubData( __BufferSize offset, const __BufferData& data) const; template <typename GLtype> const BoundObjOps& SubData( __BufferSize offset, __SizeType count, const GLtype* data) const; #if GL_VERSION_4_3 template <typename GLtype> const BoundObjOps& ClearData( __PixelDataInternalFormat internal_format, __PixelDataFormat format, const GLtype* data) const; #endif #if GL_VERSION_4_3 template <typename GLtype> const BoundObjOps& ClearSubData( __PixelDataInternalFormat internal_format, __BufferSize offset, __BufferSize size, __PixelDataFormat format, const GLtype* data) const; #endif #if GL_VERSION_4_4 || GL_ARB_buffer_storage const BoundObjOps& Storage( const __BufferData& data, __Bitfield<__BufferStorageBit> flags) const; #endif #if GL_VERSION_4_4 || GL_ARB_buffer_storage const BoundObjOps& Storage( __BufferSize size, const void* data, __Bitfield<__BufferStorageBit> flags) const; #endif #if GL_VERSION_4_4 || GL_ARB_buffer_storage __Boolean ImmutableStorage() const; #endif #if GL_VERSION_4_4 || GL_ARB_buffer_storage __Bitfield<__BufferStorageBit> StorageFlags() const; #endif #if GL_ARB_sparse_buffer const BoundObjOps& PageCommitment( __BufferSize offset, __BufferSize size, __Boolean commit) const; #endif __SizeType Size() const; __BufferUsage Usage() const; __Bitfield<__BufferMapAccess> __Access() const; #if GL_NV_shader_buffer_load const BoundObjOps& MakeResident(__AccessSpecifier access) const; #endif #if GL_NV_shader_buffer_load const BoundObjOps& MakeNonResident() const; #endif #if GL_NV_shader_buffer_load __BufferGPUAddress GPUAddress() const; #endif }; //]
26.017391
78
0.735963
matus-chochlik
086076fa0fb7740ad8ac178d8489db11364bdef3
2,186
cpp
C++
tutorials/micro/flags.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
629
2018-11-19T21:03:01.000Z
2022-02-25T03:31:40.000Z
tutorials/micro/flags.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
27
2018-11-23T22:49:28.000Z
2020-05-15T21:09:30.000Z
tutorials/micro/flags.cpp
unghee/TorchCraftAI
e6d596483d2a9a8b796765ed98097fcae39b6ac0
[ "MIT" ]
129
2018-11-22T01:16:56.000Z
2022-03-29T15:24:16.000Z
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gflags/gflags.h> DEFINE_uint64(num_threads, 20, "How many threads to use"); DEFINE_string(model, "PF", "Models: PF"); DEFINE_string(opponent, "closest", "opponent: attack_move|closest|weakest"); DEFINE_bool( relative_reward, true, "Use a reward relative to the scenario or not"); DEFINE_double(sigma, 1e-2, "Mutation step-size/learning rate for CES"); DEFINE_string(scenario, "5vu_10zl", "Scenarios (refer to environment.cpp)"); DEFINE_bool( list_scenarios, false, "Just print out the list of available scenarios and exit."); DEFINE_string( map_path_prefix, "./", "To run this from a different directory, you have to specify where the " "maps are"); DEFINE_uint64(batch_size, 64, "batch size"); DEFINE_uint64(max_frames, 24 * 60, "Max number of frames per episode"); // -1 is the max for an unsigned int DEFINE_uint64(max_episodes, -1, "Max number of episodes to train for"); DEFINE_uint64(frame_skip, 7, "Frames between forward passes"); DEFINE_bool(enable_gui, false, "Enable GUI for first thread"); DEFINE_bool(illustrate, false, "Draw interesting circles 'n' lines 'n' stuff"); DEFINE_string(results, ".", "Results directory"); DEFINE_uint64(checkpoint_freq, 50, "Number of updates between checkpoints"); DEFINE_uint64(test_freq, 50, "Number of updates between test runs"); DEFINE_uint64(num_test_episodes, 100, "Number of episodes for each test run"); DEFINE_double( realtime, -1, "BWAPI speed, as a multiple of human (fastest) speed. Negative values are " "unbounded speed."); DEFINE_bool(resume, false, "Resume training from previous checkpoint"); DEFINE_bool(evaluate, false, "Evaluation mode"); DEFINE_bool(gpu, true, "Use GPU"); DEFINE_bool(sample_command, true, "Sample or argmax on the command"); DEFINE_string( dump_replays, "eval", "When to dump game replays (train|eval|always|never)"); DEFINE_uint64( dump_replays_rate, 200, "Replays sampling rate (default = 200: will dump 0.5% of the games)");
39.035714
79
0.728728
unghee
08647e8de92e3ddc10229eeda565ab8ada5580ca
5,221
cc
C++
weblayer/browser/browsing_data_remover_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
weblayer/browser/browsing_data_remover_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
weblayer/browser/browsing_data_remover_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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 "weblayer/browser/browsing_data_remover_delegate.h" #include "base/callback.h" #include "build/build_config.h" #include "components/browsing_data/content/browsing_data_helper.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/heavy_ad_intervention/heavy_ad_blocklist.h" #include "components/heavy_ad_intervention/heavy_ad_service.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browsing_data_filter_builder.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "weblayer/browser/browser_process.h" #include "weblayer/browser/favicon/favicon_service_impl.h" #include "weblayer/browser/favicon/favicon_service_impl_factory.h" #include "weblayer/browser/heavy_ad_service_factory.h" #include "weblayer/browser/host_content_settings_map_factory.h" #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "weblayer/browser/safe_browsing/safe_browsing_service.h" namespace weblayer { BrowsingDataRemoverDelegate::BrowsingDataRemoverDelegate( content::BrowserContext* browser_context) : browser_context_(browser_context) {} BrowsingDataRemoverDelegate::~BrowsingDataRemoverDelegate() = default; BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher BrowsingDataRemoverDelegate::GetOriginTypeMatcher() { return EmbedderOriginTypeMatcher(); } bool BrowsingDataRemoverDelegate::MayRemoveDownloadHistory() { return true; } std::vector<std::string> BrowsingDataRemoverDelegate::GetDomainsForDeferredCookieDeletion( uint64_t remove_mask) { return {}; } void BrowsingDataRemoverDelegate::RemoveEmbedderData( const base::Time& delete_begin, const base::Time& delete_end, uint64_t remove_mask, content::BrowsingDataFilterBuilder* filter_builder, uint64_t origin_type_mask, base::OnceCallback<void(uint64_t)> callback) { callback_ = std::move(callback); // Note: if history is ever added to WebLayer, also remove isolated origins // when history is cleared. if (remove_mask & DATA_TYPE_ISOLATED_ORIGINS) { browsing_data::RemoveSiteIsolationData( user_prefs::UserPrefs::Get(browser_context_)); } HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForBrowserContext(browser_context_); if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE) { browsing_data::RemovePrerenderCacheData( NoStatePrefetchManagerFactory::GetForBrowserContext(browser_context_)); } if (remove_mask & DATA_TYPE_FAVICONS) { auto* service = FaviconServiceImplFactory::GetForBrowserContext(browser_context_); if (service) { // The favicon database doesn't track enough information to remove // favicons in a time range. Delete everything. service->DeleteAndRecreateDatabase(CreateTaskCompletionClosure()); } } if (remove_mask & DATA_TYPE_AD_INTERVENTIONS) { heavy_ad_intervention::HeavyAdService* heavy_ad_service = HeavyAdServiceFactory::GetForBrowserContext(browser_context_); if (heavy_ad_service->heavy_ad_blocklist()) { heavy_ad_service->heavy_ad_blocklist()->ClearBlockList(delete_begin, delete_end); } } // We ignore the DATA_TYPE_COOKIES request if UNPROTECTED_WEB is not set, // so that callers who request COOKIES_AND_SITE_DATA with PROTECTED_WEB // don't accidentally remove the cookies that are associated with the // UNPROTECTED_WEB origin. This is necessary because cookies are not separated // between UNPROTECTED_WEB and PROTECTED_WEB. if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_COOKIES) { network::mojom::NetworkContext* safe_browsing_context = nullptr; #if defined(OS_ANDROID) safe_browsing_context = BrowserProcess::GetInstance() ->GetSafeBrowsingService() ->GetNetworkContext(); #endif browsing_data::RemoveEmbedderCookieData( delete_begin, delete_end, filter_builder, host_content_settings_map, safe_browsing_context, base::BindOnce( &BrowsingDataRemoverDelegate::CreateTaskCompletionClosure, base::Unretained(this))); } if (remove_mask & DATA_TYPE_SITE_SETTINGS) { browsing_data::RemoveSiteSettingsData(delete_begin, delete_end, host_content_settings_map); } RunCallbackIfDone(); } base::OnceClosure BrowsingDataRemoverDelegate::CreateTaskCompletionClosure() { ++pending_tasks_; return base::BindOnce(&BrowsingDataRemoverDelegate::OnTaskComplete, weak_ptr_factory_.GetWeakPtr()); } void BrowsingDataRemoverDelegate::OnTaskComplete() { pending_tasks_--; RunCallbackIfDone(); } void BrowsingDataRemoverDelegate::RunCallbackIfDone() { if (pending_tasks_ != 0) return; std::move(callback_).Run(/*failed_data_types=*/0); } } // namespace weblayer
37.561151
81
0.758092
zealoussnow
0867612614a141139e36fd40b7797ab207cb5684
4,623
cpp
C++
src/engine/private/misc/Frustum.cpp
PierreEVEN/HeadlessEngine
95ffef8a7a71c5bb6e806a96c39e88cfc24311a9
[ "MIT" ]
2
2021-07-12T08:58:49.000Z
2021-09-04T10:31:04.000Z
src/engine/private/misc/Frustum.cpp
PierreEVEN/TestFlightSimulator
95ffef8a7a71c5bb6e806a96c39e88cfc24311a9
[ "MIT" ]
1
2021-10-11T13:09:32.000Z
2021-10-11T13:09:32.000Z
src/engine/private/misc/Frustum.cpp
PierreEVEN/HeadlessEngine
95ffef8a7a71c5bb6e806a96c39e88cfc24311a9
[ "MIT" ]
null
null
null
#include "misc/Frustum.h" Box3D::Box3D(const Box3D& source, const glm::dmat4& transformation) { min = transformation * glm::dvec4(source.min, 1.0); max = transformation * glm::dvec4(source.max, 1.0); if (min.x > max.x) { const double temp = max.x; max.x = min.x; min.x = temp; } if (min.y > max.y) { const double temp = max.y; max.y = min.y; min.y = temp; } if (min.z > max.z) { const double temp = max.z; max.z = min.z; min.z = temp; } } void Box3D::add_position(const glm::dvec3& in_position) { if (in_position.x < min.x) min.x = in_position.x; if (in_position.y < min.y) min.y = in_position.y; if (in_position.z < min.z) min.z = in_position.z; if (in_position.x > max.x) max.x = in_position.x; if (in_position.y > max.y) max.y = in_position.y; if (in_position.z > max.z) max.z = in_position.z; } Frustum::Frustum(glm::dmat4 view_matrix) { view_matrix = glm::transpose(view_matrix); planes[Left] = view_matrix[3] + view_matrix[0]; planes[Right] = view_matrix[3] - view_matrix[0]; planes[Bottom] = view_matrix[3] + view_matrix[1]; planes[Top] = view_matrix[3] - view_matrix[1]; planes[Near] = view_matrix[3] + view_matrix[2]; planes[Far] = view_matrix[3] - view_matrix[2]; glm::dvec3 crosses[Combinations] = { cross(glm::dvec3(planes[Left]), glm::dvec3(planes[Right])), cross(glm::dvec3(planes[Left]), glm::dvec3(planes[Bottom])), cross(glm::dvec3(planes[Left]), glm::dvec3(planes[Top])), cross(glm::dvec3(planes[Left]), glm::dvec3(planes[Near])), cross(glm::dvec3(planes[Left]), glm::dvec3(planes[Far])), cross(glm::dvec3(planes[Right]), glm::dvec3(planes[Bottom])), cross(glm::dvec3(planes[Right]), glm::dvec3(planes[Top])), cross(glm::dvec3(planes[Right]), glm::dvec3(planes[Near])), cross(glm::dvec3(planes[Right]), glm::dvec3(planes[Far])), cross(glm::dvec3(planes[Bottom]), glm::dvec3(planes[Top])), cross(glm::dvec3(planes[Bottom]), glm::dvec3(planes[Near])), cross(glm::dvec3(planes[Bottom]), glm::dvec3(planes[Far])), cross(glm::dvec3(planes[Top]), glm::dvec3(planes[Near])), cross(glm::dvec3(planes[Top]), glm::dvec3(planes[Far])), cross(glm::dvec3(planes[Near]), glm::dvec3(planes[Far]))}; points[0] = intersection<Left, Bottom, Near>(crosses); points[1] = intersection<Left, Top, Near>(crosses); points[2] = intersection<Right, Bottom, Near>(crosses); points[3] = intersection<Right, Top, Near>(crosses); points[4] = intersection<Left, Bottom, Far>(crosses); points[5] = intersection<Left, Top, Far>(crosses); points[6] = intersection<Right, Bottom, Far>(crosses); points[7] = intersection<Right, Top, Far>(crosses); } bool Frustum::is_box_visible(const Box3D& box) const { glm::dvec3 minp = box.get_min(); glm::dvec3 maxp = box.get_max(); // check box outside/inside of frustum for (int i = 0; i < Count; i++) { if (dot(planes[i], glm::dvec4(minp.x, minp.y, minp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(maxp.x, minp.y, minp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(minp.x, maxp.y, minp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(maxp.x, maxp.y, minp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(minp.x, minp.y, maxp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(maxp.x, minp.y, maxp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(minp.x, maxp.y, maxp.z, 1.0f)) < 0.0 && dot(planes[i], glm::dvec4(maxp.x, maxp.y, maxp.z, 1.0f)) < 0.0) { return false; } } // check frustum outside/inside box int out; out = 0; for (auto m_point : points) out += ((m_point.x > maxp.x) ? 1 : 0); if (out == 8) return false; out = 0; for (auto m_point : points) out += ((m_point.x < minp.x) ? 1 : 0); if (out == 8) return false; out = 0; for (auto m_point : points) out += ((m_point.y > maxp.y) ? 1 : 0); if (out == 8) return false; out = 0; for (auto m_point : points) out += ((m_point.y < minp.y) ? 1 : 0); if (out == 8) return false; out = 0; for (auto m_point : points) out += ((m_point.z > maxp.z) ? 1 : 0); if (out == 8) return false; out = 0; for (auto m_point : points) out += ((m_point.z < minp.z) ? 1 : 0); if (out == 8) return false; return true; }
38.206612
209
0.562838
PierreEVEN
0867f6604f233f61edbe96d8713581b3d474c5f5
764
cpp
C++
725/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
725/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
725/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // your code goes here int N; bool first = true; while(scanf("%d", &N)){ if(N == 0) break; bool ans = false; if(! first){ printf("\n"); } for(int fghij = 1234; fghij <= 98765 / N; fghij++){ int abcde = fghij * N; int tmp, used = (fghij < 10000); // if digit f=0, then we have to flag it //cout << used << "\n"; tmp = abcde; while(tmp){ used |= 1 << (tmp % 10); tmp /= 10; } tmp = fghij; while(tmp){ used |= 1 << (tmp % 10); tmp /= 10; } if(used == (1<<10) - 1){ printf("%0.5d / %0.5d = %d\n", abcde, fghij, N); ans = true; } } if(!ans) printf("There are no solutions for %d.\n", N); first = false; } return 0; }
18.190476
76
0.494764
sabingoyek
08682d1ad8ab55ac1101978e350d51149d14b187
5,691
cpp
C++
Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp
Karshilov/Dorothy-SSR
cce19ed2218d76f941977370f6b3894e2f87236a
[ "MIT" ]
1
2021-07-19T11:30:54.000Z
2021-07-19T11:30:54.000Z
Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
null
null
null
Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
null
null
null
/* * Original work Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2020 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "PlayRho/Dynamics/WorldContact.hpp" #include "PlayRho/Dynamics/World.hpp" #include "PlayRho/Dynamics/WorldBody.hpp" #include "PlayRho/Dynamics/WorldShape.hpp" #include "PlayRho/Dynamics/Body.hpp" // for GetBody #include "PlayRho/Dynamics/Contacts/Contact.hpp" #include "PlayRho/Collision/Manifold.hpp" #include "PlayRho/Collision/WorldManifold.hpp" namespace playrho { namespace d2 { ContactCounter GetContactRange(const World& world) noexcept { return world.GetContactRange(); } std::vector<KeyedContactPtr> GetContacts(const World& world) noexcept { return world.GetContacts(); } const Contact& GetContact(const World& world, ContactID id) { return world.GetContact(id); } void SetContact(World& world, ContactID id, const Contact& value) { world.SetContact(id, value); } bool IsTouching(const World& world, ContactID id) { return IsTouching(GetContact(world, id)); } bool IsAwake(const World& world, ContactID id) { return IsActive(GetContact(world, id)); } void SetAwake(World& world, ContactID id) { // Note awakening bodies wakens the contact. SetAwake(world, GetBodyA(world, id)); SetAwake(world, GetBodyB(world, id)); } ChildCounter GetChildIndexA(const World& world, ContactID id) { return GetChildIndexA(GetContact(world, id)); } ChildCounter GetChildIndexB(const World& world, ContactID id) { return GetChildIndexB(GetContact(world, id)); } ShapeID GetShapeA(const World& world, ContactID id) { return GetShapeA(GetContact(world, id)); } ShapeID GetShapeB(const World& world, ContactID id) { return GetShapeB(GetContact(world, id)); } BodyID GetBodyA(const World& world, ContactID id) { return GetBodyA(GetContact(world, id)); } BodyID GetBodyB(const World& world, ContactID id) { return GetBodyB(GetContact(world, id)); } TimestepIters GetToiCount(const World& world, ContactID id) { return GetToiCount(GetContact(world, id)); } bool NeedsFiltering(const World& world, ContactID id) { return NeedsFiltering(GetContact(world, id)); } bool NeedsUpdating(const World& world, ContactID id) { return NeedsUpdating(GetContact(world, id)); } bool HasValidToi(const World& world, ContactID id) { return HasValidToi(GetContact(world, id)); } Real GetToi(const World& world, ContactID id) { return GetToi(GetContact(world, id)); } Real GetFriction(const World& world, ContactID id) { return GetFriction(GetContact(world, id)); } Real GetRestitution(const World& world, ContactID id) { return GetRestitution(GetContact(world, id)); } void SetFriction(World& world, ContactID id, Real value) { auto contact = GetContact(world, id); SetFriction(contact, value); SetContact(world, id, contact); } void SetRestitution(World& world, ContactID id, Real value) { auto contact = GetContact(world, id); SetRestitution(contact, value); SetContact(world, id, contact); } const Manifold& GetManifold(const World& world, ContactID id) { return world.GetManifold(id); } LinearVelocity GetTangentSpeed(const World& world, ContactID id) { return GetTangentSpeed(GetContact(world, id)); } void SetTangentSpeed(World& world, ContactID id, LinearVelocity value) { auto contact = GetContact(world, id); SetTangentSpeed(contact, value); SetContact(world, id, contact); } bool IsEnabled(const World& world, ContactID id) { return IsEnabled(GetContact(world, id)); } void SetEnabled(World& world, ContactID id) { auto contact = GetContact(world, id); SetEnabled(contact); SetContact(world, id, contact); } void UnsetEnabled(World& world, ContactID id) { auto contact = GetContact(world, id); UnsetEnabled(contact); SetContact(world, id, contact); } Real GetDefaultFriction(const World& world, ContactID id) { const auto& c = world.GetContact(id); return GetDefaultFriction(world.GetShape(GetShapeA(c)), world.GetShape(GetShapeB(c))); } Real GetDefaultRestitution(const World& world, ContactID id) { const auto& c = world.GetContact(id); return GetDefaultRestitution(world.GetShape(GetShapeA(c)), world.GetShape(GetShapeB(c))); } WorldManifold GetWorldManifold(const World& world, ContactID id) { return GetWorldManifold(world, GetContact(world, id), GetManifold(world, id)); } ContactCounter GetTouchingCount(const World& world) noexcept { const auto contacts = world.GetContacts(); return static_cast<ContactCounter>(count_if(cbegin(contacts), cend(contacts), [&](const auto &c) { return IsTouching(world, std::get<ContactID>(c)); })); } } // namespace d2 } // namespace playrho
26.347222
94
0.728167
Karshilov
086ab5c51ed2fac28545772d2f981c59bdacc289
1,047
cc
C++
third_party/blink/renderer/core/editing/plain_text_range_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/editing/plain_text_range_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/editing/plain_text_range_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 "third_party/blink/renderer/core/editing/plain_text_range.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/testing/editing_test_base.h" namespace blink { class PlainTextRangeTest : public EditingTestBase {}; TEST_F(PlainTextRangeTest, RangeContainingTableCellBoundary) { SetBodyInnerHTML( "<table id='sample' contenteditable><tr><td>a</td><td " "id='td2'>b</td></tr></table>"); Element* table = GetElementById("sample"); PlainTextRange plain_text_range(2, 2); const EphemeralRange& range = plain_text_range.CreateRange(*table); EXPECT_EQ( "<table contenteditable id=\"sample\"><tbody><tr><td>a</td><td " "id=\"td2\">|b</td></tr></tbody></table>", GetCaretTextFromBody(range.StartPosition())); EXPECT_TRUE(range.IsCollapsed()); } } // namespace blink
34.9
78
0.726839
zealoussnow
086c08dfd3218b742bcd7757d28fc30ebc762c88
22,838
cpp
C++
drivers/kbd/src/main.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
1
2021-02-03T09:21:08.000Z
2021-02-03T09:21:08.000Z
drivers/kbd/src/main.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
null
null
null
drivers/kbd/src/main.cpp
Apache-HB/managarm
df922a987167948369ea1d0e675925126bb5fdad
[ "MIT" ]
null
null
null
#include <algorithm> #include <deque> #include <iostream> #include <stdio.h> #include <string.h> #include <linux/input.h> #include <arch/bits.hpp> #include <arch/register.hpp> #include <arch/io_space.hpp> #include <async/result.hpp> #include <boost/intrusive/list.hpp> #include <helix/ipc.hpp> #include <libevbackend.hpp> #include <protocols/mbus/client.hpp> #include <async/queue.hpp> #include <helix/timer.hpp> #include "spec.hpp" #include "ps2.hpp" namespace { constexpr bool logPackets = false; constexpr bool logMouse = false; } constexpr int default_timeout = 100'000'000; // -------------------------------------------------------------------- // Controller // -------------------------------------------------------------------- Controller::Controller() { for (auto &dev : _devices) dev = nullptr; HEL_CHECK(helAccessIrq(1, &_irq1Handle)); _irq1 = helix::UniqueIrq(_irq1Handle); uintptr_t ports[] = { DATA, STATUS }; HelHandle handle; HEL_CHECK(helAccessIo(ports, 2, &handle)); HEL_CHECK(helEnableIo(handle)); _space = arch::global_io.subspace(DATA); } async::detached Controller::init() { handleIrqsFor(_irq1, 0); _space = arch::global_io.subspace(DATA); // disable both devices submitCommand(controller_cmd::DisablePort{}, 0); submitCommand(controller_cmd::DisablePort{}, 1); // flush the output buffer while(_space.load(kbd_register::status) & status_bits::outBufferStatus) _space.load(kbd_register::data); // enable interrupt for second device auto configuration = submitCommand(controller_cmd::GetByte0{}); _hasSecondPort = configuration & (1 << 5); configuration |= 0b11; // enable interrupts configuration &= ~(1 << 6); // disable translation submitCommand(controller_cmd::SetByte0{}, configuration); // enable devices submitCommand(controller_cmd::EnablePort{}, 0); _devices[0] = new Device{this, 0}; co_await _devices[0]->init(); if (!_devices[0]->exists()) { // port exists, device doesnt delete _devices[0]; _devices[0] = nullptr; } if (_hasSecondPort) { printf("setting up second port!\n"); HEL_CHECK(helAccessIrq(12, &_irq12Handle)); _irq12 = helix::UniqueIrq(_irq12Handle); handleIrqsFor(_irq12, 1); submitCommand(controller_cmd::EnablePort{}, 1); _devices[1] = new Device{this, 1}; co_await _devices[1]->init(); if (!_devices[1]->exists()) { // port exists, device doesnt delete _devices[1]; _devices[1] = nullptr; } } co_return; } void Controller::sendCommandByte(uint8_t byte) { _space.store(kbd_register::command, byte); } void Controller::sendDataByte(uint8_t byte) { _space.store(kbd_register::data, byte); } std::optional<uint8_t> Controller::recvByte(uint64_t timeout) { if (timeout) { uint64_t start, end, current; HEL_CHECK(helGetClock(&start)); end = start + timeout; current = start; while (!(_space.load(kbd_register::status) & status_bits::outBufferStatus) && current < end) HEL_CHECK(helGetClock(&current)); bool cancelled = current >= end; if (cancelled) return std::nullopt; return _space.load(kbd_register::data); } while (!(_space.load(kbd_register::status) & status_bits::outBufferStatus)) ; return _space.load(kbd_register::data); } void Controller::submitCommand(controller_cmd::DisablePort tag, int port) { if (port == 0) sendCommandByte(disable1stPort); else if (port == 1) sendCommandByte(disable2ndPort); } void Controller::submitCommand(controller_cmd::EnablePort tag, int port) { if (port == 0) sendCommandByte(enable1stPort); else if (port == 1) sendCommandByte(enable2ndPort); } uint8_t Controller::submitCommand(controller_cmd::GetByte0 tag) { sendCommandByte(readByte0); auto result = recvByte(default_timeout); assert(result != std::nullopt && "timed out"); return result.value(); } void Controller::submitCommand(controller_cmd::SetByte0 tag, uint8_t val) { sendCommandByte(writeByte0); sendDataByte(val); } void Controller::submitCommand(controller_cmd::SendBytePort2 tag) { sendCommandByte(0xD4); // TODO: define a constant? } async::detached Controller::handleIrqsFor(helix::UniqueIrq &irq, int port) { uint64_t sequence = 0; while(true) { auto await = co_await helix_ng::awaitEvent(irq, sequence); HEL_CHECK(await.error()); sequence = await.sequence(); // TODO: detect whether we want to ack/nack processData(port); HEL_CHECK(helAcknowledgeIrq(irq.getHandle(), kHelAckAcknowledge, sequence)); } } bool Controller::processData(int port) { size_t count = 0; while (_space.load(kbd_register::status) & status_bits::outBufferStatus) { auto val = _space.load(kbd_register::data); if (logPackets) printf("ps2-hid: received byte %02x\n!", val); if (!_devices[port]) { printf("ps2-hid: received irq for non-existent device\n!"); } else { _devices[port]->pushByte(val); } count++; } return count > 0; } // -------------------------------------------------------------------- // Controller::Device // -------------------------------------------------------------------- Controller::Device::Device(Controller *controller, int port) : _controller{controller}, _port{port}, _deviceType{0}, _exists{false} { } async::result<void> Controller::Device::init() { auto res1 = co_await submitCommand(device_cmd::DisableScan{}); if (std::holds_alternative<NoDevice>(res1)) co_return; // not present auto res2 = co_await submitCommand(device_cmd::Identify{}); _exists = !std::holds_alternative<NoDevice>(res2); _deviceType = _exists ? std::get<DeviceType>(res2) : DeviceType{}; if (!_exists) co_return; _evDev = std::make_shared<libevbackend::EventDevice>(); if (_deviceType.keyboard) co_await kbdInit(); if (_deviceType.mouse) co_await mouseInit(); auto res3 = co_await submitCommand(device_cmd::EnableScan{}); assert(std::holds_alternative<std::monostate>(res3)); //printf("done setting up ps2kbd: 2\n"); } async::result<void> Controller::Device::kbdInit() { //set scancode 1 auto res1 = co_await submitCommand(device_cmd::SetScancodeSet{}, 1); assert(std::holds_alternative<std::monostate>(res1)); // make sure it's used auto res2 = co_await submitCommand(device_cmd::GetScancodeSet{}); assert(std::holds_alternative<int>(res2)); assert(std::get<int>(res2) == 1); //setup evdev stuff _evDev->enableEvent(EV_KEY, KEY_A); _evDev->enableEvent(EV_KEY, KEY_B); _evDev->enableEvent(EV_KEY, KEY_C); _evDev->enableEvent(EV_KEY, KEY_D); _evDev->enableEvent(EV_KEY, KEY_E); _evDev->enableEvent(EV_KEY, KEY_F); _evDev->enableEvent(EV_KEY, KEY_G); _evDev->enableEvent(EV_KEY, KEY_H); _evDev->enableEvent(EV_KEY, KEY_I); _evDev->enableEvent(EV_KEY, KEY_J); _evDev->enableEvent(EV_KEY, KEY_K); _evDev->enableEvent(EV_KEY, KEY_L); _evDev->enableEvent(EV_KEY, KEY_M); _evDev->enableEvent(EV_KEY, KEY_N); _evDev->enableEvent(EV_KEY, KEY_O); _evDev->enableEvent(EV_KEY, KEY_P); _evDev->enableEvent(EV_KEY, KEY_Q); _evDev->enableEvent(EV_KEY, KEY_R); _evDev->enableEvent(EV_KEY, KEY_S); _evDev->enableEvent(EV_KEY, KEY_T); _evDev->enableEvent(EV_KEY, KEY_U); _evDev->enableEvent(EV_KEY, KEY_V); _evDev->enableEvent(EV_KEY, KEY_W); _evDev->enableEvent(EV_KEY, KEY_X); _evDev->enableEvent(EV_KEY, KEY_Y); _evDev->enableEvent(EV_KEY, KEY_Z); _evDev->enableEvent(EV_KEY, KEY_1); _evDev->enableEvent(EV_KEY, KEY_2); _evDev->enableEvent(EV_KEY, KEY_3); _evDev->enableEvent(EV_KEY, KEY_4); _evDev->enableEvent(EV_KEY, KEY_5); _evDev->enableEvent(EV_KEY, KEY_6); _evDev->enableEvent(EV_KEY, KEY_7); _evDev->enableEvent(EV_KEY, KEY_8); _evDev->enableEvent(EV_KEY, KEY_9); _evDev->enableEvent(EV_KEY, KEY_0); _evDev->enableEvent(EV_KEY, KEY_ENTER); _evDev->enableEvent(EV_KEY, KEY_ESC); _evDev->enableEvent(EV_KEY, KEY_BACKSPACE); _evDev->enableEvent(EV_KEY, KEY_TAB); _evDev->enableEvent(EV_KEY, KEY_SPACE); _evDev->enableEvent(EV_KEY, KEY_MINUS); _evDev->enableEvent(EV_KEY, KEY_EQUAL); _evDev->enableEvent(EV_KEY, KEY_LEFTBRACE); _evDev->enableEvent(EV_KEY, KEY_RIGHTBRACE); _evDev->enableEvent(EV_KEY, KEY_BACKSLASH); _evDev->enableEvent(EV_KEY, KEY_SEMICOLON); _evDev->enableEvent(EV_KEY, KEY_COMMA); _evDev->enableEvent(EV_KEY, KEY_DOT); _evDev->enableEvent(EV_KEY, KEY_SLASH); _evDev->enableEvent(EV_KEY, KEY_HOME); _evDev->enableEvent(EV_KEY, KEY_PAGEUP); _evDev->enableEvent(EV_KEY, KEY_DELETE); _evDev->enableEvent(EV_KEY, KEY_END); _evDev->enableEvent(EV_KEY, KEY_PAGEDOWN); _evDev->enableEvent(EV_KEY, KEY_RIGHT); _evDev->enableEvent(EV_KEY, KEY_LEFT); _evDev->enableEvent(EV_KEY, KEY_DOWN); _evDev->enableEvent(EV_KEY, KEY_UP); _evDev->enableEvent(EV_KEY, KEY_LEFTCTRL); _evDev->enableEvent(EV_KEY, KEY_LEFTSHIFT); _evDev->enableEvent(EV_KEY, KEY_LEFTALT); _evDev->enableEvent(EV_KEY, KEY_LEFTMETA); _evDev->enableEvent(EV_KEY, KEY_RIGHTCTRL); _evDev->enableEvent(EV_KEY, KEY_RIGHTSHIFT); _evDev->enableEvent(EV_KEY, KEY_RIGHTALT); _evDev->enableEvent(EV_KEY, KEY_RIGHTMETA); // Create an mbus object for the partition. auto root = co_await mbus::Instance::global().getRoot(); mbus::Properties descriptor{ {"unix.subsystem", mbus::StringItem{"input"}} }; auto handler = mbus::ObjectHandler{} .withBind([=] () -> async::result<helix::UniqueDescriptor> { helix::UniqueLane local_lane, remote_lane; std::tie(local_lane, remote_lane) = helix::createStream(); libevbackend::serveDevice(_evDev, std::move(local_lane)); async::promise<helix::UniqueDescriptor> promise; promise.set_value(std::move(remote_lane)); return promise.async_get(); }); co_await root.createObject("ps2kbd", descriptor, std::move(handler)); printf("done setting up ps2kbd\n"); runKbd(); } async::result<void> Controller::Device::mouseInit() { // attempt to enable scroll wheel auto res1 = co_await submitCommand(device_cmd::SetReportRate{}, 200); assert(std::holds_alternative<std::monostate>(res1)); res1 = co_await submitCommand(device_cmd::SetReportRate{}, 100); assert(std::holds_alternative<std::monostate>(res1)); res1 = co_await submitCommand(device_cmd::SetReportRate{}, 80); assert(std::holds_alternative<std::monostate>(res1)); auto res2 = co_await submitCommand(device_cmd::Identify{}); assert(std::holds_alternative<DeviceType>(res2)); auto type = std::get<DeviceType>(res2); assert(type.mouse); // ensure the mouse is still a mouse _deviceType.hasScrollWheel = _deviceType.hasScrollWheel || type.hasScrollWheel; // attempt to enable the 4th and 5th buttons res1 = co_await submitCommand(device_cmd::SetReportRate{}, 200); assert(std::holds_alternative<std::monostate>(res1)); res1 = co_await submitCommand(device_cmd::SetReportRate{}, 200); assert(std::holds_alternative<std::monostate>(res1)); res1 = co_await submitCommand(device_cmd::SetReportRate{}, 80); assert(std::holds_alternative<std::monostate>(res1)); res2 = co_await submitCommand(device_cmd::Identify{}); assert(std::holds_alternative<DeviceType>(res2)); type = std::get<DeviceType>(res2); assert(type.mouse); // ensure the mouse is still a mouse _deviceType.has5Buttons = _deviceType.has5Buttons || type.has5Buttons; // set report rate to the default res1 = co_await submitCommand(device_cmd::SetReportRate{}, 100); assert(std::holds_alternative<std::monostate>(res1)); // setup evdev stuff _evDev->enableEvent(EV_REL, REL_X); _evDev->enableEvent(EV_REL, REL_Y); if (_deviceType.hasScrollWheel) _evDev->enableEvent(EV_REL, REL_WHEEL); _evDev->enableEvent(EV_KEY, BTN_LEFT); _evDev->enableEvent(EV_KEY, BTN_RIGHT); _evDev->enableEvent(EV_KEY, BTN_MIDDLE); if (_deviceType.has5Buttons) { _evDev->enableEvent(EV_KEY, BTN_SIDE); _evDev->enableEvent(EV_KEY, BTN_EXTRA); } // Create an mbus object for the partition. auto root = co_await mbus::Instance::global().getRoot(); mbus::Properties descriptor{ {"unix.subsystem", mbus::StringItem{"input"}} }; auto handler = mbus::ObjectHandler{} .withBind([=] () -> async::result<helix::UniqueDescriptor> { helix::UniqueLane local_lane, remote_lane; std::tie(local_lane, remote_lane) = helix::createStream(); libevbackend::serveDevice(_evDev, std::move(local_lane)); async::promise<helix::UniqueDescriptor> promise; promise.set_value(std::move(remote_lane)); return promise.async_get(); }); co_await root.createObject("ps2mouse", descriptor, std::move(handler)); runMouse(); } async::detached Controller::Device::runMouse() { while (true) { uint8_t byte0, byte1, byte2, byte3 = 0; byte0 = (co_await recvByte()).value(); byte1 = (co_await recvByte()).value(); byte2 = (co_await recvByte()).value(); if (_deviceType.has5Buttons || _deviceType.hasScrollWheel) byte3 = (co_await recvByte()).value(); int movement_x = (int)byte1 - (int)((byte0 << 4) & 0x100); int movement_y = (int)byte2 - (int)((byte0 << 3) & 0x100); int movement_wheel = 0; if (_deviceType.hasScrollWheel) { movement_wheel = (int)(byte3 & 0x7) - (int)(byte3 & 0x8); } if (!(byte0 & 8)) { printf("ps2-hid: desync? first byte is %02x\n", byte0); continue; } if (byte0 & 0xC0) { printf("ps2-hid: overflow\n"); continue; } if(logMouse) { printf("ps2-hid: mouse packet dump:\n"); printf("ps2-hid: x move: %d, y move: %d, z move: %d\n", movement_x, movement_y, movement_wheel); printf("ps2-hid: left: %d, right: %d, middle: %d\n", (byte0 & 1) > 0, (byte0 & 2) > 0, (byte0 & 4)); printf("ps2-hid: 4th: %d, 5th: %d\n", (byte3 & 4) > 0, (byte3 & 5) > 0); } _evDev->emitEvent(EV_REL, REL_X, byte1 ? movement_x : 0); _evDev->emitEvent(EV_REL, REL_Y, byte2 ? -movement_y : 0); if (_deviceType.hasScrollWheel) { _evDev->emitEvent(EV_REL, REL_WHEEL, -movement_wheel); } _evDev->emitEvent(EV_KEY, BTN_LEFT, byte0 & 1); _evDev->emitEvent(EV_KEY, BTN_RIGHT, byte0 & 2); _evDev->emitEvent(EV_KEY, BTN_MIDDLE, byte0 & 4); if (_deviceType.has5Buttons) { _evDev->emitEvent(EV_KEY, BTN_SIDE, byte3 & 4); _evDev->emitEvent(EV_KEY, BTN_EXTRA, byte3 & 5); } _evDev->emitEvent(EV_SYN, SYN_REPORT, 0); _evDev->notify(); } } int scanNormal(uint8_t data) { switch (data) { case 0x01: return KEY_ESC; case 0x02: return KEY_1; case 0x03: return KEY_2; case 0x04: return KEY_3; case 0x05: return KEY_4; case 0x06: return KEY_5; case 0x07: return KEY_6; case 0x08: return KEY_7; case 0x09: return KEY_8; case 0x0A: return KEY_9; case 0x0B: return KEY_0; case 0x0C: return KEY_MINUS; case 0x0D: return KEY_EQUAL; case 0x0E: return KEY_BACKSPACE; case 0x0F: return KEY_TAB; case 0x10: return KEY_Q; case 0x11: return KEY_W; case 0x12: return KEY_E; case 0x13: return KEY_R; case 0x14: return KEY_T; case 0x15: return KEY_Y; case 0x16: return KEY_U; case 0x17: return KEY_I; case 0x18: return KEY_O; case 0x19: return KEY_P; case 0x1A: return KEY_LEFTBRACE; case 0x1B: return KEY_RIGHTBRACE; case 0x1C: return KEY_ENTER; case 0x1D: return KEY_LEFTCTRL; case 0x1E: return KEY_A; case 0x1F: return KEY_S; case 0x20: return KEY_D; case 0x21: return KEY_F; case 0x22: return KEY_G; case 0x23: return KEY_H; case 0x24: return KEY_J; case 0x25: return KEY_K; case 0x26: return KEY_L; case 0x27: return KEY_SEMICOLON; case 0x28: return KEY_APOSTROPHE; case 0x29: return KEY_GRAVE; case 0x2A: return KEY_LEFTSHIFT; case 0x2B: return KEY_BACKSLASH; case 0x2C: return KEY_Z; case 0x2D: return KEY_X; case 0x2E: return KEY_C; case 0x2F: return KEY_V; case 0x30: return KEY_B; case 0x31: return KEY_N; case 0x32: return KEY_M; case 0x33: return KEY_COMMA; case 0x34: return KEY_DOT; case 0x35: return KEY_SLASH; case 0x36: return KEY_RIGHTSHIFT; case 0x37: return KEY_KPASTERISK; case 0x38: return KEY_LEFTALT; case 0x39: return KEY_SPACE; case 0x3A: return KEY_CAPSLOCK; case 0x3B: return KEY_F1; case 0x3C: return KEY_F2; case 0x3D: return KEY_F3; case 0x3E: return KEY_F4; case 0x3F: return KEY_F5; case 0x40: return KEY_F6; case 0x41: return KEY_F7; case 0x42: return KEY_F8; case 0x43: return KEY_F9; case 0x44: return KEY_F10; case 0x45: return KEY_NUMLOCK; case 0x46: return KEY_SCROLLLOCK; case 0x47: return KEY_KP7; case 0x48: return KEY_KP8; case 0x49: return KEY_KP9; case 0x4A: return KEY_KPMINUS; case 0x4B: return KEY_KP4; case 0x4C: return KEY_KP5; case 0x4D: return KEY_KP6; case 0x4E: return KEY_KPPLUS; case 0x4F: return KEY_KP1; case 0x50: return KEY_KP2; case 0x51: return KEY_KP3; case 0x52: return KEY_KP0; case 0x53: return KEY_KPDOT; case 0x57: return KEY_F11; case 0x58: return KEY_F12; default: return KEY_RESERVED; } } int scanE0(uint8_t data) { switch (data) { case 0x1C: return KEY_KPENTER; case 0x1D: return KEY_RIGHTCTRL; case 0x35: return KEY_KPSLASH; case 0x37: return KEY_SYSRQ; case 0x38: return KEY_RIGHTALT; case 0x47: return KEY_HOME; case 0x48: return KEY_UP; case 0x49: return KEY_PAGEUP; case 0x4B: return KEY_LEFT; case 0x4D: return KEY_RIGHT; case 0x4F: return KEY_END; case 0x50: return KEY_DOWN; case 0x51: return KEY_PAGEDOWN; case 0x52: return KEY_INSERT; case 0x53: return KEY_DELETE; case 0x5B: return KEY_LEFTMETA; case 0x5C: return KEY_RIGHTMETA; case 0x5D: return KEY_COMPOSE; default: return KEY_RESERVED; } } int scanE1(uint8_t data1, uint8_t data2) { if ((data1 & 0x7F) == 0x1D && (data2 & 0x7F) == 0x45) { return KEY_PAUSE; } else { return KEY_RESERVED; } } async::detached Controller::Device::runKbd() { while (true) { int key = -1; bool pressed = false; uint8_t byte0, byte1, byte2; byte0 = (co_await recvByte()).value(); if (byte0 == 0xE0) { byte1 = (co_await recvByte()).value(); key = scanE0(byte1 & 0x7F); pressed = !(byte1 & 0x80); } else if (byte0 == 0xE1) { byte1 = (co_await recvByte()).value(); byte2 = (co_await recvByte()).value(); key = scanE1(byte1, byte2); pressed = !(byte1 & 0x80); assert((byte1 & 0x80) == (byte2 & 0x80)); } else { key = scanNormal(byte0 & 0x7F); pressed = !(byte0 & 0x80); } _evDev->emitEvent(EV_KEY, key, pressed); _evDev->emitEvent(EV_SYN, SYN_REPORT, 0); _evDev->notify(); } } void Controller::Device::pushByte(uint8_t byte) { if (_awaitingResponse) { _responseQueue.put(byte); } else { _reportQueue.put(byte); } } static Controller::Device::DeviceType determineTypeById(uint16_t id) { if (id == 0) return Controller::Device::DeviceType{.mouse = true}; if (id == 0x3) return Controller::Device::DeviceType{.mouse = true, .hasScrollWheel = true}; if (id == 0x4) return Controller::Device::DeviceType{.mouse = true, .has5Buttons = true}; if (id == 0xAB41 || id == 0xABC1 || id == 0xAB83) return Controller::Device::DeviceType{.keyboard = true}; printf("ps2-hid: unknown device id %04x, please submit a bug report\n", id); return Controller::Device::DeviceType{}; // we assume nothing } async::result<std::variant<NoDevice, Controller::Device::DeviceType>> Controller::Device::submitCommand(device_cmd::Identify tag) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF2) == std::nullopt) co_return NoDevice{}; auto resp2 = co_await recvByte(default_timeout); auto resp3 = co_await recvByte(default_timeout); if (resp2 == std::nullopt && resp3 == std::nullopt) { // ancient AT keyboard co_return DeviceType{.keyboard = true}; } if ((resp2 != std::nullopt) ^ (resp3 != std::nullopt)) { uint16_t v = resp2 != std::nullopt ? resp2.value() : resp3.value(); co_return determineTypeById(v); } uint16_t a = resp2.value(); uint16_t b = resp3.value(); uint16_t v = a << 8 | b; co_return determineTypeById(v); } async::result<std::variant<NoDevice, std::monostate>> Controller::Device::submitCommand(device_cmd::DisableScan tag) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF5) == std::nullopt) co_return NoDevice{}; co_return std::monostate{}; } async::result<std::variant<NoDevice, std::monostate>> Controller::Device::submitCommand(device_cmd::EnableScan tag) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF4) == std::nullopt) co_return NoDevice{}; co_return std::monostate{}; } async::result<std::variant<NoDevice, std::monostate>> Controller::Device::submitCommand(device_cmd::SetReportRate tag, int rate) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF3) == std::nullopt) co_return NoDevice{}; if (co_await transferByte(rate) == std::nullopt) co_return NoDevice{}; co_return std::monostate{}; } async::result<std::variant<NoDevice, std::monostate>> Controller::Device::submitCommand(device_cmd::SetScancodeSet tag, int set) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF0) == std::nullopt) co_return NoDevice{}; if (co_await transferByte(set) == std::nullopt) co_return NoDevice{}; co_return std::monostate{}; } async::result<std::variant<NoDevice, int>> Controller::Device::submitCommand(device_cmd::GetScancodeSet tag) { _awaitingResponse = true; FlagGuard g{_awaitingResponse, false}; if (co_await transferByte(0xF0) == std::nullopt) co_return NoDevice{}; if (co_await transferByte(0) == std::nullopt) co_return NoDevice{}; auto set = co_await recvByte(default_timeout); assert(set != std::nullopt); co_return set.value(); } void Controller::Device::sendByte(uint8_t byte) { if (_port == 1) { _controller->submitCommand(controller_cmd::SendBytePort2{}); } while (_controller->_space.load(kbd_register::status) & status_bits::inBufferStatus) ; // wait for the buffer to become empty _controller->_space.store(kbd_register::data, byte); } async::result<std::optional<uint8_t>> Controller::Device::transferByte(uint8_t byte) { while (true) { sendByte(byte); auto resp = co_await recvByte(default_timeout); if (auto v = resp.value_or(0); v != 0xFE) co_return resp; } } async::result<std::optional<uint8_t>> Controller::Device::recvByte(uint64_t timeout) { if (timeout) { async::cancellation_event ev; helix::TimeoutCancellation timer{timeout, ev}; auto result = _awaitingResponse ? co_await _responseQueue.async_get(ev) : co_await _reportQueue.async_get(ev); co_await timer.retire(); co_return result; } else { if (_awaitingResponse) co_return co_await _responseQueue.async_get(); else co_return co_await _reportQueue.async_get(); } } bool Controller::Device::exists() { return _exists; } Controller *_controller; int main() { std::cout << "ps2-hid: Starting driver" << std::endl; _controller = new Controller; { async::queue_scope scope{helix::globalQueue()}; _controller->init(); } async::run_forever(helix::globalQueue()->run_token(), helix::currentDispatcher); return 0; }
28.799496
131
0.709651
Apache-HB
086c237384091d5ab91c5fe608aba137658e9740
1,858
cc
C++
xls/codegen/codegen_options.cc
cdleary/xls
9989a97091e29b58ef4425e76ffc8b55025c5f55
[ "Apache-2.0" ]
1
2021-06-29T17:37:28.000Z
2021-06-29T17:37:28.000Z
xls/codegen/codegen_options.cc
cdleary/xls
9989a97091e29b58ef4425e76ffc8b55025c5f55
[ "Apache-2.0" ]
null
null
null
xls/codegen/codegen_options.cc
cdleary/xls
9989a97091e29b58ef4425e76ffc8b55025c5f55
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The XLS 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. #include "xls/codegen/codegen_options.h" #include "xls/common/proto_adaptor_utils.h" namespace xls::verilog { CodegenOptions& CodegenOptions::entry(absl::string_view name) { entry_ = name; return *this; } CodegenOptions& CodegenOptions::module_name(absl::string_view name) { module_name_ = name; return *this; } CodegenOptions& CodegenOptions::reset(absl::string_view name, bool asynchronous, bool active_low) { reset_proto_ = ResetProto(); reset_proto_->set_name(ToProtoString(name)); reset_proto_->set_asynchronous(asynchronous); reset_proto_->set_active_low(active_low); return *this; } CodegenOptions& CodegenOptions::clock_name(absl::string_view clock_name) { clock_name_ = std::move(clock_name); return *this; } CodegenOptions& CodegenOptions::use_system_verilog(bool value) { use_system_verilog_ = value; return *this; } CodegenOptions& CodegenOptions::flop_inputs(bool value) { flop_inputs_ = value; return *this; } CodegenOptions& CodegenOptions::flop_outputs(bool value) { flop_outputs_ = value; return *this; } CodegenOptions& CodegenOptions::assert_format(absl::string_view value) { assert_format_ = std::string{value}; return *this; } } // namespace xls::verilog
28.151515
80
0.738967
cdleary
086c67dd5ab45dcbb7f8b16301eb120e17d7a6b1
73
cpp
C++
src/Devices/A4963/A4963RegisterInfo.cpp
SetZero/A4963
4983ceb36fa605e32f53d816d5f98a8f522192b1
[ "MIT" ]
null
null
null
src/Devices/A4963/A4963RegisterInfo.cpp
SetZero/A4963
4983ceb36fa605e32f53d816d5f98a8f522192b1
[ "MIT" ]
5
2018-09-18T23:04:43.000Z
2018-10-19T20:59:44.000Z
src/Devices/A4963/A4963RegisterInfo.cpp
SetZero/A4963
4983ceb36fa605e32f53d816d5f98a8f522192b1
[ "MIT" ]
null
null
null
// // Created by sebastian on 03.10.18. // #include "A4963RegisterInfo.h"
18.25
36
0.69863
SetZero
086ea28a347a5dcf536b720dcd1b334d96a12a70
8,293
cpp
C++
32blit/graphics/blend.cpp
mikerr/32blit-beta
38ceca02226ec405d2de6883fc75376242a61778
[ "MIT" ]
null
null
null
32blit/graphics/blend.cpp
mikerr/32blit-beta
38ceca02226ec405d2de6883fc75376242a61778
[ "MIT" ]
null
null
null
32blit/graphics/blend.cpp
mikerr/32blit-beta
38ceca02226ec405d2de6883fc75376242a61778
[ "MIT" ]
null
null
null
#include <cstdint> #include <cstring> #include "surface.hpp" #ifdef WIN32 #define __attribute__(A) #endif // note: // for performance reasons none of the blending functions make any attempt // to validate input, adhere to clipping, or source/destination bounds. it // is assumed that all validation has been done by the caller. namespace blit { __attribute__((always_inline)) inline uint32_t alpha(const uint32_t &a1, const uint32_t &a2) { return ((a1 + 1) * (a2 + 1)) >> 8; } __attribute__((always_inline)) inline uint32_t alpha(const uint32_t &a1, const uint32_t &a2, const uint32_t &a3) { return ((a1 + 1) * (a2 + 1) * (a3 + 1)) >> 16; } __attribute__((always_inline)) inline uint8_t blend(const uint8_t &s, const uint8_t &d, const uint8_t &a) { return d + ((a * (s - d) + 127) >> 8); } __attribute__((always_inline)) inline void blend_rgba_rgb(const Pen *s, uint8_t *d, const uint8_t &a, uint32_t c) { if (c == 1) { // fast case for single pixel draw *d = blend(s->r, *d, a); d++; *d = blend(s->g, *d, a); d++; *d = blend(s->b, *d, a); d++; return; } if (c <= 4) { // fast case for small number of pixels while (c--) { *d = blend(s->r, *d, a); d++; *d = blend(s->g, *d, a); d++; *d = blend(s->b, *d, a); d++; } return; } // create packed 32bit source // s32 now contains RGBA uint32_t s32 = *((uint32_t*)(s)); // replace A with R so s32 is now RGBR s32 = (s32 & 0x00ffffff) | ((s32 & 0x000000ff) << 24); // if destination is not double-word aligned copy at most three bytes until it is uint8_t* de = d + c * 3; while (uintptr_t(d) & 0b11) { *d = blend((s32 & 0xff), *d, a); d++; // rotate the aligned rgbr/gbrg/brgb quad s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24; } // destination is now double-word aligned if (d < de) { // get a double-word aligned pointer to the destination surface uint32_t *d32 = (uint32_t*)d; // copy four bytes at a time until we have fewer than four bytes remaining uint32_t c32 = uint32_t(de - d) >> 2; while (c32--) { uint32_t dd32 = *d32; *d32++ = blend((s32 & 0xff), (dd32 & 0xff), a) | (blend((s32 & 0xff00) >> 8, (dd32 & 0xff00) >> 8, a) << 8) | (blend((s32 & 0xff0000) >> 16, (dd32 & 0xff0000) >> 16, a) << 16) | (blend((s32 & 0xff000000) >> 24, (dd32 & 0xff000000) >> 24, a) << 24); // rotate the aligned rgbr/gbrg/brgb quad s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24; } // copy the trailing bytes as needed d = (uint8_t*)d32; while (d < de) { *d = blend((s32 & 0xff), *d, a); s32 >>= 8; d++; } } } __attribute__((always_inline)) inline void copy_rgba_rgb(const Pen* s, uint8_t *d, uint32_t c) { if (c == 1) { // fast case for single pixel draw *(d + 0) = s->r; *(d + 1) = s->g; *(d + 2) = s->b; return; } if (c <= 4) { // fast case for small number of pixels do { *(d + 0) = s->r; *(d + 1) = s->g; *(d + 2) = s->b; d += 3; } while (--c); return; } // create packed 32bit source // s32 now contains RGBA uint32_t s32 = *((uint32_t*)(s)); // replace A with R so s32 is now RGBR s32 = (s32 & 0x00ffffff) | ((s32 & 0x000000ff) << 24); // if destination is not double-word aligned copy at most three bytes until it is uint8_t* de = d + c * 3; while (uintptr_t(d) & 0b11) { *d = s32 & 0xff; d++; // rotate the aligned rgbr/gbrg/brgb quad s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24; } // destination is now double-word aligned if (d < de) { // get a double-word aligned pointer to the destination surface uint32_t *d32 = (uint32_t*)d; // copy four bytes at a time until we have fewer than four bytes remaining uint32_t c32 = uint32_t(de - d) >> 2; while (c32--) { *d32++ = s32; // rotate the aligned rgbr/gbrg/brgb quad s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24; } // copy the trailing bytes as needed d = (uint8_t*)d32; while (d < de) { *d = (s32 & 0xff); s32 >>= 8; d++; } } } void RGBA_RGBA(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) { uint8_t* d = dest->data + (off * 4); uint8_t* m = dest->mask ? dest->mask->data + off : nullptr; uint16_t a1 = alpha(pen->a, dest->alpha); do { uint16_t a = m ? alpha(a1, *m++) : a1; if (a >= 255) { *d++ = pen->r; *d++ = pen->g; *d++ = pen->b; *d++ = 255; } else if (a > 0) { *d = blend(pen->r, *d, a); d++; *d = blend(pen->g, *d, a); d++; *d = blend(pen->b, *d, a); d++; *d = blend(pen->a, *d, a); d++; }else{ d += 4; } } while (--cnt); } void RGBA_RGB(const Pen* pen, const Surface* dest, uint32_t off, uint32_t c) { uint8_t* d = dest->data + (off * 3); uint8_t* m = dest->mask ? dest->mask->data + off : nullptr; uint16_t a = alpha(pen->a, dest->alpha); if (!m) { // no mask if (a >= 255) { // no alpha, just copy copy_rgba_rgb(pen, d, c); } else { // alpha, blend blend_rgba_rgb(pen, d, a, c); } } else { // mask enabled, slow blend do { uint16_t ma = alpha(a, *m++); blend_rgba_rgb(pen, d, ma, 1); d += 3; } while (--c); } } void P_P(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) { uint8_t* d = dest->data + off; do { if (pen->a != 0) { *d = pen->a; } d++; } while (--cnt); } void M_M(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) { uint8_t* d = dest->data + off; do { *d = blend(pen->a, *d, dest->alpha); d++; } while (--cnt); } void RGBA_RGBA(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) { uint8_t* s = src->palette ? src->data + soff : src->data + (soff * 4); uint8_t* d = dest->data + (doff * 3); uint8_t* m = dest->mask ? dest->mask->data + doff : nullptr; do { Pen *pen = src->palette ? &src->palette[*s] : (Pen *)s; uint16_t a = m ? alpha(pen->a, *m++, dest->alpha) : alpha(pen->a, dest->alpha); if (a >= 255) { *d++ = pen->r; *d++ = pen->g; *d++ = pen->b; d++; } else if (a > 0) { *d = blend(pen->r, *d, a); d++; *d = blend(pen->g, *d, a); d++; *d = blend(pen->b, *d, a); d++; *d = blend(pen->b, *d, a); d++; }else{ d += 4; } s += (src->palette ? 1 : 4) * src_step; } while (--cnt); } void RGBA_RGB(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) { uint8_t* s = src->palette ? src->data + soff : src->data + (soff * 4); uint8_t* d = dest->data + (doff * 3); uint8_t* m = dest->mask ? dest->mask->data + doff : nullptr; do { Pen *pen = src->palette ? &src->palette[*s] : (Pen *)s; uint16_t a = m ? alpha(pen->a, *m++, dest->alpha) : alpha(pen->a, dest->alpha); if (a >= 255) { *d++ = pen->r; *d++ = pen->g; *d++ = pen->b; } else if (a > 0) { *d = blend(pen->r, *d, a); d++; *d = blend(pen->g, *d, a); d++; *d = blend(pen->b, *d, a); d++; }else{ d += 3; } s += (src->palette ? 1 : 4) * src_step; } while (--cnt); } void P_P(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) { uint8_t *s = src->data + soff; uint8_t *d = dest->data + doff; do { if (*s != 0) { *d = *s; } d++; s += src_step; } while (--cnt); } void M_M(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) { uint8_t *s = src->data + soff; uint8_t *d = dest->data + doff; do { *d = blend(*s, *d, dest->alpha); d++; s += src_step; } while (--cnt); } }
30.156364
123
0.503798
mikerr
086f58ca69e3f3dfbf81b52233b5c0abac904053
2,428
hh
C++
include/sea_dsa/Cloner.hh
igcontreras/sea-dsa
19dae890dc482c10832a9cf604e0f9847a7ac57d
[ "BSD-3-Clause" ]
120
2017-07-10T19:03:55.000Z
2022-03-27T05:54:16.000Z
include/sea_dsa/Cloner.hh
igcontreras/sea-dsa
19dae890dc482c10832a9cf604e0f9847a7ac57d
[ "BSD-3-Clause" ]
90
2017-07-03T01:17:07.000Z
2022-03-28T22:37:30.000Z
include/sea_dsa/Cloner.hh
igcontreras/sea-dsa
19dae890dc482c10832a9cf604e0f9847a7ac57d
[ "BSD-3-Clause" ]
34
2017-12-22T15:10:42.000Z
2021-12-24T02:24:05.000Z
#pragma once #include "sea_dsa/Graph.hh" namespace sea_dsa { struct CloningContext { llvm::Optional<const llvm::Instruction *> m_cs; enum DirectionKind { Unset, BottomUp, TopDown }; DirectionKind m_dir; CloningContext(const llvm::Instruction &cs, DirectionKind dir) : m_cs(&cs), m_dir(dir) {} static CloningContext mkNoContext() { return {}; } private: CloningContext() : m_cs(llvm::None), m_dir(DirectionKind::Unset) {} }; /** * \brief Recursively clone DSA sub-graph rooted at a given Node */ class Cloner { public: enum Options : unsigned { Basic = 0, StripAllocas = 1 << 0, TrackAllocaCallPaths = 1 << 1, }; template <typename... Os> static Options BuildOptions(Os... os) { Options options = Basic; Options unpacked[] = {os...}; for (Options o : unpacked) options = Options(options | o); return options; } Cloner(Graph &g, CloningContext context, Cloner::Options options) : m_graph(g), m_context(context), m_strip_allocas(options & Cloner::Options::StripAllocas) {} /// Returns a clone of a given node in the new graph /// Recursive clones nodes linked by this node as necessary Node &clone(const Node &n, bool forceAddAlloca = false, const llvm::Value *onlyAllocSite = nullptr); /// Returns a cloned node that corresponds to the given node Node &at(const Node &n) { assert(hasNode(n)); auto it = m_map.find(&n); assert(it != m_map.end()); return *(it->second.first); } /// Returns true if the node has already been cloned bool hasNode(const Node &n) { return m_map.count(&n) > 0; } private: enum CachingLevel { SingleAllocSite, NoAllocas, Full }; Graph &m_graph; llvm::DenseMap<const Node *, std::pair<Node *, CachingLevel>> m_map; llvm::DenseMap<const Node *, llvm::SmallDenseSet<Node *, 4>> m_deferredUnify; CloningContext m_context; bool m_strip_allocas; bool isTopDown() const { return m_context.m_dir == CloningContext::TopDown; } bool isBottomUp() const { return m_context.m_dir == CloningContext::BottomUp; } bool isUnset() const { return !(isTopDown() || isBottomUp()); } void copyAllocationSites(const Node &from, Node &to, bool forceAddAlloca, const llvm::Value *onlyAllocSite = nullptr); void importCallPaths(DsaAllocSite &site, llvm::Optional<DsaAllocSite *> other); }; } // namespace sea_dsa
29.975309
79
0.667628
igcontreras
08715a656689a96d283d4314a02e3510aa1041d4
2,059
cpp
C++
ote/Themes/theme.cpp
JuBan1/OpenTextEdit
78543d95887c89824405f610f41f9783e6347f27
[ "MIT" ]
3
2018-02-05T12:47:32.000Z
2021-06-12T00:43:20.000Z
ote/Themes/theme.cpp
JuBan1/OpenTextEdit
78543d95887c89824405f610f41f9783e6347f27
[ "MIT" ]
null
null
null
ote/Themes/theme.cpp
JuBan1/OpenTextEdit
78543d95887c89824405f610f41f9783e6347f27
[ "MIT" ]
1
2021-06-12T05:22:29.000Z
2021-06-12T05:22:29.000Z
#include "theme.h" #include "themedata.h" #include "themedatabase.h" namespace ote { #define CASE(item) case item: return #item; #define IF(item) if(strcmp(elem, #item)==0) return item; const char* Theme::elementToString(Theme::HighlightElements elem) { switch(elem) { CASE(TextEditText) CASE(TextEditActiveText) CASE(TextEditBackground) CASE(TextEditActiveBackground) CASE(GutterText) CASE(GutterActiveText) CASE(GutterBackground) CASE(GutterActiveBackground) CASE(SyntaxComment) CASE(SyntaxString) CASE(SyntaxNumber) CASE(SyntaxConstant) CASE(SyntaxType) CASE(SyntaxKeyword) CASE(SyntaxMatchingBracket) CASE(SyntaxOperator) CASE(SyntaxSymbol) CASE(SyntaxVariable) CASE(SearchHighlight) CASE(MAX_ITEMS) } } Theme::HighlightElements Theme::stringToElement(const char* elem) { IF(TextEditText) IF(TextEditActiveText) IF(TextEditBackground) IF(TextEditActiveBackground) IF(GutterText) IF(GutterActiveText) IF(GutterBackground) IF(GutterActiveBackground) IF(SyntaxComment) IF(SyntaxString) IF(SyntaxNumber) IF(SyntaxConstant) IF(SyntaxType) IF(SyntaxKeyword) IF(SyntaxMatchingBracket) IF(SyntaxOperator) IF(SyntaxSymbol) IF(SyntaxVariable) IF(SearchHighlight) IF(MAX_ITEMS) return MAX_ITEMS; } Theme::HighlightElements Theme::stringToElement(const QString& elem) { return stringToElement(static_cast<const char*>(elem.toLatin1())); } Theme::Theme() : m_data( ThemeDatabase::getTheme("").m_data ) {} Theme::Theme(QString name) : m_data( ThemeDatabase::getTheme(name).m_data ) {} Theme::Theme(ThemeData* data) : m_data(data) {} QString Theme::getName() const { return m_data->getName(); } bool Theme::isDefault() const { return getName().isEmpty(); } QTextCharFormat Theme::getFormat(HighlightElements c) const { return m_data->getFormat(c); } QColor Theme::getColor(HighlightElements c) const { return m_data->getColor(c); } } // namespace ote
21.226804
70
0.708596
JuBan1
0874a8234629c4eb7823aee4226332ec17c30852
3,950
cpp
C++
tools/ad_map_access_qgis_python/src/core_py_log.cpp
fgolemo/map
5af0f99ff781e63ef72192ea714dce295a44298c
[ "MIT" ]
null
null
null
tools/ad_map_access_qgis_python/src/core_py_log.cpp
fgolemo/map
5af0f99ff781e63ef72192ea714dce295a44298c
[ "MIT" ]
null
null
null
tools/ad_map_access_qgis_python/src/core_py_log.cpp
fgolemo/map
5af0f99ff781e63ef72192ea714dce295a44298c
[ "MIT" ]
1
2020-10-27T11:09:30.000Z
2020-10-27T11:09:30.000Z
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (C) 2018-2020 Intel Corporation // // SPDX-License-Identifier: MIT // // ----------------- END LICENSE BLOCK ----------------------------------- #include <string> #include <ad/map/access/Logging.hpp> #include "core_python.h" using ::ad::map::access::getLogger; PyObject *LogDebug(PyObject * /*self*/, PyObject *py_message) { PyErr_Clear(); if (py_message != nullptr) { const char *message = PyString_AsString(py_message); if (message != nullptr && *message != '\0') { getLogger()->debug(message); } else { PyErr_SetString(PyExc_RuntimeError, "Empty Debug message!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Missing Debug message!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogInfo(PyObject * /*self*/, PyObject *py_message) { PyErr_Clear(); if (py_message != nullptr) { const char *message = PyString_AsString(py_message); if (message != nullptr && *message != '\0') { getLogger()->info(message); } else { PyErr_SetString(PyExc_RuntimeError, "Empty Info message!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Missing Info message!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogWarning(PyObject * /*self*/, PyObject *py_message) { PyErr_Clear(); if (py_message != nullptr) { const char *message = PyString_AsString(py_message); if (message != nullptr && *message != '\0') { getLogger()->warn(message); } else { PyErr_SetString(PyExc_RuntimeError, "Empty Warning message!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Missing Warning message!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogError(PyObject * /*self*/, PyObject *py_message) { PyErr_Clear(); if (py_message != nullptr) { const char *message = PyString_AsString(py_message); if (message != nullptr && *message != '\0') { getLogger()->error(message); } else { PyErr_SetString(PyExc_RuntimeError, "Empty Error message!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Missing Error message!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogInternalError(PyObject * /*self*/, PyObject *py_message) { PyErr_Clear(); if (py_message != nullptr) { const char *message = PyString_AsString(py_message); if (message != nullptr && *message != '\0') { getLogger()->critical(message); } else { PyErr_SetString(PyExc_RuntimeError, "Empty Internal Error message!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Missing Internal Error message!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogLevel(PyObject * /*self*/, PyObject *py_level) { PyErr_Clear(); if (py_level != nullptr) { if (PyInt_Check(py_level)) { spdlog::level::level_enum level = static_cast<spdlog::level::level_enum>(PyInt_AsLong(py_level)); if (spdlog::level::trace <= level && level < spdlog::level::off) { getLogger()->set_level(level); } else { PyErr_SetString(PyExc_RuntimeError, "Out-of-range argument to LogLevel()!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Expecting integer argument to LogLevel()!"); } } else { PyErr_SetString(PyExc_RuntimeError, "Expecting integer argument to LogLevel()!"); } if (PyErr_Occurred() != nullptr) { PyErr_Print(); } Py_RETURN_NONE; } PyObject *LogFileName(PyObject * /*self*/, PyObject * /*args*/) { static std::string log_file_name; return PyString_FromString(log_file_name.c_str()); }
21.467391
103
0.612152
fgolemo
087a22be0db7730bf7dba1d4b8f81e5ed859a840
12,364
cc
C++
WinNTKline/KlineUtil/mygl/House.cc
TsyQi/MyAutomatic
2afd3dcabba818051c7119fac7e6c099ff7954a7
[ "Apache-2.0" ]
4
2016-08-19T08:16:49.000Z
2020-04-15T12:30:25.000Z
WinNTKline/KlineUtil/mygl/House.cc
TsyQi/MyAutomatic
2afd3dcabba818051c7119fac7e6c099ff7954a7
[ "Apache-2.0" ]
null
null
null
WinNTKline/KlineUtil/mygl/House.cc
TsyQi/MyAutomatic
2afd3dcabba818051c7119fac7e6c099ff7954a7
[ "Apache-2.0" ]
3
2019-03-23T03:40:24.000Z
2020-04-15T00:57:43.000Z
#include "House.h" extern TEXTURE_2D **TextureList; House::House() { texnum = 0; } // Create an OpenGL rendering context BOOL House::CreateViewGLContext(HDC hDC) { m_hGLContext = wglCreateContext(hDC); if (m_hGLContext == NULL) return FALSE; if (wglMakeCurrent(hDC, m_hGLContext) == FALSE) return FALSE; return TRUE; } void House::InitGeometry(void) { GLfloat fogColor[4] = { 0.75, 0.75, 1.0, 1.0 }; speed = 0; srand(224); srand((unsigned)time(NULL)); // Default mode glPolygonMode(GL_FRONT, GL_FILL); glPolygonMode(GL_BACK, GL_FILL); glShadeModel(GL_FLAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glEnable(GL_DEPTH_TEST); glShadeModel(GL_FLAT); glFogi(GL_FOG_MODE, GL_LINEAR); glFogfv(GL_FOG_COLOR, fogColor); glFogf(GL_FOG_DENSITY, 0.8f); glFogf(GL_FOG_START, 400.0f); glFogf(GL_FOG_END, 500.0f); glClearColor(0.75f, 0.75f, 1.0f, 1.0f); // light must be disabled // while rendering the terrain // because it has no normal definition glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); } // Function that moves the eye or turns the angle of sight. // Updates scene if update != 0. void House::MoveEye(int type, GLfloat amount, int update) { GLfloat a; switch (type) { case FORWARD: a = sqrt((cx - ex)*(cx - ex) + (cz - ez)*(cz - ez)); ex = (amount*(cx - ex) + a * ex) / a; ez = (amount*(cz - ez) + a * ez) / a; cx = (amount*(cx - ex) + a * cx) / a; cz = (amount*(cz - ez) + a * cz) / a; break; case MOVELR: a = sqrt((cx - ex)*(cx - ex) + (cy - ey)*(cy - ey)); ex = (amount*(cx - ex) + a * ex) / a; ey = (amount*(cy - ey) + a * ey) / a; cx = (amount*(cx - ex) + a * cx) / a; cy = (amount*(cy - ey) + a * cy) / a; case TURNLEFT: cx = (cx - ex)*(float)cos(amount / 360.0f) + (cz - ez)*(float)sin(amount / 360.0f) + ex; cz = (cz - ez)*(float)cos(amount / 360.0f) - (cx - ex)*(float)sin(amount / 360.0f) + ez; break; case UPDOWN: ey += amount; break; case LOOKUP: cy += amount; break; case DEFAULT: glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break; } if (update) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz); } } void House::ReadData() { int i; unsigned j, l; FILE *fp; char stemp[100]; POINT3D *plist; INT4U nAllVertexNum; INT4U *pchlist; strcpy_s(gEnergyFile, "data/ROOM.ED"); fopen_s(&fp, gEnergyFile, "r"); if (fp == NULL) { printf("\n Can not open energy data file:%s\n", gEnergyFile); exit(0); } fseek(fp, 0, SEEK_SET); /****** read texture list ******/ fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "texnum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%d", &texnum); TextureList = (TEXTURE_2D **)malloc(sizeof(TEXTURE_2D)*(texnum + 1)); for (i = 1; i <= texnum; i++) { TextureList[i] = (TEXTURE_2D *)malloc(sizeof(TEXTURE_2D)); fscanf_s(fp, "%s%s", TextureList[i]->fname, sizeof(TextureList[i]->fname), stemp, sizeof(stemp)); if (strcmp(stemp, "REPEAT_TEXTURE") == 0) TextureList[i]->type = 1; else if (strcmp(stemp, "CLAMP_TEXTURE") == 0) TextureList[i]->type = 0; } /****** Read object list ******/ fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "ObjectNum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%ld", &ObjectNum); ObjectList = (OBJECT *)malloc(sizeof(OBJECT) * ObjectNum); for (i = 0; i < ObjectNum; i++) { fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "SurfaceNum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%ld", &(ObjectList[i].SurfNum)); ObjectList[i].surflist = (SURFACE *)malloc(sizeof(SURFACE) * ObjectList[i].SurfNum); for (j = 0; j < ObjectList[i].SurfNum; j++) { /****** Read surface infor ******/ fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "TextureId") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].texId)); fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "pointnum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].pointn)); fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "triangle") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].triangle)); fscanf_s(fp, "%s", stemp, sizeof(stemp)); while (strcmp(stemp, "quadrangle") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp)); fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].quadric)); /****** Read point list ******/ ObjectList[i].surflist[j].pointlist = (POINT3D*)malloc(sizeof(POINT3D) * ObjectList[i].surflist[j].pointn); plist = ObjectList[i].surflist[j].pointlist; for (l = 0; l < ObjectList[i].surflist[j].pointn; l++) fscanf_s(fp, "%f%f%f%f%f%f%f%f", &(plist[l].r), &(plist[l].g), &(plist[l].b), &(plist[l].u), &(plist[l].v), &(plist[l].x), &(plist[l].y), &(plist[l].z)); /****** Read patchlist ******/ nAllVertexNum = ObjectList[i].surflist[j].triangle * 3 + ObjectList[i].surflist[j].quadric * 4; ObjectList[i].surflist[j].patchlist = (INT4U *)malloc(sizeof(INT4U) * nAllVertexNum); pchlist = ObjectList[i].surflist[j].patchlist; for (l = 0; l < nAllVertexNum; l++) fscanf_s(fp, "%ld", &(pchlist[l])); } } fclose(fp); } void House::InitLookAt() { FILE *fp; strcpy_s(sLookAtFN, "data/ROOM.LK"); fopen_s(&fp, sLookAtFN, "rb"); if (fp == NULL) { ex = ey = ez = 1.0f; cx = cy = cz = 0.0f; Near = 0.1f; angle = 30.0f; } else fscanf_s(fp, "%f%f%f%f%f%f%f%f", &angle, &Near, &ex, &ey, &ez, &cx, &cy, &cz); fclose(fp); } void House::InitRenderWin() { glShadeModel(GL_SMOOTH); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluPerspective(angle, (float)Width / (float)Height, Near, 1000000000.0); gluLookAt(ex, ey, ez, cx, cy, cz, 0.0, 1.0, 0.0); } void House::Render(void) { int i; unsigned j, k, l, m, TexIndex; POINT3D *plist; INT4U *pchlist; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ACCUM_BUFFER_BIT); for (i = 0; i < ObjectNum; i++) for (j = 0; j < ObjectList[i].SurfNum; j++) { TexIndex = ObjectList[i].surflist[j].texId; if (TexIndex > 0) InitTex(TexIndex); plist = ObjectList[i].surflist[j].pointlist; pchlist = ObjectList[i].surflist[j].patchlist; l = 0; for (k = 0; k < ObjectList[i].surflist[j].triangle; k++) { glBegin(GL_TRIANGLES); for (m = 0; m < 3; m++) { glColor3f(plist[pchlist[l]].r, plist[pchlist[l]].g, plist[pchlist[l]].b); glTexCoord2f(plist[pchlist[l]].u, plist[pchlist[l]].v); glVertex3f(plist[pchlist[l]].x, plist[pchlist[l]].y, plist[pchlist[l]].z); l++; }/* m */ glEnd(); }/* k */ for (k = 0; k < ObjectList[i].surflist[j].quadric; k++) { glBegin(GL_QUADS); for (m = 0; m < 4; m++) { glColor3f(plist[pchlist[l]].r, plist[pchlist[l]].g, plist[pchlist[l]].b); glTexCoord2f(plist[pchlist[l]].u, plist[pchlist[l]].v); glVertex3f(plist[pchlist[l]].x, plist[pchlist[l]].y, plist[pchlist[l]].z); l++; }/* m */ glEnd(); }/* k */ glFlush(); KillTex(); } } void House::CleanList() { int i; unsigned j; for (i = 0; i < ObjectNum; i++) { for (j = 0; j < ObjectList[i].SurfNum; j++) { free(ObjectList[i].surflist[j].pointlist); free(ObjectList[i].surflist[j].patchlist); } free(ObjectList[i].surflist); } free(ObjectList); for (i = 1; i <= texnum; i++) free(TextureList[i]); free(TextureList); } /********************************/ /* function : OpenTexImage */ /********************************/ unsigned char *House::OpenTexImage(INT2U TexIndex, INT2U *rslx, INT2U *rsly) { unsigned char *image; FILE *fp; INT2U srcx, srcy; INT4U i, j; char ImageName[30]; unsigned char *SImageData; int width, height; strcpy_s(ImageName, TextureList[TexIndex]->fname); /* load a image */ fopen_s(&fp, ImageName, "rb"); if (!fp) return 0; fseek(fp, 18L, 0); fread(&width, sizeof(long), 1, fp); fread(&height, sizeof(long), 1, fp); *rslx = srcx = width; *rsly = srcy = height; fseek(fp, 54L, 0); image = (unsigned char *)malloc(width*height * 3); fread(image, width*height * 3, 1, fp); fclose(fp); SImageData = (unsigned char *)malloc(srcx*srcy * 3); for (i = 0; i < srcx; i++) { for (j = 0; j < srcy; j++) { (unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 0) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 2); (unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 1) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 1); (unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 2) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 0); } } free(image); printf("%s : %ld=%ld\n", ImageName, srcx*srcy * 3, (long)(i*j * 3)); return(SImageData); } /********************************/ /* function : InitTex */ /********************************/ void House::InitTex(int TexIndex) { INT2U TextType; unsigned char *ImageData; static int OldIndex = -1; if (TexIndex <= 0) return; if (TexIndex == OldIndex) { glEnable(GL_TEXTURE_2D); return; } ImageData = ImageDatas[TexIndex - 1]; TextType = TextureList[TexIndex]->type; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); if (TextType == CLAMP_TEXTURE) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexImage2D(GL_TEXTURE_2D, 0, 3, rslxs[TexIndex - 1], rslys[TexIndex - 1], 0, GL_RGB, GL_UNSIGNED_BYTE, ImageData); glEnable(GL_TEXTURE_2D); OldIndex = TexIndex; } /********************************/ /* function : KillTex */ /********************************/ void House::KillTex() { glDisable(GL_TEXTURE_2D); } void House::LoadAllTexture() { int i; for (i = 0; i < texnum; i++) ImageDatas[i] = OpenTexImage(i + 1, &rslxs[i], &rslys[i]); } void House::CleanAllTexture() { for (int i = 0; i < texnum; i++) free(ImageDatas[i]); } House::~House() { } #ifdef __error //ws2tcpip.h 'Error' redefined. #undef __error #endif
30.082725
121
0.518036
TsyQi
087ebbf1a91982efd55f2e7e451c97406b6f259a
15,686
cpp
C++
models/lnd/clm/src/iac/giac/gcam/cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp
E3SM-Project/iESM
2a1013a3d85a11d935f1b2a8187a8bbcd75d115d
[ "BSD-3-Clause-LBNL" ]
9
2018-05-15T02:10:40.000Z
2020-01-10T18:27:31.000Z
models/lnd/clm/src/iac/giac/gcam/cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp
zhangyue292/iESM
2a1013a3d85a11d935f1b2a8187a8bbcd75d115d
[ "BSD-3-Clause-LBNL" ]
3
2018-10-12T18:41:56.000Z
2019-11-12T15:18:49.000Z
models/lnd/clm/src/iac/giac/gcam/cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp
zhangyue292/iESM
2a1013a3d85a11d935f1b2a8187a8bbcd75d115d
[ "BSD-3-Clause-LBNL" ]
3
2018-05-15T02:10:33.000Z
2021-04-06T17:45:49.000Z
/* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file calibrate_share_weight_visitor.cpp * \ingroup Objects * \brief The CalibrateShareWeightVisitor class source file. * \author Pralit Patel */ #include "util/base/include/definitions.h" #include <cassert> #include "util/base/include/calibrate_share_weight_visitor.h" #include "technologies/include/technology_container.h" #include "technologies/include/itechnology.h" #include "sectors/include/subsector.h" #include "sectors/include/sector.h" #include "containers/include/gdp.h" #include "util/logger/include/ilogger.h" // includes for detailed buildings calibration #include "technologies/include/building_generic_dmd_technology.h" #include "sectors/include/sector_utils.h" #include "marketplace/include/marketplace.h" #include "containers/include/scenario.h" #include "containers/include/iinfo.h" #include "functions/include/iinput.h" using namespace std; extern Scenario* scenario; /*! * \brief Constructor * \param aRegionName Name of the region if starting the visiting below the * region level. */ CalibrateShareWeightVisitor::CalibrateShareWeightVisitor( const string& aRegionName, const GDP* aGDP ) :mCurrentRegionName( aRegionName ), mGDP( aGDP ) { } void CalibrateShareWeightVisitor::startVisitSector( const Sector* aSector, const int aPeriod ) { mCurrentSectorName = aSector->getName(); } void CalibrateShareWeightVisitor::endVisitSector( const Sector* aSector, const int aPeriod ) { // Doing subsector calibration in sector rather than in subsector because we will need access // to all of the subsectors at the same time. Also we need to do this in end visit sector // because the subsector can't be calculated until we have gotten the correct share weights // for the technologies. // Find out if we need to do calibration, make sure we do not have a mix of calibrated/non-calibrated // subsectors, and figure out the largest subsector to make the other subsectors anchored by it. int anchorIndex = -1; bool hasCalValues = false; double maxCalValue = 0; int numCalSubsectors = 0; double totalCalValue = 0; for( int subsectorIndex = 0; subsectorIndex < aSector->subsec.size(); ++subsectorIndex ) { double currCalValue = aSector->subsec[ subsectorIndex ]->getTotalCalOutputs( aPeriod ); bool isAllFixed = aSector->subsec[ subsectorIndex ]->containsOnlyFixedOutputTechnologies( aPeriod ) || aSector->subsec[ subsectorIndex ]->mShareWeights[ aPeriod ] == 0; // check if the subsector is calibrated if( hasCalValues && currCalValue == 0 && !isAllFixed ) { // warn that we mixed calibrated and variable technologies ILogger& mainLog = ILogger::getLogger( "main_log" ); ILogger& calibrationLog = ILogger::getLogger( "calibration_log" ); mainLog.setLevel( ILogger::WARNING ); calibrationLog.setLevel( ILogger::WARNING ); mainLog << "Mixed calibrated and variable subsectors or read a zero calibration value in Region: " << mCurrentRegionName << " in sector: " << mCurrentSectorName << " for Subsector: " << aSector->subsec[ subsectorIndex ]->getName() << endl; calibrationLog << "Mixed calibrated and variable subsectors or read a zero calibration value in Region: " << mCurrentRegionName << " in sector: " << mCurrentSectorName << " for Subsector: " << aSector->subsec[ subsectorIndex ]->getName() << endl; } else if( currCalValue > 0 ) { hasCalValues = true; } // If the calibrated value > 0 then increase the number of subsectors to calibrate // and include it in the total sum. if( currCalValue > 0 ) { ++numCalSubsectors; totalCalValue += currCalValue; } // attempt to locate the largest subsector if( currCalValue > maxCalValue ) { maxCalValue = currCalValue; anchorIndex = subsectorIndex; } } // do calibration if we have cal values and there are more than one subsector in this nest if( hasCalValues && numCalSubsectors > 1 ) { // we should have found a subsector to have share weights anchored assert( anchorIndex != -1 ); const double scaledGdpPerCapita = mGDP->getBestScaledGDPperCap( aPeriod ); const double anchorPrice = aSector->subsec[ anchorIndex ]->getPrice( mGDP, aPeriod ); const double anchorShare = ( aSector->subsec[ anchorIndex ]->getTotalCalOutputs( aPeriod ) / totalCalValue ) / pow( scaledGdpPerCapita, aSector->subsec[ anchorIndex ]->fuelPrefElasticity[ aPeriod ] ); assert( anchorShare > 0 ); for( int subsectorIndex = 0; subsectorIndex < aSector->subsec.size(); ++subsectorIndex ) { Subsector* currSubsector = aSector->subsec[ subsectorIndex ]; double currShare = ( currSubsector->getTotalCalOutputs( aPeriod ) / totalCalValue ) / pow( scaledGdpPerCapita, currSubsector->fuelPrefElasticity[ aPeriod ] ); // only set the share weight for valid subsectors if( currShare > 0 ) { double currShareWeight = ( currShare / anchorShare ) * pow( anchorPrice / currSubsector->getPrice( mGDP, aPeriod ), aSector->mSubsectorLogitExp[ aPeriod ] ); currSubsector->mShareWeights[ aPeriod ] = currShareWeight; } } } mCurrentSectorName.clear(); } void CalibrateShareWeightVisitor::startVisitSubsector( const Subsector* aSubsector, const int aPeriod ) { // Doing technology calibration in subsector rather than in technology because we will need access // to all of the technologies at the same time. // First we need to make sure that the technologies have calculated their costs. // We will also find the largest technology in terms of output so that we can anchor the share weights // by that technology and we will also make sure that we do not have a inconsistent set of // technologies with and without calibration values. const bool hasRequired = false; const string requiredName = ""; int anchorTechIndex = -1; bool hasCalValues = false; double maxCalValue = -1; int numlCalTechs = 0; double totalCalValue = 0; for( int techIndex = 0; techIndex < aSubsector->mTechContainers.size(); ++techIndex ) { ITechnology* currTech = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod ); // call calc cost to make sure they are up to date currTech->calcCost( mCurrentRegionName, mCurrentSectorName, aPeriod ); double currCalValue = currTech->getCalibrationOutput( hasRequired, requiredName, aPeriod ); bool isAvailable = currTech->isAvailable( aPeriod ); // check if we have calibrated technologies if( hasCalValues && currCalValue == -1 && isAvailable ) { // log that we have inconsistent calibrated and variable technologies ILogger& mainLog = ILogger::getLogger( "main_log" ); ILogger& calibrationLog = ILogger::getLogger( "calibration_log" ); mainLog.setLevel( ILogger::WARNING ); calibrationLog.setLevel( ILogger::WARNING ); mainLog << "Mixed calibrated and variable subsectors in Region: " << mCurrentRegionName << " in sector: " << mCurrentSectorName << " for technology: " << currTech->getName() << endl; calibrationLog << "Mixed calibrated and variable subsectors in Region: " << mCurrentRegionName << " in sector: " << mCurrentSectorName << " for technology: " << currTech->getName() << endl; } else if( isAvailable && currCalValue != -1 ) { hasCalValues = true; } // If the calibrated value > 0 then increase the number of technologies to calibrate // and include it in the total sum. if( currCalValue > 0 ) { ++numlCalTechs; totalCalValue += currCalValue; } // attempt to locate the largest technology if( currCalValue > maxCalValue ) { maxCalValue = currCalValue; anchorTechIndex = techIndex; } } // do calibration if we have cal values and there are more than one technologies in this nest if( hasCalValues && numlCalTechs > 1 ) { // we should have found a technology to have share weights anchored by assert( anchorTechIndex != -1 ); const ITechnology* anchorTech = aSubsector->mTechContainers[ anchorTechIndex ]->getNewVintageTechnology( aPeriod ); const double scaledGdpPerCapita = mGDP->getBestScaledGDPperCap( aPeriod ); const double anchorPrice = anchorTech->getCost( aPeriod ); const double anchorShare = ( anchorTech->getCalibrationOutput( hasRequired, requiredName, aPeriod ) / totalCalValue ) / pow( scaledGdpPerCapita, anchorTech->calcFuelPrefElasticity( aPeriod ) ); for( int techIndex = 0; techIndex < aSubsector->mTechContainers.size(); ++techIndex ) { ITechnology* currTech = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod ); double currShare = ( currTech->getCalibrationOutput( hasRequired, requiredName, aPeriod ) / totalCalValue ) / pow( scaledGdpPerCapita, currTech->calcFuelPrefElasticity( aPeriod ) ); // only set share weights for valid technologies if( currShare > 0 ) { double currShareWeight = ( currShare / anchorShare ) * pow( anchorPrice / currTech->getCost( aPeriod ), aSubsector->mTechLogitExp[ aPeriod ] ); currTech->setShareWeight( currShareWeight ); } } } } void CalibrateShareWeightVisitor::startVisitBuildingGenericDmdTechnology( const BuildingGenericDmdTechnology* aBuildingTech, const int aPeriod ) { // We must handle the detailed buildings as a special case here due to internal gains making it difficult // to know what the proper calibrated supply should be outside of the model. // We handle special detailed buildings calibration requirement by getting the total calibrated supply // for each input (including internal gains) and backing out the what the coef should be (excluding the demand // adjustment factor which will be handled by the BuildingDemandInput). // Note that this methodology relies on calibration values having already been tablulated. Also the calibrated // values (including those from internal gains) do no change per iteration however if there is a price // elasticity for an input that could change the coef per iteration. typedef vector<IInput*>::const_iterator CInputIterator; int normPeriod = SectorUtils::getDemandNormPeriod( aPeriod ); const Marketplace* marketplace = scenario->getMarketplace(); for( CInputIterator it = aBuildingTech->mInputs.begin(); it != aBuildingTech->mInputs.end(); ++it ) { // skip non-energy inputs if( (*it)->hasTypeFlag( IInput::ENERGY ) ) { // Get the calibration value for the output. const IInfo* tempInfo = marketplace->getMarketInfo( (*it)->getName(), mCurrentRegionName, aPeriod, true ); double calSupply = tempInfo ? tempInfo->getDouble( "calSupply", true ) : -1; tempInfo = marketplace->getMarketInfo( mCurrentSectorName, mCurrentRegionName, aPeriod, true ); double calDemand = tempInfo ? tempInfo->getDouble( "calDemand", true ) : -1; if( calSupply > 0 && calDemand > 0 ) { double priceRatio = SectorUtils::calcPriceRatio( mCurrentRegionName, (*it)->getName(), normPeriod, aPeriod ); double adjustedDemand = calDemand * pow( priceRatio, (*it)->getPriceElasticity() ); // Calculate a coefficient that would cause actual demand to equal // calibrated demand. double coef = adjustedDemand > util::getSmallNumber() ? calSupply / adjustedDemand : 0; const_cast<IInput*>( *it )->setCoefficient( coef / aBuildingTech->mAlphaZero, aPeriod ); // Double check things worked correctly. assert( util::isEqual( coef / aBuildingTech->mAlphaZero * calDemand * pow( priceRatio, ( *it )->getPriceElasticity() ), calSupply ) ); } else { // we are missing a calibration value so we will not be able to calibrate ILogger& mainLog = ILogger::getLogger( "main_log" ); ILogger& calibrationLog = ILogger::getLogger( "calibration_log" ); mainLog.setLevel( ILogger::WARNING ); calibrationLog.setLevel( ILogger::WARNING ); mainLog << "Missing cal value for building input " << (*it)->getName() << " in technology " << aBuildingTech->getName() << " sector " << mCurrentSectorName << " region " << mCurrentRegionName << " calSupply: " << calSupply << " calDemand: " << calDemand << endl; calibrationLog << "Missing cal value for building input " << (*it)->getName() << " in technology " << aBuildingTech->getName() << " sector " << mCurrentSectorName << " region " << mCurrentRegionName << " calSupply: " << calSupply << " calDemand: " << calDemand << endl; } } } }
53.90378
125
0.649241
E3SM-Project
087f8a963feb832dae01e037b98a7a6fd9436755
4,793
hpp
C++
boids_examples/boids/source/state/State.hpp
ankurshaswat/Starlings
f69147b13a47804b2d76c40b1f84ee07d57bbe60
[ "MIT" ]
null
null
null
boids_examples/boids/source/state/State.hpp
ankurshaswat/Starlings
f69147b13a47804b2d76c40b1f84ee07d57bbe60
[ "MIT" ]
null
null
null
boids_examples/boids/source/state/State.hpp
ankurshaswat/Starlings
f69147b13a47804b2d76c40b1f84ee07d57bbe60
[ "MIT" ]
null
null
null
/* * Author: Renato Utsch Gonçalves * Computer Science, UFMG * Computer Graphics * Practical exercise 2 - Boids * * Copyright (c) 2014 Renato Utsch <renatoutsch@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef STATE_STATE_HPP #define STATE_STATE_HPP struct GLFWwindow; class Engine; /** * Each state has an ID that is represented here. **/ enum StateId { /** * Idle state that does nothing, except listening to GLFW's close event. **/ IdleStateId = 0, /** * Running state. Normal state of the engine. **/ RunStateId, /** * Paused state. Does nothing until the state is restored to another state. **/ PauseStateId, /** * Debug state. Goes step by step. **/ DebugStateId }; /** * Each implementation of the State class stores the functions related to * a state of execution. This class must be derived and each derived class will * implement a state. **/ class State { public: /// Virtual destructor. virtual ~State() { } /** * Returns the ID of the current state. **/ virtual StateId getId() = 0; /** * The load function will be responsible for loading the state's necessary * data. It will be called only once, when starting the state, but never * again, not even when the state restarts. * It is the first function to be called when a state starts. **/ virtual void load() = 0; /** * The init function prepares the state's data. It is called when the state * is started and every time it is restarted. * This function should not load any data, only prepare it. This allows a * fast restart of state if a restart is required - with no loading or * unloading of data involved. **/ virtual void init() = 0; /** * The input function processes input. * This function should call glfwPollEvents() to handle events received by * the operating system. * This function must be non-blocking, so it must NEVER call * glfwWaitEvents(). **/ virtual void input() = 0; /** * The update function advances the game by dt time. * All gameplay logic should happen in this state. * @param dt The difference in time to simulate the game. **/ virtual void update(float dt) = 0; /** * The render function renders the current game state to the screen. * @param dt The time we are after the last physics update to display the * physics-affected objects at the right position. **/ virtual void render(float dt) = 0; /** * The cleanUp function frees any objects no longer required and sets the * state up for changing state or restarting. It is called when the current * state is being put on hold or when the game is exiting, before the * unload function. * No data should be unloaded, the idea is to just set everything up to be * initialized cleanly again. **/ virtual void cleanUp() = 0; /** * The unload function is called during state termination, i.e., when the * game is exiting, and unloads all data loaded in the load state. **/ virtual void unload() = 0; /** * Callback for key events from glfw. **/ virtual void keyEvent(GLFWwindow *window, int key, int scancode, int action, int mods) = 0; /** * Callback for mouse cursor position events from glfw. **/ virtual void cursorPosEvent(GLFWwindow *window, double xpos, double ypos) = 0; /** * Callback for mouse button events from glfw. **/ virtual void mouseButtonEvent(GLFWwindow *window, int button, int action, int mods) = 0; }; #endif // !STATE_STATE_HPP
31.532895
80
0.669727
ankurshaswat
08803fc56e85f2a45f1bb7370616ef7b54a31dc7
6,169
cpp
C++
StereoKitC/systems/d3d.cpp
gongminmin/StereoKit
3f83990ed6de0807735d8485664bf9350c37fc8a
[ "MIT" ]
null
null
null
StereoKitC/systems/d3d.cpp
gongminmin/StereoKit
3f83990ed6de0807735d8485664bf9350c37fc8a
[ "MIT" ]
null
null
null
StereoKitC/systems/d3d.cpp
gongminmin/StereoKit
3f83990ed6de0807735d8485664bf9350c37fc8a
[ "MIT" ]
null
null
null
#pragma comment(lib,"D3D11.lib") #pragma comment(lib,"Dxgi.lib") // CreateSwapChainForHwnd #include "../stereokit.h" #include "d3d.h" namespace sk { /////////////////////////////////////////// ID3D11Device *d3d_device = nullptr; ID3D11DeviceContext *d3d_context = nullptr; ID3D11InfoQueue *d3d_info = nullptr; ID3D11DepthStencilState *d3d_depthstate = nullptr; ID3D11RasterizerState *d3d_rasterstate = nullptr; int d3d_screen_width = 640; int d3d_screen_height = 480; /////////////////////////////////////////// bool d3d_init(LUID *adapter_id) { UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG creation_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif // Find the right adapter to use: IDXGIAdapter1 *final_adapter = nullptr; if (adapter_id != nullptr) { IDXGIFactory1 *dxgi_factory; CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **)(&dxgi_factory)); int curr = 0; IDXGIAdapter1 *curr_adapter = nullptr; while (dxgi_factory->EnumAdapters1(curr++, &curr_adapter) == S_OK) { DXGI_ADAPTER_DESC1 adapterDesc; curr_adapter->GetDesc1(&adapterDesc); if (memcmp(&adapterDesc.AdapterLuid, adapter_id, sizeof(adapter_id)) == 0) { log_diagf("Using graphics adapter: %ws", adapterDesc.Description); final_adapter = curr_adapter; break; } curr_adapter->Release(); } dxgi_factory->Release(); } D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; if (FAILED(D3D11CreateDevice(final_adapter, final_adapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN, 0, creation_flags, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, &d3d_device, nullptr, &d3d_context))) return false; if (final_adapter != nullptr) final_adapter->Release(); // Hook into debug information ID3D11Debug *d3dDebug = nullptr; if (SUCCEEDED(d3d_device->QueryInterface(__uuidof(ID3D11Debug), (void**)&d3dDebug))) { d3d_info = nullptr; if (SUCCEEDED(d3dDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&d3d_info))) { D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, (D3D11_MESSAGE_ID)351, (D3D11_MESSAGE_ID)49, // TODO: Figure out the Flip model for backbuffers! // Add more message IDs here as needed }; D3D11_INFO_QUEUE_FILTER filter = {}; filter.DenyList.NumIDs = _countof(hide); filter.DenyList.pIDList = hide; d3d_info->ClearStorageFilter(); d3d_info->AddStorageFilterEntries(&filter); } d3dDebug->Release(); } D3D11_DEPTH_STENCIL_DESC desc_depthstate = {}; desc_depthstate.DepthEnable = true; desc_depthstate.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc_depthstate.DepthFunc = D3D11_COMPARISON_LESS; desc_depthstate.StencilEnable = true; desc_depthstate.StencilReadMask = 0xFF; desc_depthstate.StencilWriteMask = 0xFF; desc_depthstate.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; desc_depthstate.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc_depthstate.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; desc_depthstate.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc_depthstate.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; d3d_device->CreateDepthStencilState(&desc_depthstate, &d3d_depthstate); d3d_context->OMSetDepthStencilState(d3d_depthstate, 1); D3D11_RASTERIZER_DESC desc_rasterizer = {}; desc_rasterizer.FillMode = D3D11_FILL_SOLID; desc_rasterizer.CullMode = D3D11_CULL_BACK; desc_rasterizer.FrontCounterClockwise = true; d3d_device->CreateRasterizerState(&desc_rasterizer, &d3d_rasterstate); d3d_context->RSSetState(d3d_rasterstate); d3d_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return true; } /////////////////////////////////////////// void d3d_shutdown() { if (d3d_context) { d3d_context->Release(); d3d_context = nullptr; } if (d3d_device ) { d3d_device->Release(); d3d_device = nullptr; } } /////////////////////////////////////////// void d3d_update() { #ifdef _DEBUG if (d3d_info == nullptr) return; for(size_t i = 0; i < d3d_info->GetNumStoredMessages(); i++) { SIZE_T size = 0; d3d_info->GetMessage(0, nullptr, &size); D3D11_MESSAGE * pMessage = (D3D11_MESSAGE*)malloc(size); if (SUCCEEDED(d3d_info->GetMessage(i, pMessage, &size)) && pMessage->Severity <= D3D11_MESSAGE_SEVERITY_WARNING) { const char *cat = "None"; switch(pMessage->Category) { case D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED: cat = "App"; break; case D3D11_MESSAGE_CATEGORY_MISCELLANEOUS: cat = "Misc"; break; case D3D11_MESSAGE_CATEGORY_INITIALIZATION: cat = "Init"; break; case D3D11_MESSAGE_CATEGORY_CLEANUP: cat = "Cleanup"; break; case D3D11_MESSAGE_CATEGORY_COMPILATION: cat = "Compile"; break; case D3D11_MESSAGE_CATEGORY_STATE_CREATION: cat = "State Create"; break; case D3D11_MESSAGE_CATEGORY_STATE_SETTING: cat = "State Set"; break; case D3D11_MESSAGE_CATEGORY_STATE_GETTING: cat = "State Get"; break; case D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:cat = "Resource"; break; case D3D11_MESSAGE_CATEGORY_EXECUTION: cat = "Exec"; break; case D3D11_MESSAGE_CATEGORY_SHADER: cat = "Shader"; break; } log_ level; switch (pMessage->Severity) { case D3D11_MESSAGE_SEVERITY_MESSAGE: case D3D11_MESSAGE_SEVERITY_INFO: level = log_inform; break; case D3D11_MESSAGE_SEVERITY_WARNING: level = log_warning; break; case D3D11_MESSAGE_SEVERITY_CORRUPTION: case D3D11_MESSAGE_SEVERITY_ERROR: level = log_error; break; default: level = log_inform; } log_writef(level, "%s: [%d] %s", cat, pMessage->ID, pMessage->pDescription); } free(pMessage); } d3d_info->ClearStoredMessages(); #endif } } // namespace sk
39.8
239
0.71065
gongminmin
08806b55c90ff8268bc5e6c35ad64b30151e5907
7,849
cpp
C++
include/card-gen/detail/rich_text.cpp
jonathansharman/card-gen
8a7b16baa8c17457959300a8b7825b29ed12051e
[ "Zlib", "MIT" ]
null
null
null
include/card-gen/detail/rich_text.cpp
jonathansharman/card-gen
8a7b16baa8c17457959300a8b7825b29ed12051e
[ "Zlib", "MIT" ]
null
null
null
include/card-gen/detail/rich_text.cpp
jonathansharman/card-gen
8a7b16baa8c17457959300a8b7825b29ed12051e
[ "Zlib", "MIT" ]
null
null
null
//! @file //! @copyright See <a href="RichText-LICENSE.txt">RichText-LICENSE.txt</a>. #include "rich_text.hpp" #include <SFML/Graphics.hpp> #include <fmt/format.h> #include <map> namespace { struct format { sf::Font* font = nullptr; sf::Uint32 style_flags = sf::Text::Regular; sf::Color fill_color = sf::Color::White; sf::Color outline_color = sf::Color::White; float outline_thickness = 0; }; struct chunk { format format; sf::String text; }; enum class align { left, center, right }; struct line { std::vector<chunk> chunks; align alignment = align::left; }; std::map<std::string, sf::Font> _fonts; std::map<std::string, sf::Color> _colors = { // {"default", sf::Color::White}, {"black", sf::Color::Black}, {"blue", sf::Color::Blue}, {"cyan", sf::Color::Cyan}, {"green", sf::Color::Green}, {"magenta", sf::Color::Magenta}, {"red", sf::Color::Red}, {"white", sf::Color::White}, {"yellow", sf::Color::Yellow}}; auto color_from_hex(unsigned argb_hex) -> sf::Color { argb_hex |= 0xff000000; return sf::Color(argb_hex >> 16 & 0xff, argb_hex >> 8 & 0xff, argb_hex >> 0 & 0xff, argb_hex >> 24 & 0xff); } auto color_from_string(std::string const& source) -> sf::Color { auto result = _colors.find(source); if (result != _colors.end()) { return result->second; } try { return color_from_hex(std::stoi(source, 0, 16)); } catch (...) { // Conversion failed; use default color. return sf::Color::White; } } } namespace sfe { auto rich_text::add_color(sf::String const& name, sf::Color const& color) -> void { _colors[name] = color; } auto rich_text::add_color(sf::String const& name, unsigned argb_hex) -> void { _colors[name] = color_from_hex(argb_hex); } rich_text::rich_text(sf::String const& source, unsigned character_size) : _character_size(character_size) { set_source(source); } auto rich_text::get_source() const -> sf::String { return _source; } auto rich_text::set_source(sf::String const& source) -> void { _source = source; clear(); format current_format; std::vector<line> lines{line{{chunk{current_format}}}}; for (auto it = source.begin(); it != source.end(); ++it) { static auto apply_formatting = [&] { if (!lines.back().chunks.back().text.isEmpty()) { // Start a new chunk if the current chunk has text. lines.back().chunks.push_back(chunk{current_format}); } else { // Otherwise, update current chunk. lines.back().chunks.back().format = current_format; } }; switch (*it) { case '/': // Italic current_format.style_flags ^= sf::Text::Italic; apply_formatting(); break; case '*': // Bold current_format.style_flags ^= sf::Text::Bold; apply_formatting(); break; case '_': // Underline current_format.style_flags ^= sf::Text::Underlined; apply_formatting(); break; case '~': // Strikethrough current_format.style_flags ^= sf::Text::StrikeThrough; apply_formatting(); break; case '[': { // Tag ++it; // Find the end of the tag and advance the iterator. auto const tag_end = std::find(it, source.end(), sf::Uint32{']'}); if (tag_end == source.end()) { throw std::domain_error{"Missing ']' in tag."}; } // Split into command and argument. auto const command_end = std::find(it, tag_end, sf::Uint32{' '}); auto const command = sf::String::fromUtf32(it, command_end); auto const arg = sf::String::fromUtf32(command_end + 1, tag_end).toAnsiString(); // Handle the tag. if (command == "fill-color") { current_format.fill_color = color_from_string(arg); apply_formatting(); } else if (command == "outline-color") { current_format.outline_color = color_from_string(arg); apply_formatting(); } else if (command == "outline-thickness") { current_format.outline_thickness = std::stof(arg); apply_formatting(); } else if (command == "font") { // First = (font name, font) pair; second = whether insertion occurred. auto result = _fonts.try_emplace(arg); if (result.second) { // Cache miss. Need to load font. if (!result.first->second.loadFromFile(arg)) { throw std::runtime_error{fmt::format("Could not load font from \"{}\".", arg)}; } } current_format.font = &result.first->second; apply_formatting(); } else if (command == "align") { if (arg == "left") { lines.back().alignment = align::left; } else if (arg == "center") { lines.back().alignment = align::center; } else if (arg == "right") { lines.back().alignment = align::right; } else { throw std::domain_error{fmt::format("Invalid alignment: {}.", arg)}; } } // Advance the iterator to the end of the tag (it will be incremented past at the end by the // loop). it = tag_end; break; } case '\\': // Escape sequence ++it; if (it == source.end()) { throw std::domain_error{"Expected formatting control character after '\\'."}; } switch (*it) { case '/': case '*': case '_': case '~': case '[': case '\\': lines.back().chunks.back().text += *it; break; default: throw std::domain_error{ fmt::format("Cannot escape non-control character '{}'.", static_cast<char>(*it))}; } break; case '\n': // New line lines.push_back(line{{chunk{current_format}}}); break; default: lines.back().chunks.back().text += *it; break; } } // Build texts and formatting-stripped string and compute bounds. sf::Vector2f next_position{}; _bounds = {0, 0, 0, 0}; for (auto const& line : lines) { float line_spacing = 0; for (auto const& chunk : line.chunks) { // Construct text. if (chunk.format.font == nullptr) { throw std::domain_error{"Text missing font specification."}; } line_spacing = std::max(line_spacing, chunk.format.font->getLineSpacing(_character_size)); _texts.push_back({chunk.text, *chunk.format.font, _character_size}); _texts.back().setStyle(chunk.format.style_flags); _texts.back().setFillColor(chunk.format.fill_color); _texts.back().setOutlineColor(chunk.format.outline_color); _texts.back().setOutlineThickness(chunk.format.outline_thickness); // Round next_position to avoid text blurriness. _texts.back().setPosition(std::roundf(next_position.x), std::roundf(next_position.y)); // Move next position to the end of the text. next_position = _texts.back().findCharacterPos(chunk.text.getSize()); // Extend bounds. auto const text_bounds = _texts.back().getGlobalBounds(); auto const right = text_bounds.left + text_bounds.width; _bounds.width = std::max(_bounds.width, right - _bounds.left); auto const bottom = text_bounds.top + text_bounds.height; _bounds.height = std::max(_bounds.height, bottom - _bounds.top); } //! @todo Align line. if (&line != &lines.back()) { // Handle new lines. next_position = {0, next_position.y + line_spacing}; } } } auto rich_text::clear() -> void { _texts.clear(); _bounds = sf::FloatRect{}; } auto rich_text::get_character_size() const -> unsigned { return _character_size; } auto rich_text::set_character_size(unsigned size) -> void { _character_size = std::max(size, 1u); set_source(_source); } auto rich_text::get_local_bounds() const -> sf::FloatRect { return _bounds; } auto rich_text::get_global_bounds() const -> sf::FloatRect { return getTransform().transformRect(_bounds); } auto rich_text::draw(sf::RenderTarget& target, sf::RenderStates states) const -> void { states.transform *= getTransform(); for (auto const& text : _texts) { target.draw(text, states); } } }
31.270916
109
0.631928
jonathansharman
08814127e99b0faf8f69413dc1720419c1475490
1,299
hpp
C++
headers/vivace/iterator/filter_map.hpp
KyleMayes/vivace
3baacc0785590c807e40e74a064c5c68a02c9c94
[ "Apache-2.0" ]
null
null
null
headers/vivace/iterator/filter_map.hpp
KyleMayes/vivace
3baacc0785590c807e40e74a064c5c68a02c9c94
[ "Apache-2.0" ]
null
null
null
headers/vivace/iterator/filter_map.hpp
KyleMayes/vivace
3baacc0785590c807e40e74a064c5c68a02c9c94
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Kyle Mayes // // 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. template <class T, class I, class F> class FilterMap : public Iterator<T, FilterMap<T, I, F>> { I source; F f; template <class S> Option<T> impl(S&& source) { for (auto item : source) { auto option = std::invoke(f, item); if (option.is_some()) { return option; } } return {}; } protected: Bounds bounds_impl() const { return {0, source.bounds().upper}; } Option<T> next_impl() { return impl(source); } Option<T> next_back_impl() { return impl(source.as_ref().reverse()); } public: FilterMap(I source, F f) : source{std::move(source)}, f{std::move(f)} { } };
27.638298
77
0.622787
KyleMayes
088152c73e437f17af152cdf6e83700ffacbef48
700
cpp
C++
export/debug/macos/obj/src/resources/__res_17.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
export/debug/macos/obj/src/resources/__res_17.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
export/debug/macos/obj/src/resources/__res_17.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 namespace hx { unsigned char __res_17[] = { 0x80, 0x00, 0x00, 0x80, 137,80,78,71,13,10,26,10,0,0, 0,13,73,72,68,82,0,0,0,11, 0,0,0,11,8,6,0,0,0,169, 172,119,38,0,0,0,25,116,69,88, 116,83,111,102,116,119,97,114,101,0, 65,100,111,98,101,32,73,109,97,103, 101,82,101,97,100,121,113,201,101,60, 0,0,0,84,73,68,65,84,120,218, 148,144,81,14,192,32,8,67,11,183, 220,5,185,102,183,37,83,153,86,221, 94,2,33,164,188,15,140,36,190,226, 105,142,171,184,168,176,100,190,7,91, 136,233,201,136,153,177,197,71,14,177, 67,109,93,16,226,96,8,151,32,196, 129,52,199,179,11,101,118,252,65,88, 102,188,254,188,229,20,96,0,3,5, 232,22,166,15,127,92,0,0,0,0, 73,69,78,68,174,66,96,130,0x00 }; }
29.166667
38
0.67
EnvyBun
0881fd34870e82b1b55b4876c21e49b1247e2044
907
hpp
C++
src/main/include/CANSparkMaxUtil.hpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
5
2022-01-12T02:08:29.000Z
2022-03-13T00:57:16.000Z
src/main/include/CANSparkMaxUtil.hpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
11
2022-01-29T22:00:14.000Z
2022-03-26T20:10:07.000Z
src/main/include/CANSparkMaxUtil.hpp
calcmogul/Robot-2020
b416c202794fb7deea0081beff2f986de7001ed9
[ "BSD-3-Clause" ]
1
2022-01-19T01:31:11.000Z
2022-01-19T01:31:11.000Z
// Copyright (c) FRC Team 3512. All Rights Reserved. #pragma once #include <rev/CANSparkMax.h> namespace frc3512 { enum class Usage { kAll, kPositionOnly, kVelocityOnly, kMinimal }; /** * This function allows reducing a Spark Max's CAN bus utilization by reducing * the periodic status frame period of nonessential frames from 20ms to 500ms. * * See * https://docs.revrobotics.com/sparkmax/operating-modes/control-interfaces#periodic-status-frames * for a description of the status frames. * * @param motor The motor to adjust the status frame periods on. * @param usage The status frame feedack to enable. kAll is the default * when a CANSparkMax is constructed. * @param enableFollowing Whether to enable motor following. */ void SetCANSparkMaxBusUsage(rev::CANSparkMax& motor, Usage usage, bool enableFollowing = false); } // namespace frc3512
32.392857
98
0.725469
calcmogul
08824c36bfdcdae1ddf40e4080c3d8265a4b1ea0
3,779
cc
C++
Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
#include <precompiled.h> /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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. /// /// Header file #include <Dy/Meta/Descriptor/WidgetTextMetaInformation.h> #include <nlohmann/json.hpp> #include <Dy/Helper/Library/HelperJson.h> #include <Dy/Helper/Type/DColorRGB24.h> namespace dy { std::unique_ptr<PDyMetaWidgetTextDescriptor> PDyMetaWidgetTextDescriptor::CreateMetaInformation(_MIN_ const nlohmann::json& itemAtlas) { /* Template { { "Name": "WidgetName", "Type": "Text", "Parent": "", "ZOrder": 0, "Details": { "InitialPosition": { "X": 0, "Y": 0 }, "WidgetSize": { "X": 200, "Y": 100 }, "Origin": "Center_Center", "InitialString": "This is test for general UI.", "InitialColor": { "R": 1.0, "G": 1.0, "B": 1.0, "A": 1.0 }, "EdgeColor": { "R": 1.0, "G": 1.0, "B": 1.0 }, "FontSize": 10, "FontSpecifierName": "Arial", "IsUsingEdge": false, "Alignment": "Left" } } } */ static MDY_SET_IMMUTABLE_STRING(sHeader_InitialString, "InitialString"); static MDY_SET_IMMUTABLE_STRING(sHeader_InitialPosition, "InitialPosition"); static MDY_SET_IMMUTABLE_STRING(sHeader_InitialColor, "InitialColor"); static MDY_SET_IMMUTABLE_STRING(sHeader_FontSize, "FontSize"); static MDY_SET_IMMUTABLE_STRING(sHeader_FontSpecifierName, "FontSpecifierName"); static MDY_SET_IMMUTABLE_STRING(sHeader_IsUsingEdge, "IsUsingEdge"); using TPDyMWCBD = PDyMetaWidgetCommonBaseDesc; //! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! FUNCTIONBODY ∨ //! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Common auto instance = std::make_unique<PDyMetaWidgetTextDescriptor>(); instance->mUiObjectSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Name); instance->mComponentType = EDyWidgetComponentType::Text; instance->mParentSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Parent); json::GetValueFromTo(itemAtlas, "IsActivated", instance->mIsActivated); json::GetValueFromTo(itemAtlas, "ZOrder", instance->mZOrder); // Detail (TEXT) const auto& detailAtlas = itemAtlas[(TPDyMWCBD::sHeader_Details)]; const auto string = json::GetValueFrom<std::string>(detailAtlas, sHeader_InitialString); instance->mTextString = string; instance->mTextColor = json::GetValueFrom<DColorRGBA>(detailAtlas, sHeader_InitialColor);; instance->mFontSize = json::GetValueFrom<TU32>(detailAtlas, sHeader_FontSize); instance->mFontName = json::GetValueFrom<std::string>(detailAtlas, sHeader_FontSpecifierName); instance->mEdgeColor = json::GetValueFrom<DColorRGB>(detailAtlas, "EdgeColor"); instance->mIsUsingEdge = json::GetValueFrom<bool>(detailAtlas, sHeader_IsUsingEdge); instance->mInitialPosition = DIVec2{json::GetValueFrom<DVec2>(detailAtlas, sHeader_InitialPosition)}; instance->mOrigin = json::GetValueFrom<EDyOrigin>(detailAtlas, "Origin"); instance->mWidgetSize = json::GetValueFrom<DIVec2>(detailAtlas, "WidgetSize"); json::GetValueFromTo(detailAtlas, "Alignment", instance->mAlignment); return instance; } } /// ::dy namespace
43.94186
107
0.677163
liliilli
088260d1292a5abdd9b3580bc5bead80a8216e71
7,052
cpp
C++
CMSIS/DSP/Testing/Source/Tests/InterpolationTestsF16.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
2,293
2016-02-25T06:47:33.000Z
2022-03-29T16:44:02.000Z
CMSIS/DSP/Testing/Source/Tests/InterpolationTestsF16.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
1,125
2016-02-27T09:56:01.000Z
2022-03-31T13:57:05.000Z
CMSIS/DSP/Testing/Source/Tests/InterpolationTestsF16.cpp
DavidLesnjak/CMSIS_5
e0848410d137758a3356a5ee94ca4501cea708a8
[ "Apache-2.0" ]
1,160
2016-02-27T09:06:10.000Z
2022-03-31T19:06:24.000Z
#include "InterpolationTestsF16.h" #include <stdio.h> #include "Error.h" #define SNR_THRESHOLD 55 /* Reference patterns are generated with a double precision computation. */ #define REL_ERROR (5.0e-3) #define ABS_ERROR (5.0e-3) void InterpolationTestsF16::test_linear_interp_f16() { const float16_t *inp = input.ptr(); float16_t *outp = output.ptr(); unsigned long nb; for(nb = 0; nb < input.nbSamples(); nb++) { outp[nb] = arm_linear_interp_f16(&S,inp[nb]); } ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); ASSERT_CLOSE_ERROR(output,ref,ABS_ERROR,REL_ERROR); } void InterpolationTestsF16::test_bilinear_interp_f16() { const float16_t *inp = input.ptr(); float16_t *outp = output.ptr(); float16_t x,y; unsigned long nb; for(nb = 0; nb < input.nbSamples(); nb += 2) { x = inp[nb]; y = inp[nb+1]; *outp++=arm_bilinear_interp_f16(&SBI,x,y); } ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); ASSERT_CLOSE_ERROR(output,ref,ABS_ERROR,REL_ERROR); } #if 0 void InterpolationTestsF16::test_spline_square_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*4-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(4-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_PARABOLIC_RUNOUT, inpX, inpY, 4, coef, buf); arm_spline_f16(&S, outX, outp, 20); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } void InterpolationTestsF16::test_spline_sine_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*9-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(9-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_NATURAL, inpX, inpY, 9, coef, buf); arm_spline_f16(&S, outX, outp, 33); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } void InterpolationTestsF16::test_spline_ramp_f16() { const float16_t *inpX = inputX.ptr(); const float16_t *inpY = inputY.ptr(); const float16_t *outX = outputX.ptr(); float16_t *outp = output.ptr(); float16_t *buf = buffer.ptr(); // ((2*3-1)*sizeof(float16_t)) float16_t *coef = splineCoefs.ptr(); // ((3*(3-1))*sizeof(float16_t)) arm_spline_instance_f16 S; arm_spline_init_f16(&S, ARM_SPLINE_PARABOLIC_RUNOUT, inpX, inpY, 3, coef, buf); arm_spline_f16(&S, outX, outp, 30); ASSERT_EMPTY_TAIL(buffer); ASSERT_EMPTY_TAIL(splineCoefs); ASSERT_EMPTY_TAIL(output); ASSERT_SNR(output,ref,(float16_t)SNR_THRESHOLD); } #endif void InterpolationTestsF16::setUp(Testing::testID_t id,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr) { const int16_t *pConfig; Testing::nbSamples_t nb=MAX_NB_SAMPLES; (void)params; switch(id) { case InterpolationTestsF16::TEST_LINEAR_INTERP_F16_1: input.reload(InterpolationTestsF16::INPUT_F16_ID,mgr,nb); y.reload(InterpolationTestsF16::YVAL_F16_ID,mgr,nb); ref.reload(InterpolationTestsF16::REF_LINEAR_F16_ID,mgr,nb); S.nValues=y.nbSamples(); /**< nValues */ /* Those values must be coherent with the ones in the Python script generating the patterns */ S.x1=0.0; /**< x1 */ S.xSpacing=1.0; /**< xSpacing */ S.pYData=y.ptr(); /**< pointer to the table of Y values */ break; case InterpolationTestsF16::TEST_BILINEAR_INTERP_F16_2: input.reload(InterpolationTestsF16::INPUTBI_F16_ID,mgr,nb); config.reload(InterpolationTestsF16::CONFIGBI_S16_ID,mgr,nb); y.reload(InterpolationTestsF16::YVALBI_F16_ID,mgr,nb); ref.reload(InterpolationTestsF16::REF_BILINEAR_F16_ID,mgr,nb); pConfig = config.ptr(); SBI.numRows = pConfig[1]; SBI.numCols = pConfig[0]; SBI.pData = y.ptr(); break; #if 0 case TEST_SPLINE_SQUARE_F16_3: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_SQU_X_F16_ID,mgr,4); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_SQU_Y_F16_ID,mgr,4); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_SQU_X_F16_ID,mgr,20); ref.reload(InterpolationTestsF16::REF_SPLINE_SQU_F16_ID,mgr,20); splineCoefs.create(3*(4-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*4-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(20,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; case TEST_SPLINE_SINE_F16_4: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_SIN_X_F16_ID,mgr,9); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_SIN_Y_F16_ID,mgr,9); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_SIN_X_F16_ID,mgr,33); ref.reload(InterpolationTestsF16::REF_SPLINE_SIN_F16_ID,mgr,33); splineCoefs.create(3*(9-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*9-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(33,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; case TEST_SPLINE_RAMP_F16_5: inputX.reload(InterpolationTestsF16::INPUT_SPLINE_RAM_X_F16_ID,mgr,3); inputY.reload(InterpolationTestsF16::INPUT_SPLINE_RAM_Y_F16_ID,mgr,3); outputX.reload(InterpolationTestsF16::OUTPUT_SPLINE_RAM_X_F16_ID,mgr,30); ref.reload(InterpolationTestsF16::REF_SPLINE_RAM_F16_ID,mgr,30); splineCoefs.create(3*(3-1),InterpolationTestsF16::COEFS_SPLINE_F16_ID,mgr); buffer.create(2*3-1,InterpolationTestsF16::TEMP_SPLINE_F16_ID,mgr); output.create(30,InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); break; #endif } output.create(ref.nbSamples(),InterpolationTestsF16::OUT_SAMPLES_F16_ID,mgr); } void InterpolationTestsF16::tearDown(Testing::testID_t id,Client::PatternMgr *mgr) { (void)id; output.dump(mgr); }
34.738916
121
0.638117
DavidLesnjak
0882dd8c60c42df44e794bcd69bfb71c3276c64c
4,737
cpp
C++
OGLApp/src/oaAnimationLoader.cpp
Consalv0/OGLApp
45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd
[ "MIT" ]
null
null
null
OGLApp/src/oaAnimationLoader.cpp
Consalv0/OGLApp
45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd
[ "MIT" ]
null
null
null
OGLApp/src/oaAnimationLoader.cpp
Consalv0/OGLApp
45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd
[ "MIT" ]
null
null
null
#include "oaLoaderUtils.h" #include <math.h> #include <codecvt> #include <locale> #include "oaJoint.h" #include "rapidxml\rapidxml.hpp" #include "rapidxml\rapidxml_iterators.hpp" #include "rapidxml\rapidxml_print.hpp" #include "rapidxml\rapidxml_utils.hpp" #include "oaAnimationLoader.h" std::unordered_map<std::string, std::vector<oaAnimation>> oaAnimationLoader::animationIDs = std::unordered_map<std::string, std::vector<oaAnimation>>(); std::vector<oaAnimation>* oaAnimationLoader::loadAnimation(const char * filePath) { if (animationIDs.find(filePath) != animationIDs.end()) { return &animationIDs.at(filePath); } std::string fileExt = oaGetFileExtension(filePath); std::vector<oaAnimation>* animation; // OBJ parser if (fileExt == "dae") { animation = loadDAE( filePath ); // Format not supported } else { printf("File extension no supported: '%s'", fileExt.c_str()); return NULL; } // Format supported, file unsopported if (animation == NULL || animation->empty()) { printf("Unable to load '%s'\n", filePath); return NULL; } // All right, add to the list of meshes animationIDs.insert({ std::string(filePath), *animation }); printf("Animation loaded : %s\n", filePath); return &animationIDs.find(filePath)->second; } std::vector<oaAnimation>* oaAnimationLoader::loadDAE(const char * filePath) { using namespace rapidxml; std::vector<oaAnimation>* animations = new std::vector<oaAnimation>(); xml_document<wchar_t> doc; // Open file file<wchar_t> fileXml(filePath); doc.parse<0>(fileXml.data()); // 0 means default parse flags xml_node<wchar_t> *collada = doc.first_node(L"COLLADA"); xml_node<wchar_t> *up_axis = collada->first_node(L"asset")->first_node(L"up_axis"); // Get the model orientation, OpenGl is Y-Up oriented glm::mat4 orientation = glm::mat4(); if (up_axis) { if (wcscmp(up_axis->value(), L"Z_UP") == 0) { orientation = { 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1 }; } //else if (wcscmp(up_axis->value(), L"Y_UP") == 0) { // orientation = { 1, 0, 0, // 0, 1, 0, // 0, 0, 1, }; //} else if (wcscmp(up_axis->value(), L"X_UP") == 0) { orientation = { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; } } xml_node<wchar_t> *library_animations = collada->first_node(L"library_animations"); xml_node<wchar_t> *animation = library_animations->first_node(L"animation"); while (animation) { xml_node<wchar_t> *source = animation->first_node(L"source"); oaAnimation currentAnimation; while (source) { if (auto technique_common = source->first_node(L"technique_common")) { if (auto accessor = technique_common->first_node(L"accessor")) { wchar_t* type = accessor->first_node(L"param")->first_attribute(L"name")->value(); if (wcscmp(L"TIME", type) == 0) { int keys = _wtoi(accessor->first_attribute(L"count")->value()); currentAnimation.size = keys; currentAnimation.keyTimes = new float[keys]; xml_node<wchar_t> *farray = source->first_node(L"float_array"); std::wistringstream iss(farray->value()); std::wstring s; for (int i = 0; i < keys; i++) { s.clear(); iss >> s; currentAnimation.keyTimes[i] = (float)_wtof(s.c_str()); } } if (wcscmp(L"TRANSFORM", type) == 0) { int keys = _wtoi(accessor->first_attribute(L"count")->value()); currentAnimation.transforms = new oaAnimation::JointTransforms[keys]; xml_node<wchar_t> *farray = source->first_node(L"float_array"); std::wistringstream iss(farray->value()); std::wstring s; for (int i = 0; i < keys; i++) { glm::mat4 transform; for (int j = 0; j < 4; j++) { s.clear(); iss >> s; transform[j][0] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][1] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][2] = (float)_wtof(s.c_str()); s.clear(); iss >> s; transform[j][3] = (float)_wtof(s.c_str()); } currentAnimation.transforms[i] = oaAnimation::JointTransforms(transform); } } } } source = source->next_sibling(L"source"); } if (auto channel = animation->first_node(L"channel")) { if (auto target = channel->first_attribute(L"target")) { currentAnimation.name = target->value(); } } animations->push_back(currentAnimation); animation = animation->next_sibling(L"animation"); } if (!animations || animations->empty()) { delete animations; return NULL; } return animations; }
31.791946
153
0.615368
Consalv0
08859397465f7b0033fbf0a340ec6ca5a1f25836
1,960
cpp
C++
src/ossimPlanet/netBuffer.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
11
2015-12-24T03:25:01.000Z
2021-01-09T18:22:56.000Z
src/ossimPlanet/netBuffer.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
3
2016-01-24T10:30:35.000Z
2018-03-31T15:07:16.000Z
src/ossimPlanet/netBuffer.cpp
ossimlabs/ossim-planet
ba37375aaab4dcc4b01d55d297c8d1f2b2dbbef8
[ "MIT" ]
5
2015-12-16T13:10:16.000Z
2021-11-12T19:23:31.000Z
/* PLIB - A Suite of Portable Game Libraries Copyright (C) 1998,2002 Steve Baker 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; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For further information visit http://plib.sourceforge.net $Id: netBuffer.cxx 1568 2002-09-02 06:05:49Z sjbaker $ */ #include <ossimPlanet/netBuffer.h> void netBufferChannel::handleRead (void) { int max_read = in_buffer.getMaxLength() - in_buffer.getLength() ; if (max_read) { char* data = in_buffer.getData() + in_buffer.getLength() ; int num_read = recv (data, max_read) ; if (num_read > 0) { in_buffer.append (num_read) ; //ulSetError ( UL_DEBUG, "netBufferChannel: %d read", num_read ) ; } } if (in_buffer.getLength()) { handleBufferRead (in_buffer); } } void netBufferChannel::handleWrite (void) { if (out_buffer.getLength()) { if (isConnected()) { int length = out_buffer.getLength() ; if (length>512) length=512; int num_sent = netChannel::send ( out_buffer.getData(), length); if (num_sent > 0) { out_buffer.remove (0, num_sent); //ulSetError ( UL_DEBUG, "netBufferChannel: %d sent", num_sent ) ; } } } else if (should_close) { close(); } }
28
77
0.661224
ossimlabs
08880d8906f8f3089c63dc941a5c7df11ebedb90
3,504
inl
C++
src/dcc/unit-import-source.c.inl
GrieferAtWork/dcc
e70803aef1d7dc83ecedc6134c3e7902e6b6bbca
[ "Zlib" ]
19
2017-08-27T16:27:44.000Z
2021-12-02T21:17:17.000Z
src/dcc/unit-import-source.c.inl
GrieferAtWork/dcc
e70803aef1d7dc83ecedc6134c3e7902e6b6bbca
[ "Zlib" ]
null
null
null
src/dcc/unit-import-source.c.inl
GrieferAtWork/dcc
e70803aef1d7dc83ecedc6134c3e7902e6b6bbca
[ "Zlib" ]
1
2022-02-17T18:51:21.000Z
2022-02-17T18:51:21.000Z
/* Copyright (c) 2017 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL #define GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL 1 #define DCC(x) x #include <dcc/common.h> #include <dcc/target.h> #include <dcc/compiler.h> #include <dcc/lexer.h> #include <dcc/assembler.h> #include <dcc/addr2line.h> #include "unit-import.h" DCC_DECL_BEGIN PRIVATE void load_std_sections(void) { unit.u_text = DCCUnit_NewSecs(".text",DCC_SYMFLAG_SEC_X|DCC_SYMFLAG_SEC_R); unit.u_data = DCCUnit_NewSecs(".data",DCC_SYMFLAG_SEC_R); unit.u_bss = DCCUnit_NewSecs(".bss",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_W); unit.u_string = DCCUnit_NewSecs(".string",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_M); /* NOTE: Symbols within '.dbgstr' cannot be merged! */ unit.u_dbgstr = DCCUnit_NewSecs(A2L_STRING_SECTION,DCC_SYMFLAG_SEC_R); } INTERN void DCCUNIT_IMPORTCALL DCCUnit_LoadSrc_C(struct DCCLibDef *__restrict def) { (void)def; compiler.c_flags |= (DCC_COMPILER_FLAG_NOCGEN); /*CURRENT.l_flags |= (TPPLEXER_FLAG_TERMINATE_STRING_LF);*/ /* Load standard sections. */ load_std_sections(); CURRENT.l_extokens &= (TPPLEXER_TOKEN_EQUALBINOP); CURRENT.l_extokens |= (TPPLEXER_TOKEN_LANG_C| TPPLEXER_TOKEN_TILDETILDE); /* Yield the initial token. */ TPPLexer_Yield(); /* Select the text section and begin compiling. */ DCCUnit_SetCurr(unit.u_text); DCCParse_AllGlobal(); DCCUnit_SetCurr(NULL); } INTERN void DCCUNIT_IMPORTCALL DCCUnit_LoadSrc_ASM(struct DCCLibDef *__restrict def) { (void)def; CURRENT.l_flags |= (TPPLEXER_FLAG_ASM_COMMENTS| /*TPPLEXER_FLAG_TERMINATE_STRING_LF|*/ TPPLEXER_FLAG_COMMENT_NOOWN_LF| TPPLEXER_FLAG_WANTLF); CURRENT.l_extokens = TPPLEXER_TOKEN_LANG_ASM; compiler.c_flags |= DCC_COMPILER_FLAG_INASM; load_std_sections(); /* Yield the initial token. */ TPPLexer_Yield(); /* Select the text section and begin compiling. */ DCCUnit_SetCurr(unit.u_text); while (TOK > 0) { unsigned long old_num = TOKEN.t_num; DCCParse_AsmInstr(); if (old_num == TOKEN.t_num) YIELD(); } DCCUnit_SetCurr(NULL); } DCC_DECL_END #endif /* !GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL */
36.884211
80
0.646404
GrieferAtWork
08892b6b615c227d047d8f35065a06969c30845c
480
cc
C++
tests/babel/compression/zstd.cc
project-arcana/arcana-samples
7dbe2cab765d4d86c6e96b4ab542cac75608a0b0
[ "MIT" ]
null
null
null
tests/babel/compression/zstd.cc
project-arcana/arcana-samples
7dbe2cab765d4d86c6e96b4ab542cac75608a0b0
[ "MIT" ]
null
null
null
tests/babel/compression/zstd.cc
project-arcana/arcana-samples
7dbe2cab765d4d86c6e96b4ab542cac75608a0b0
[ "MIT" ]
1
2020-01-22T18:04:53.000Z
2020-01-22T18:04:53.000Z
#include <nexus/fuzz_test.hh> #include <babel-serializer/compression/zstd.hh> FUZZ_TEST("zstd fuzzer")(tg::rng& rng) { auto cnt = uniform(rng, 0, 10); if (uniform(rng)) cnt = uniform(rng, 100, 1000); auto orig_data = cc::vector<std::byte>(cnt); for (auto& d : orig_data) d = uniform(rng); auto comp_data = babel::zstd::compress(orig_data); auto uncomp_data = babel::zstd::uncompress(comp_data); CHECK(orig_data == uncomp_data); }
22.857143
58
0.639583
project-arcana
08896b378a2aeaad13f8403f615158078cbf95bc
1,271
cpp
C++
example/example.cpp
maxcong001/empty001
b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e
[ "MIT" ]
null
null
null
example/example.cpp
maxcong001/empty001
b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e
[ "MIT" ]
null
null
null
example/example.cpp
maxcong001/empty001
b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e
[ "MIT" ]
null
null
null
#include "MessageBus.hpp" MessageBus g_bus; const string Topic = "Drive"; const string CallBackTopic = "DriveOK"; struct Subject { Subject() { g_bus.Attach([this]{DriveOK();},CallBackTopic); } void SendReq(const string& topic) { g_bus.SendReq<void, int>(50, topic); } void DriveOK() { cout<<"drive OK"<<endl; } }; struct Car { Car() { g_bus.Attach([this](int speed){Drive(speed);}, Topic); } void Drive(int speed) { cout<<"car drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; struct Bus { Bus() { g_bus.Attach([this](int speed){Drive(speed);}); } void Drive(int speed) { cout<<"Bus drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; struct Truck { Truck() { g_bus.Attach([this](int speed){Drive(speed);}); } void Drive(int speed) { cout<<"Truck drives "<<speed<<endl; g_bus.SendReq<void>(CallBackTopic); } }; void TestBus() { Subject subject; Car car; Bus bus; Truck truck; //subject.SendReq(Topic); for (int i = 0; i < 10000; i++) { subject.SendReq(""); } } int main() { TestBus(); return 0; }
15.8875
62
0.540519
maxcong001
088ba18ec1d1fc81f9e6193ee9e8b2c9fc289b91
1,361
cpp
C++
src/MessageCallbackMgr.cpp
enjoy0924/nuts-poppy
768f6dbd78afbdead4ea5b1e593ea9083da31d9e
[ "Apache-2.0" ]
null
null
null
src/MessageCallbackMgr.cpp
enjoy0924/nuts-poppy
768f6dbd78afbdead4ea5b1e593ea9083da31d9e
[ "Apache-2.0" ]
null
null
null
src/MessageCallbackMgr.cpp
enjoy0924/nuts-poppy
768f6dbd78afbdead4ea5b1e593ea9083da31d9e
[ "Apache-2.0" ]
null
null
null
#include "MessageCallbackMgr.h" CMessageCallbackMgr::CMessageCallbackMgr():m_nppMessageConstructor(NULL), m_sessionEventHandler(NULL) {} CMessageCallbackMgr::~CMessageCallbackMgr(){} int CMessageCallbackMgr::registerMessageCallback(int messageCode, DoMessageExecute onMessageFunc) { ACE_Guard<ACE_Mutex> guard(m_iMutex); m_mapDoExecuteFunc[messageCode] = onMessageFunc; return NPP_NOERROR; } DoMessageExecute CMessageCallbackMgr::getMessageCallbackByCode( int messageCode ) { ACE_Guard<ACE_Mutex> guard(m_iMutex); return m_mapDoExecuteFunc[messageCode]; } void CMessageCallbackMgr::setMessageConstructor( nppMessageConstructor defaultCreateMessage ) { m_nppMessageConstructor = defaultCreateMessage; } nppMessageConstructor CMessageCallbackMgr::getMessageConstructor() { return m_nppMessageConstructor; } void CMessageCallbackMgr::FireIoEventHandler( int sessionId, ENUM_IO_EVENT event ) { //throw std::exception("The method or operation is not implemented."); //we should give another thread to fire this kind of event return ; } void CMessageCallbackMgr::setIoEventHandler( IoEventHandler sessionEventHandler ) { m_sessionEventHandler = sessionEventHandler; } IoEventHandler CMessageCallbackMgr::getIoEventHandler() { return m_sessionEventHandler; }
28.957447
98
0.775165
enjoy0924
0891114c98097ca2d299c23de53361ba69033b50
3,206
cpp
C++
src/Game.cpp
nonk123/SpaceThing
efb0929cf6dc67df652be45619e7ed012aa41a5f
[ "MIT" ]
null
null
null
src/Game.cpp
nonk123/SpaceThing
efb0929cf6dc67df652be45619e7ed012aa41a5f
[ "MIT" ]
null
null
null
src/Game.cpp
nonk123/SpaceThing
efb0929cf6dc67df652be45619e7ed012aa41a5f
[ "MIT" ]
null
null
null
#include "Game.hpp" #include <algorithm> #include "Utils.hpp" #include "SimpleEntity.hpp" #include "RenderUtils.hpp" #include "Math.hpp" #include "config.hpp" using namespace SpaceThing; using namespace Utils; void Game::initSession(irr::IrrlichtDevice* device) { session.device = device; session.driver = device->getVideoDriver(); session.smg = device->getSceneManager(); session.gui = device->getGUIEnvironment(); session.gc = session.smg->getGeometryCreator(); } void Game::nullSession() { session.device = nullptr; session.driver = nullptr; session.smg = nullptr; session.gui = nullptr; session.gc = nullptr; } static irr::f32 cameraPitch = Pi<irr::f32>; static irr::f32 cameraYaw = HalfPi<irr::f32>; static irr::f32 cameraRadius = 20; static irr::scene::ICameraSceneNode* camera = nullptr; void Game::acceptInput(const EventReceiver& receiver) { if (receiver.isDown(irr::KEY_KEY_Q)) running = false; irr::f32 dp = 0, dy = 0; static const irr::f32 d = Pi<irr::f32> / 32; static const irr::f32 r = 0.5; if (receiver.isDown(irr::KEY_KEY_A)) dy = -d; else if (receiver.isDown(irr::KEY_KEY_D)) dy = +d; if (receiver.isDown(irr::KEY_KEY_W)) dp = +d; else if (receiver.isDown(irr::KEY_KEY_S)) dp = -d; if (receiver.isDown(irr::KEY_KEY_R)) cameraRadius -= r; else if (receiver.isDown(irr::KEY_KEY_F)) cameraRadius += r; cameraRadius = std::clamp(cameraRadius, irr::f32(0.05), irr::f32(25)); cameraPitch += dp; cameraPitch = std::clamp(cameraPitch, -HalfPi<irr::f32>, HalfPi<irr::f32>); cameraYaw += dy; if (cameraYaw < 0) cameraYaw = Pi2<irr::f32>; else if (cameraYaw > Pi2<irr::f32>) cameraYaw = 0; const irr::core::vector3df origin(2.5, 2.5, 2.5); camera->setPosition(origin + irr::core::vector3df(std::cos(cameraYaw), std::sin(cameraPitch), std::sin(cameraYaw)) * cameraRadius); camera->setTarget(origin); } int Game::run() { EventReceiver receiver; IrrPtr<irr::IrrlichtDevice> device(irr::createDevice(VIDEO_DRIVER, {800, 600}, 32, false, false, false, &receiver)); initSession(device.get()); device->setWindowCaption(L"Space Thing"); camera = session.smg->addCameraSceneNode(); session.gui->addStaticText(L"Q to quit", {0, 0, 100, 10}) ->setOverrideColor({255, 255, 255, 255}); session.smg->addLightSceneNode(nullptr, {12.5, 10, 12.5}); world.add(new SimpleEntity(box({5, 5, 5}, {255, 255, 255, 255}))); while (running && device->run()) { session.driver->beginScene(true, true, {255, 8, 8, 10}); acceptInput(receiver); world.update(); session.smg->drawAll(); session.gui->drawAll(); session.driver->endScene(); } return 0; }
27.878261
79
0.564255
nonk123
0895e18f2cdcf1f77701cbbe0a26580eeb0da3d8
525
cpp
C++
Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp
AkhilSoni0102/Learning-Data-Structures
27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6
[ "MIT" ]
2
2021-04-03T11:50:42.000Z
2021-05-06T16:45:06.000Z
Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp
AkhilSoni0102/Learning-Data-Structures
27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6
[ "MIT" ]
null
null
null
Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp
AkhilSoni0102/Learning-Data-Structures
27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int n, sum; cin>>n>>sum; int coin[n]; for(int i = 0;i < n;i++) cin>>coin[i]; int t[n+1][sum+1]; for(int i = 0;i < sum+1;i++) t[0][i] = 0; for(int i = 0;i < n + 1;i++) t[i][0] = 1; for(int i = 1;i < n+1;i++) for(int j = 1;j < sum + 1;j++) if(coin[i-1] <= j) t[i][j] = t[i][j-coin[i-1]] + t[i-1][j]; else t[i][j] = t[i-1][j]; cout <<t[n][sum]; }
25
56
0.373333
AkhilSoni0102
08966fa6223ce3e837f3316adffeae7e2fb4e0bf
9,369
cpp
C++
C/src/Coordinates.cpp
AltynbekAndr/GpsOtMadDevs
1da1cf5c74a145a96384e480367b418abd8a3e39
[ "Unlicense" ]
null
null
null
C/src/Coordinates.cpp
AltynbekAndr/GpsOtMadDevs
1da1cf5c74a145a96384e480367b418abd8a3e39
[ "Unlicense" ]
null
null
null
C/src/Coordinates.cpp
AltynbekAndr/GpsOtMadDevs
1da1cf5c74a145a96384e480367b418abd8a3e39
[ "Unlicense" ]
null
null
null
#include <QDebug> #include <QFile> #include <vector> #include <QRegExp> #include <math.h> #include "Coordinates.h" #include "Geohash.h" #include "Commons.h" #include "SensorController.h" std::vector<geopoint_t> CoordGetFromFile(const QString& filePath, int interested) { std::vector<geopoint_t> lstResult; QFile f(filePath); SensorData_t sd; if (!f.open(QFile::ReadOnly)) { qDebug() << "Open file " << filePath << " error : " << f.errorString(); return lstResult; } while (!f.atEnd()) { QString line = f.readLine(); int pi = SensorControllerParseDataString(line.toStdString().c_str(), &sd); if (pi != interested) continue; lstResult.push_back(geopoint_t(sd.gpsLat, sd.gpsLon)); } f.close(); return lstResult; } ////////////////////////////////////////////////////////////////////////// std::vector<geopoint_t> CoordFilterByGeoHash(std::vector<geopoint_t> &lstSrc, int precision, int minPointCount) { #define NOT_VALID_POINT_INDEX -1 struct AuxItem { double lon; double lat; int32_t index; int32_t count; }; std::vector<geopoint_t> lstRes; std::map<uint64_t, AuxItem> dctHashCount; typedef std::map<uint64_t, AuxItem>::iterator dctIter; int idx = 0; for (auto ci = lstSrc.begin(); ci != lstSrc.end(); ++ci) { uint64_t gh = GeohashEncodeU64(ci->Latitude, ci->Longitude, precision); dctIter it = dctHashCount.find(gh); if (it == dctHashCount.end()) { AuxItem ni; ni.count = 0; ni.lat = ni.lon = 0.0; ni.index = NOT_VALID_POINT_INDEX; auto ir = dctHashCount.insert(std::pair<uint64_t, AuxItem>(gh, ni)); if (!ir.second) continue; it = ir.first; } if (++it->second.count == minPointCount) it->second.index = idx++; it->second.lat += ci->Latitude; it->second.lon += ci->Longitude; } lstRes.reserve(idx); lstRes.resize(idx); for (auto it = dctHashCount.begin(); it != dctHashCount.end(); ++it) { if (it->second.index == NOT_VALID_POINT_INDEX) continue; geopoint_t np; np.Latitude = it->second.lat / it->second.count; np.Longitude = it->second.lon / it->second.count; lstRes[it->second.index] = np; } return lstRes; } ////////////////////////////////////////////////////////////////////////// static const double a = 6378137.0; // meter static const double f = 1 / 298.257223563; static const double b = (1 - f) * a; // meter //https://en.wikipedia.org/wiki/Great-circle_distance static double geoDistanceMeters(double lon1, double lat1, double lon2, double lat2) { #if COORDINATES_HIGH_ACCURACY==0 double deltaLon = Degree2Rad(lon2 - lon1); double deltaLat = Degree2Rad(lat2 - lat1); double a = pow(sin(deltaLat / 2.0), 2.0) + cos(Degree2Rad(lat1))* cos(Degree2Rad(lat2))* pow(sin(deltaLon / 2.0), 2.0); double c = 2.0 * atan2(sqrt(a), sqrt(1.0-a)); return EARTH_RADIUS * c; #else double f1 = Degree2Rad(lat1), l1 = Degree2Rad(lon1); double f2 = Degree2Rad(lat2), l2 = Degree2Rad(lon2); double L = l2 - l1; double tanU1 = (1-f) * tan(f1); double cosU1 = 1 / sqrt((1.0 + tanU1*tanU1)); double sinU1 = tanU1 * cosU1; double tanU2 = (1-f) * tan(f2); double cosU2 = 1 / sqrt((1.0 + tanU2*tanU2)); double sinU2 = tanU2 * cosU2; double sinl, cosl; double sinSqs, sins=0.0, coss=0.0, sig=0.0, sina, cosSqa=0, cos2sigM=0, C; double l = L, ll; int iterations = 1000; do { sinl = sin(l); cosl = cos(l); sinSqs = (cosU2*sinl) * (cosU2*sinl) + (cosU1*sinU2-sinU1*cosU2*cosl) * (cosU1*sinU2-sinU1*cosU2*cosl); if (sinSqs == 0) break; // co-incident points sins = sqrt(sinSqs); coss = sinU1*sinU2 + cosU1*cosU2*cosl; sig = atan2(sins, coss); sina = cosU1 * cosU2 * sinl / sins; cosSqa = 1 - sina*sina; cos2sigM = (cosSqa != 0) ? (coss - 2*sinU1*sinU2/cosSqa) : 0; // equatorial line: cosSqα=0 (§6) C = f/16*cosSqa*(4+f*(4-3*cosSqa)); ll = l; l = L + (1-C) * f * sina * (sig + C*sins*(cos2sigM+C*coss*(-1+2*cos2sigM*cos2sigM))); if (abs(l) > M_PI) return 0.0; } while (abs(l-ll) > 1e-12 && iterations--); if (!iterations) return 0.0; double uSq = cosSqa * (a*a - b*b) / (b*b); double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq))); double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq))); double dsig = B*sins*(cos2sigM+B/4*(coss*(-1+2*cos2sigM*cos2sigM)- B/6*cos2sigM*(-3+4*sins*sins)*(-3+4*cos2sigM*cos2sigM))); double s = b*A*(sig-dsig); return s; #endif } ////////////////////////////////////////////////////////////////////////// double CoordLongitudeToMeters(double lon) { double distance = geoDistanceMeters(lon, 0.0, 0.0, 0.0); return distance * (lon < 0.0 ? -1.0 : 1.0); } ////////////////////////////////////////////////////////////////////////// double CoordLatitudeToMeters(double lat) { double distance = geoDistanceMeters(0.0, lat, 0.0, 0.0); return distance * (lat < 0.0 ? -1.0 : 1.0); } ////////////////////////////////////////////////////////////////////////// static geopoint_t getPointAhead(geopoint_t point, double distance, double azimuthDegrees) { #if COORDINATES_HIGH_ACCURACY==0 geopoint_t res; double radiusFraction = distance / EARTH_RADIUS; double bearing = Degree2Rad(azimuthDegrees); double lat1 = Degree2Rad(point.Latitude); double lng1 = Degree2Rad(point.Longitude); double lat2_part1 = sin(lat1) * cos(radiusFraction); double lat2_part2 = cos(lat1) * sin(radiusFraction) * cos(bearing); double lat2 = asin(lat2_part1 + lat2_part2); double lng2_part1 = sin(bearing) * sin(radiusFraction) * cos(lat1); double lng2_part2 = cos(radiusFraction) - sin(lat1) * sin(lat2); double lng2 = lng1 + atan2(lng2_part1, lng2_part2); lng2 = fmod(lng2 + 3.0*M_PI, 2.0*M_PI) - M_PI; res.Latitude = Rad2Degree(lat2); res.Longitude = Rad2Degree(lng2); return res; #else double t1 = Degree2Rad(point.Latitude); double l1 = Degree2Rad(point.Longitude); double a1 = Degree2Rad(azimuthDegrees); double sina1 = sin(a1); double cosa1 = cos(a1); double tanU1 = (1-f) * tan(t1); double cosU1 = 1 / sqrt((1 + tanU1*tanU1)); double sinU1 = tanU1 * cosU1; double sig1 = atan2(tanU1, cosa1); double sina = cosU1 * sina1; double cosSqa = 1 - sina*sina; double uSq = cosSqa * (a*a - b*b) / (b*b); double A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq))); double B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq))); double cos2sigM, sinSig, cosSig, dsig; double sig = distance / (b*A); double ddsig; int iterations = 100; do { cos2sigM = cos(2*sig1 + sig); sinSig = sin(sig); cosSig = cos(sig); dsig = B*sinSig*(cos2sigM+B/4*(cosSig*(-1+2*cos2sigM*cos2sigM)- B/6*cos2sigM*(-3+4*sinSig*sinSig)*(-3+4*cos2sigM*cos2sigM))); ddsig = sig; sig = distance / (b*A) + dsig; } while (abs(sig-ddsig) > 1e-12 && iterations--); assert(iterations); //hack! double x = sinU1*sinSig - cosU1*cosSig*cosa1; double l = atan2(sinSig*sina1, cosU1*cosSig - sinU1*sinSig*cosa1); double C = f/16*cosSqa*(4+f*(4-3*cosSqa)); double L = l - (1-C) * f * sina * (sig + C*sinSig*(cos2sigM+C*cosSig*(-1+2*cos2sigM*cos2sigM))); double l2 = fmod((l1+L+3*M_PI) , (2*M_PI)) - M_PI; // normalise to -180..+180 geopoint_t res; res.Latitude = Rad2Degree(atan2(sinU1*cosSig + cosU1*sinSig*cosa1, (1-f)*sqrt(sina*sina + x*x))); res.Longitude = Rad2Degree(l2); return res; #endif } ////////////////////////////////////////////////////////////////////////// static geopoint_t pointPlusDistanceEast(geopoint_t point, double distance) { return getPointAhead(point, distance, 90.0); } static geopoint_t pointPlusDistanceNorth(geopoint_t point, double distance) { return getPointAhead(point, distance, 0.0); } ////////////////////////////////////////////////////////////////////////// geopoint_t CoordMetersToGeopoint(double lonMeters, double latMeters) { geopoint_t point = {0.0, 0.0}; geopoint_t pointEast = pointPlusDistanceEast(point, lonMeters); geopoint_t pointNorthEast = pointPlusDistanceNorth(pointEast, latMeters); return pointNorthEast; } ////////////////////////////////////////////////////////////////////////// double CoordDistanceBetweenPointsMeters(double lat1, double lon1, double lat2, double lon2) { return geoDistanceMeters(lon1, lat1, lon2, lat2); } ////////////////////////////////////////////////////////////////////////// double CoordCaclulateDistance(const std::vector<geopoint_t> &lst) { double distance = 0.0; double llon, llat; if (lst.empty() || lst.size() == 1) return 0.0; llon = lst[0].Longitude; llat = lst[0].Latitude; for (auto pp = lst.begin()+1; pp != lst.end(); ++pp) { distance += CoordDistanceBetweenPointsMeters(llat, llon, pp->Latitude, pp->Longitude); llat = pp->Latitude; llon = pp->Longitude; } return distance; } //////////////////////////////////////////////////////////////////////////
32.989437
109
0.568897
AltynbekAndr