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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f15f6d28bf1e139232cf003c1ea937e305a5c5a | 3,539 | cpp | C++ | Codility/NumberOfDiscIntersections.cpp | dfm066/Programming | 53d28460cd40b966cca1d4695d9dc6792ced4c6f | [
"MIT"
] | null | null | null | Codility/NumberOfDiscIntersections.cpp | dfm066/Programming | 53d28460cd40b966cca1d4695d9dc6792ced4c6f | [
"MIT"
] | null | null | null | Codility/NumberOfDiscIntersections.cpp | dfm066/Programming | 53d28460cd40b966cca1d4695d9dc6792ced4c6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define MAX 1e7
bool first_comp(const pair<long long,long long> a, const pair<long long,long long> b) {
if (a.first > b.first) return false;
else if(a.first == b.first && a.second > b.second) return false;
else return true;
}
bool second_comp(const pair<long long,long long> a, const pair<long long,long long> b) {
if (a.second > b.second) return false;
else if (a.second == b.second && a.first > b.first) return false;
return true;
}
int is_equal(const pair<long long,long long> &val, const vector<pair<long long,long long>> &container) {
int st = 0;
int en = container.size();
int middle = 0;
while (st <= en) {
middle = (st+en) / 2;
if (container[middle] == val) return middle;
else if(second_comp(val, container[middle])) en = middle - 1;
else st = middle + 1;
}
return middle;
}
int is_greater_or_equal(const pair<long long,long long> val, const vector<pair<long long,long long>> &container, int lim) {
int st = 0;
int en = lim;
int middle = 0;
while (st <= en) {
middle = (st+en) / 2;
if (val.first == container[middle].second) {
while(container[middle].second == val.first && middle > 0) middle--;
break;
}
else if (val.first < container[middle].second) en = middle -1;
else st = middle + 1;
}
if (val.first <= container[middle].second) return middle;
else return middle+1;
}
template <class T>
void print_container(string header, T container) {
cout << header << " : ";
for(auto val:container) {
cout << "[" << val.first << ", " << val.second << "] ";
}
cout << endl;
}
int solution(vector<int> &A) {
int N = (int)A.size();
int res = 0;
vector<pair<long long,long long>> start_bound(N);
for(long long pos = 0; pos < N; pos++) {
start_bound[pos].first = pos - A[pos];
start_bound[pos].second = pos + A[pos];
}
// Debugging purpose
print_container("original vector", start_bound);
vector<pair<long long,long long>> end_bound(start_bound);
make_heap(start_bound.begin(), start_bound.end(), first_comp);
make_heap(end_bound.begin(), end_bound.end(), second_comp);
// Debugging purpose
print_container("start_bound before sort", start_bound);
print_container("end_bound before sort", end_bound);
sort_heap(start_bound.begin(), start_bound.end(), first_comp);
sort_heap(end_bound.begin(), end_bound.end(), second_comp);
// Debugging purpose
print_container("start_bound after sort", start_bound);
print_container("end_bound after sort", end_bound);
for (auto val:start_bound){
int en_lim = is_equal(val, end_bound);
int st_lim = is_greater_or_equal(val, end_bound, en_lim);
// Debugging purpose
cout << en_lim << " " << st_lim << " "<< res << endl;
assert(en_lim >= st_lim);
res += en_lim-st_lim;
}
if (res > MAX) res = -1;
return res;
}
// Driver Program
int main(){
int N;
cin>>N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin>>A[i];
}
cout << "Input : ";
for(auto val : A){
cout << " " << val;
}
cout << endl;
cout << "Solution : " << solution(A) << endl;
cout << MAX;
return 0;
}
| 28.540323 | 124 | 0.565131 | dfm066 |
1f15f8db8541780972f18bac14cdfb549498b72d | 2,983 | cpp | C++ | components/raisedbutton.cpp | ashraf-kx/qt-material-widgets | 851d3fb7b56695a9181e3ea373f3d9e4015c15df | [
"BSD-3-Clause"
] | 5 | 2018-09-13T16:18:03.000Z | 2022-03-16T07:34:21.000Z | components/raisedbutton.cpp | ashraf-kx/qt-material-widgets | 851d3fb7b56695a9181e3ea373f3d9e4015c15df | [
"BSD-3-Clause"
] | null | null | null | components/raisedbutton.cpp | ashraf-kx/qt-material-widgets | 851d3fb7b56695a9181e3ea373f3d9e4015c15df | [
"BSD-3-Clause"
] | 2 | 2022-02-22T04:08:50.000Z | 2022-03-12T10:05:15.000Z | #include "raisedbutton_p.h"
namespace md
{
/*!
* \class QtMaterialRaisedButtonPrivate
* \internal
*/
/*!
* \internal
*/
RaisedButtonPrivate::RaisedButtonPrivate(RaisedButton *q)
: FlatButtonPrivate(q)
{
}
/*!
* \internal
*/
RaisedButtonPrivate::~RaisedButtonPrivate()
{
}
/*!
* \internal
*/
void RaisedButtonPrivate::init()
{
Q_Q(RaisedButton);
shadowStateMachine = new QStateMachine(q);
normalState = new QState;
pressedState = new QState;
effect = new QGraphicsDropShadowEffect;
effect->setBlurRadius(7);
effect->setOffset(QPointF(0, 2));
effect->setColor(QColor(0, 0, 0, 75));
q->setBackgroundMode(Qt::OpaqueMode);
q->setMinimumHeight(42);
q->setGraphicsEffect(effect);
q->setBaseOpacity(0.3);
shadowStateMachine->addState(normalState);
shadowStateMachine->addState(pressedState);
normalState->assignProperty(effect, "offset", QPointF(0, 2));
normalState->assignProperty(effect, "blurRadius", 7);
pressedState->assignProperty(effect, "offset", QPointF(0, 5));
pressedState->assignProperty(effect, "blurRadius", 29);
QAbstractTransition *transition;
transition = new QEventTransition(q, QEvent::MouseButtonPress);
transition->setTargetState(pressedState);
normalState->addTransition(transition);
transition = new QEventTransition(q, QEvent::MouseButtonDblClick);
transition->setTargetState(pressedState);
normalState->addTransition(transition);
transition = new QEventTransition(q, QEvent::MouseButtonRelease);
transition->setTargetState(normalState);
pressedState->addTransition(transition);
QPropertyAnimation *animation;
animation = new QPropertyAnimation(effect, "offset", q);
animation->setDuration(100);
shadowStateMachine->addDefaultAnimation(animation);
animation = new QPropertyAnimation(effect, "blurRadius", q);
animation->setDuration(100);
shadowStateMachine->addDefaultAnimation(animation);
shadowStateMachine->setInitialState(normalState);
shadowStateMachine->start();
}
/*!
* \class QtMaterialRaisedButton
*/
RaisedButton::RaisedButton(QWidget *parent)
: FlatButton(*new RaisedButtonPrivate(this), parent)
{
d_func()->init();
}
RaisedButton::RaisedButton(const QString &text, QWidget *parent)
: FlatButton(*new RaisedButtonPrivate(this), parent)
{
d_func()->init();
setText(text);
}
RaisedButton::~RaisedButton()
{
}
RaisedButton::RaisedButton(RaisedButtonPrivate &d, QWidget *parent)
: FlatButton(d, parent)
{
d_func()->init();
}
bool RaisedButton::event(QEvent *event)
{
Q_D(RaisedButton);
if (QEvent::EnabledChange == event->type()) {
if (isEnabled()) {
d->shadowStateMachine->start();
d->effect->setEnabled(true);
} else {
d->shadowStateMachine->stop();
d->effect->setEnabled(false);
}
}
return FlatButton::event(event);
}
}
| 23.304688 | 70 | 0.684211 | ashraf-kx |
1f1773bc564d12a50ad025a5af7f5fd6ac3bf253 | 204 | ipp | C++ | dev/test/router/express/usings.ipp | faizol/restinio | 8a7da3e2e3a54d0ca6ac80e6c7952d9905a084bb | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 881 | 2017-12-26T23:45:13.000Z | 2022-03-26T08:12:54.000Z | dev/test/router/express/usings.ipp | faizol/restinio | 8a7da3e2e3a54d0ca6ac80e6c7952d9905a084bb | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 142 | 2018-01-07T01:45:43.000Z | 2022-03-17T04:53:41.000Z | dev/test/router/express/usings.ipp | faizol/restinio | 8a7da3e2e3a54d0ca6ac80e6c7952d9905a084bb | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 97 | 2017-12-28T13:06:45.000Z | 2022-03-03T04:43:44.000Z | using namespace restinio;
using namespace restinio::router;
using regex_engine_t = restinio::router::std_regex_engine_t;
using route_matcher_t = restinio::router::impl::route_matcher_t< regex_engine_t >;
| 40.8 | 82 | 0.823529 | faizol |
1f17a00fc05e94477d5bb3428d939891fdb66ae5 | 1,259 | hpp | C++ | code/src/engine/physics/helper_physx.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 3 | 2020-04-29T14:55:58.000Z | 2020-08-20T08:43:24.000Z | code/src/engine/physics/helper_physx.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 1 | 2022-03-12T11:37:46.000Z | 2022-03-12T20:17:38.000Z | code/src/engine/physics/helper_physx.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | null | null | null |
#ifndef ENGINE_PHYSICS_HELPER_PHYSX_HPP
#define ENGINE_PHYSICS_HELPER_PHYSX_HPP
#include <PxPhysicsAPI.h>
#include <core/maths/Vector.hpp>
/**
* \note Should be used by physics implementation only.
*/
namespace engine
{
namespace physics
{
template<class T>
inline T convert(const core::maths::Vector3f val)
{
core::maths::Vector3f::array_type buffer;
val.get_aligned(buffer);
return T {buffer[0], buffer[1], buffer[2]};
}
inline physx::PxQuat convert(const core::maths::Quaternionf val)
{
core::maths::Quaternionf::array_type buffer;
val.get_aligned(buffer);
return physx::PxQuat { buffer[1], buffer[2], buffer[3], buffer[0] };
}
inline core::maths::Quaternionf convert(const physx::PxQuat val)
{
return core::maths::Quaternionf {val.w, val.x, val.y, val.z};
}
inline core::maths::Vector3f convert(const physx::PxVec3 val)
{
return core::maths::Vector3f {val.x, val.y, val.z};
}
inline core::maths::Vector3f convert(const physx::PxTransform val)
{
return core::maths::Vector3f {val.p.x, val.p.y, val.p.z};
}
inline core::maths::Vector3f convert(const physx::PxExtendedVec3 val)
{
return core::maths::Vector3f {(float) val.x, (float) val.y, (float) val.z};
}
}
}
#endif /* ENGINE_PHYSICS_HELPER_PHYSX_HPP */
| 23.314815 | 77 | 0.709293 | shossjer |
1f1a52d230d41f4071da52d70426260c3af197cc | 1,377 | hpp | C++ | lib/graph/chromatic_number.hpp | kuhaku-space/atcoder-lib | 7fe1365e1be69d3eff11e122b2c7dff997a6c541 | [
"Apache-2.0"
] | null | null | null | lib/graph/chromatic_number.hpp | kuhaku-space/atcoder-lib | 7fe1365e1be69d3eff11e122b2c7dff997a6c541 | [
"Apache-2.0"
] | 4 | 2022-01-05T14:40:40.000Z | 2022-03-05T08:03:19.000Z | lib/graph/chromatic_number.hpp | kuhaku-space/atcoder-lib | 7fe1365e1be69d3eff11e122b2c7dff997a6c541 | [
"Apache-2.0"
] | null | null | null | #include "graph/matrix_graph.hpp"
#include "template/template.hpp"
// 彩色数を求める
// O(2^N)
int chromatic_number(const matrix_graph<bool> &G) {
constexpr int64_t _MOD = (1LL << 31) - 1;
int n = G.size();
vector<int> neighbor(n, 0);
for (int i = 0; i < n; ++i) {
int s = 1 << i;
for (int j = 0; j < n; ++j) {
if (G[i][j]) s |= 1 << j;
}
neighbor[i] = s;
}
vector<int> v(1 << n);
v[0] = 1;
for (int s = 1; s < 1 << n; ++s) {
int c = __builtin_ctz(s);
v[s] = v[s & ~(1 << c)] + v[s & ~neighbor[c]];
}
auto _mod = [](int64_t a) -> int64_t {
a = (a & _MOD) + (a >> 31);
return a >= _MOD ? a - _MOD : a;
};
auto _pow = [](auto f, int64_t a, int n) {
int64_t res = 1;
for (; n > 0; n >>= 1) {
if (n & 1) res = f(res * a);
a = f(a * a);
}
return res;
};
int low = 0, high = n;
while (high - low > 1) {
int mid = (low + high) >> 1;
int64_t g = 0;
for (int s = 0; s < 1 << n; ++s) {
if ((n - __builtin_popcount(s)) & 1) g = _mod(g + _MOD - _pow(_mod, v[s], mid));
else g = _mod(g + _pow(_mod, v[s], mid));
}
if (g != 0) high = mid;
else low = mid;
}
return high;
}
| 27 | 93 | 0.394336 | kuhaku-space |
1f1afe595b2b65558b55df0399ddf865908340fc | 4,416 | cpp | C++ | test/unit/module/math/cosd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | test/unit/module/math/cosd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | test/unit/module/math/cosd.cpp | clayne/eve | dc268b5db474376e1c53f5a474f5bb42b7c4cb59 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/module/core.hpp>
#include <eve/module/core.hpp>
#include <eve/module/math.hpp>
#include <cmath>
#include <eve/detail/function/tmp/boost_math_cospi.hpp>
#include <eve/detail/function/tmp/boost_math_sinpi.hpp>
//==================================================================================================
// Types tests
// //==================================================================================================
// EVE_TEST_TYPES( "Check return types of cosd"
// , eve::test::simd::ieee_reals
// )
// <typename T>(eve::as<T>)
// {
// using v_t = eve::element_type_t<T>;
// TTS_EXPR_IS( eve::cosd(T()) , T);
// TTS_EXPR_IS( eve::cosd(v_t()), v_t);
// };
//==================================================================================================
//== cosd tests
//==================================================================================================
auto mquarter_c = []<typename T>(eve::as<T> const & ){ return T(-45); };
auto quarter_c = []<typename T>(eve::as<T> const & ){ return T( 45); };
auto mhalf_c = []<typename T>(eve::as<T> const & ){ return T(-90 ); };
auto half_c = []<typename T>(eve::as<T> const & ){ return T( 90 ); };
auto mmed = []<typename T>(eve::as<T> const & ){ return -5000; };
auto med = []<typename T>(eve::as<T> const & ){ return 5000; };
EVE_TEST( "Check behavior of cosd on wide"
, eve::test::simd::ieee_reals
, eve::test::generate( eve::test::randoms(mquarter_c, quarter_c)
, eve::test::randoms(mhalf_c, half_c)
, eve::test::randoms(mmed, med))
)
<typename T>(T const& a0, T const& a1, T const& a2)
{
using eve::detail::map;
using eve::cosd;
using eve::diff;
using eve::deginrad;
using v_t = eve::element_type_t<T>;
auto ref = [](auto e) -> v_t { return boost::math::cos_pi(e/180.0l); };
TTS_ULP_EQUAL(eve::quarter_circle(cosd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cosd)(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(eve::half_circle(cosd)(a1) , map(ref, a1), 30);
TTS_ULP_EQUAL(cosd(a0) , map(ref, a0), 2);
TTS_ULP_EQUAL(cosd(a1) , map(ref, a1), 30);
TTS_ULP_EQUAL(cosd(a2) , map(ref, a2), 420);
auto dinr = 1.7453292519943295769236907684886127134428718885417e-2l;
TTS_ULP_EQUAL(diff(cosd)(a0), map([dinr](auto e) -> v_t { return -dinr*boost::math::sin_pi(e/180.0l); }, a0), 2);
};
EVE_TEST_TYPES( "Check return types of cosd"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
TTS_ULP_EQUAL(eve::cosd(T(1)) , T(0.9998476951563912391570115588139148516927403105832) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(-1)) , T(0.9998476951563912391570115588139148516927403105832) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(45.0)) , T(0.70710678118654752440084436210484903928483593768847) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(-T(45.0)) , T(0.70710678118654752440084436210484903928483593768847) , 0.5 );
TTS_ULP_EQUAL(eve::cosd(T(-500.0)) , T(-0.7660444431189780352023926505554166739358324570804) , 3.5 );
TTS_ULP_EQUAL(eve::cosd(T(500.0)) , T(-0.7660444431189780352023926505554166739358324570804) , 3.5 );
// using v_t = eve::element_type_t<T>;
// if constexpr(eve::cardinal_v<T> == 1)
// {
// // TTS_ULP_EQUAL(eve::cosd(T(-89.9948004)) , T(9.0750139662133702308589680368087310425111681700988e-5l) , 3.5 );
// T x(-3870.0014720); //-87.2292316); ///*(-89.9948004); /*/(+24.2768812);
// TTS_ULP_EQUAL(eve::cosd(x), map([](auto e) -> v_t { return boost::math::cos_pi(((long double)e)/180.0l); }, x), 2);
// TTS_ULP_EQUAL(eve::cospi(x), T(2.5691246586530322324691158981079804836564072146655e-5), 2);
// }
// else TTS_PASS("***");
// // eve::wide < v_t, eve::fixed < 4>> u{-3870.0014720, +856.9305370, -1459.2691069, +11.4976682};
// // TTS_ULP_EQUAL(eve::cosd(u), map([](auto e) -> v_t { return boost::math::cos_pi(((long double)e)/180.0l); }, u), 2);
};
| 49.066667 | 125 | 0.52808 | clayne |
1f1e93e0df42d30a99c04fc4bf35157a42a2abe7 | 2,428 | cpp | C++ | registerwidget/borrowerregister.cpp | winthegame9/cpp-libsystem | 4346dbb1aa22464e1ce26d8f3f53311411eac9f3 | [
"Apache-2.0"
] | null | null | null | registerwidget/borrowerregister.cpp | winthegame9/cpp-libsystem | 4346dbb1aa22464e1ce26d8f3f53311411eac9f3 | [
"Apache-2.0"
] | null | null | null | registerwidget/borrowerregister.cpp | winthegame9/cpp-libsystem | 4346dbb1aa22464e1ce26d8f3f53311411eac9f3 | [
"Apache-2.0"
] | null | null | null | #include "borrowerregister.h"
#include "ui_borrowerregister.h"
#include "dialogs/persondialog.h"
#include <QMessageBox>
#include <QDebug>
BorrowerRegister::BorrowerRegister(QWidget *parent) :
QWidget(parent),
ui(new Ui::BorrowerRegister)
{
ui->setupUi(this);
listModel = new PersonListModel(lib::Borrower, this);
ui->listView->setModel(listModel);
setDeregisterButtonEnabled(false);
connect(this, &BorrowerRegister::itemInsert,
listModel, &PersonListModel::whenItemInserted);
connect(this, &BorrowerRegister::itemUpdate,
listModel, &PersonListModel::whenItemUpdated);
}
BorrowerRegister::~BorrowerRegister()
{
delete ui;
}
void BorrowerRegister::setDeregisterButtonEnabled(bool enable)
{
ui->buttonDeregister->setEnabled(enable);
}
lib::Person BorrowerRegister::getCurrent() const
{
return current;
}
void BorrowerRegister::loadFromDB(QVector<lib::Person> items)
{
if(items.size() > 0) {
qDebug() << "loading borrowers from database";
listModel->loadFromDB(items);
}
qDebug() << "no borrowers from database";
}
void BorrowerRegister::on_listView_clicked(const QModelIndex &index)
{
current = index.data(Qt::UserRole).value<lib::Person>();
if(current.getDeregistered().isValid()) {
setDeregisterButtonEnabled(false);
} else {
setDeregisterButtonEnabled(true);
}
emit itemSelectionChanged(current);
}
void BorrowerRegister::on_buttonRegister_clicked()
{
// create a dialog for role lib::Borrower
PersonDialog dialog(lib::Borrower, this);
connect(&dialog, &PersonDialog::personCreated,
this, &BorrowerRegister::whenPersonCreated);
dialog.exec();
}
void BorrowerRegister::on_buttonDeregister_clicked()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,
tr("Deregister person"),
tr("Deregister selected person?"),
QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes) {
current.setDeregistered(QDate::currentDate());
setDeregisterButtonEnabled(false);
emit itemUpdate(current);
}
}
void BorrowerRegister::whenPersonCreated(lib::Person person)
{
emit itemInsert(person);
}
void BorrowerRegister::whenPersonInsertedFromMain(lib::Person person)
{
emit itemInsert(person);
}
| 25.557895 | 70 | 0.679572 | winthegame9 |
1f1eb1e9a3340a4d227c687af9f77386d1cf9853 | 6,726 | cpp | C++ | brlycmbd/CrdBrlyUsg/PnlBrlyUsgRec.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyUsg/PnlBrlyUsgRec.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyUsg/PnlBrlyUsgRec.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | /**
* \file PnlBrlyUsgRec.cpp
* job handler for job PnlBrlyUsgRec (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 11 Jan 2021
*/
// IP header --- ABOVE
#ifdef BRLYCMBD
#include <Brlycmbd.h>
#else
#include <Brlyd.h>
#endif
#include "PnlBrlyUsgRec.h"
#include "PnlBrlyUsgRec_blks.cpp"
#include "PnlBrlyUsgRec_evals.cpp"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
// IP ns.cust --- INSERT
/******************************************************************************
class PnlBrlyUsgRec
******************************************************************************/
PnlBrlyUsgRec::PnlBrlyUsgRec(
XchgBrly* xchg
, DbsBrly* dbsbrly
, const ubigint jrefSup
, const uint ixBrlyVLocale
) :
JobBrly(xchg, VecBrlyVJob::PNLBRLYUSGREC, jrefSup, ixBrlyVLocale)
{
jref = xchg->addJob(dbsbrly, this, jrefSup);
pnlmnuser = NULL;
pnlaaccess = NULL;
pnldetail = NULL;
// IP constructor.cust1 --- INSERT
// IP constructor.cust2 --- INSERT
// IP constructor.cust3 --- INSERT
updatePreset(dbsbrly, VecBrlyVPreset::PREBRLYREFUSG, jref);
};
PnlBrlyUsgRec::~PnlBrlyUsgRec() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
DpchEngBrly* PnlBrlyUsgRec::getNewDpchEng(
set<uint> items
) {
DpchEngBrly* dpcheng = NULL;
if (items.empty()) {
dpcheng = new DpchEngBrlyConfirm(true, jref, "");
} else {
insert(items, DpchEngData::JREF);
dpcheng = new DpchEngData(jref, &continf, &statshr, items);
};
return dpcheng;
};
void PnlBrlyUsgRec::refresh(
DbsBrly* dbsbrly
, set<uint>& moditems
, const bool unmute
) {
if (muteRefresh && !unmute) return;
muteRefresh = true;
ContInf oldContinf(continf);
StatShr oldStatshr(statshr);
// IP refresh --- BEGIN
// continf
continf.TxtRef = StubBrly::getStubUsgStd(dbsbrly, recUsg.ref, ixBrlyVLocale, Stub::VecVNonetype::FULL);
// statshr
if (recUsg.ref == 0) statshr.ixBrlyVExpstate = VecBrlyVExpstate::MIND;
statshr.ButRegularizeActive = evalButRegularizeActive(dbsbrly);
if (statshr.ixBrlyVExpstate == VecBrlyVExpstate::MIND) {
if (pnldetail) {delete pnldetail; pnldetail = NULL;};
if (pnlaaccess) {delete pnlaaccess; pnlaaccess = NULL;};
if (pnlmnuser) {delete pnlmnuser; pnlmnuser = NULL;};
} else {
if (!pnldetail) pnldetail = new PnlBrlyUsgDetail(xchg, dbsbrly, jref, ixBrlyVLocale);
if (!pnlaaccess) pnlaaccess = new PnlBrlyUsgAAccess(xchg, dbsbrly, jref, ixBrlyVLocale);
if (!pnlmnuser) pnlmnuser = new PnlBrlyUsgMNUser(xchg, dbsbrly, jref, ixBrlyVLocale);
};
statshr.jrefDetail = ((pnldetail) ? pnldetail->jref : 0);
statshr.jrefAAccess = ((pnlaaccess) ? pnlaaccess->jref : 0);
statshr.jrefMNUser = ((pnlmnuser) ? pnlmnuser->jref : 0);
// IP refresh --- END
if (continf.diff(&oldContinf).size() != 0) insert(moditems, DpchEngData::CONTINF);
if (statshr.diff(&oldStatshr).size() != 0) insert(moditems, DpchEngData::STATSHR);
muteRefresh = false;
};
void PnlBrlyUsgRec::updatePreset(
DbsBrly* dbsbrly
, const uint ixBrlyVPreset
, const ubigint jrefTrig
, const bool notif
) {
// IP updatePreset --- BEGIN
set<uint> moditems;
if (ixBrlyVPreset == VecBrlyVPreset::PREBRLYREFUSG) {
BrlyMUsergroup* _recUsg = NULL;
if (dbsbrly->tblbrlymusergroup->loadRecByRef(xchg->getRefPreset(VecBrlyVPreset::PREBRLYREFUSG, jref), &_recUsg)) {
recUsg = *_recUsg;
delete _recUsg;
} else recUsg = BrlyMUsergroup();
if (recUsg.ref != 0) {
if (pnldetail) pnldetail->updatePreset(dbsbrly, ixBrlyVPreset, jrefTrig, notif);
if (pnlaaccess) pnlaaccess->updatePreset(dbsbrly, ixBrlyVPreset, jrefTrig, notif);
if (pnlmnuser) pnlmnuser->updatePreset(dbsbrly, ixBrlyVPreset, jrefTrig, notif);
};
refresh(dbsbrly, moditems);
if (notif && !moditems.empty()) xchg->submitDpch(getNewDpchEng(moditems));
};
// IP updatePreset --- END
};
void PnlBrlyUsgRec::minimize(
DbsBrly* dbsbrly
, const bool notif
, DpchEngBrly** dpcheng
) {
set<uint> moditems;
if (statshr.ixBrlyVExpstate != VecBrlyVExpstate::MIND) {
statshr.ixBrlyVExpstate = VecBrlyVExpstate::MIND;
insert(moditems, DpchEngData::STATSHR);
refresh(dbsbrly, moditems);
};
if (notif) {
if (dpcheng) *dpcheng = getNewDpchEng(moditems);
else if (!moditems.empty()) xchg->submitDpch(getNewDpchEng(moditems));
};
};
void PnlBrlyUsgRec::regularize(
DbsBrly* dbsbrly
, const bool notif
, DpchEngBrly** dpcheng
) {
set<uint> moditems;
if (statshr.ixBrlyVExpstate != VecBrlyVExpstate::REGD) {
statshr.ixBrlyVExpstate = VecBrlyVExpstate::REGD;
insert(moditems, DpchEngData::STATSHR);
refresh(dbsbrly, moditems);
};
if (notif) {
if (dpcheng) *dpcheng = getNewDpchEng(moditems);
else if (!moditems.empty()) xchg->submitDpch(getNewDpchEng(moditems));
};
};
void PnlBrlyUsgRec::handleRequest(
DbsBrly* dbsbrly
, ReqBrly* req
) {
if (req->ixVBasetype == ReqBrly::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
} else if (req->ixVBasetype == ReqBrly::VecVBasetype::DPCHAPP) {
if (req->dpchapp->ixBrlyVDpch == VecBrlyVDpch::DPCHAPPBRLYINIT) {
handleDpchAppBrlyInit(dbsbrly, (DpchAppBrlyInit*) (req->dpchapp), &(req->dpcheng));
} else if (req->dpchapp->ixBrlyVDpch == VecBrlyVDpch::DPCHAPPBRLYUSGRECDO) {
DpchAppDo* dpchappdo = (DpchAppDo*) (req->dpchapp);
if (dpchappdo->ixVDo != 0) {
if (dpchappdo->ixVDo == VecVDo::BUTMINIMIZECLICK) {
handleDpchAppDoButMinimizeClick(dbsbrly, &(req->dpcheng));
} else if (dpchappdo->ixVDo == VecVDo::BUTREGULARIZECLICK) {
handleDpchAppDoButRegularizeClick(dbsbrly, &(req->dpcheng));
};
};
};
};
};
void PnlBrlyUsgRec::handleDpchAppBrlyInit(
DbsBrly* dbsbrly
, DpchAppBrlyInit* dpchappbrlyinit
, DpchEngBrly** dpcheng
) {
*dpcheng = getNewDpchEng({DpchEngData::ALL});
};
void PnlBrlyUsgRec::handleDpchAppDoButMinimizeClick(
DbsBrly* dbsbrly
, DpchEngBrly** dpcheng
) {
minimize(dbsbrly, true, dpcheng);
};
void PnlBrlyUsgRec::handleDpchAppDoButRegularizeClick(
DbsBrly* dbsbrly
, DpchEngBrly** dpcheng
) {
regularize(dbsbrly, true, dpcheng);
};
void PnlBrlyUsgRec::handleCall(
DbsBrly* dbsbrly
, Call* call
) {
if (call->ixVCall == VecBrlyVCall::CALLBRLYUSGUPD_REFEQ) {
call->abort = handleCallBrlyUsgUpd_refEq(dbsbrly, call->jref);
};
};
bool PnlBrlyUsgRec::handleCallBrlyUsgUpd_refEq(
DbsBrly* dbsbrly
, const ubigint jrefTrig
) {
bool retval = false;
// IP handleCallBrlyUsgUpd_refEq --- INSERT
return retval;
};
| 25.574144 | 116 | 0.684954 | mpsitech |
1f23c11bab6091dd70ae53585057c8dc71bbfb14 | 855 | cpp | C++ | scripting/lua/ScutControls/Win32/myWin32WebView.cpp | ScutGame/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | 23 | 2015-01-28T12:41:43.000Z | 2021-07-14T05:35:56.000Z | scripting/lua/ScutControls/Win32/myWin32WebView.cpp | HongXiao/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | null | null | null | scripting/lua/ScutControls/Win32/myWin32WebView.cpp | HongXiao/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | 35 | 2015-02-04T10:01:00.000Z | 2021-03-05T15:27:14.000Z | #include "Win32WebView.h"
#include "cocos2d.h"
#include "myWin32WebView.h"
namespace NdCxControl
{
void *Win32WebView(const char *pszUrl, cocos2d::CCRect rcScreenFrame, const char *pszTitle, const char *pszNormal, const char *pszPushDown)
{
CWin32WebView *pWebView = new CWin32WebView();
if(pWebView && pWebView->init(pszUrl, rcScreenFrame, pszTitle, pszNormal, pszPushDown))
{
return pWebView;
}
else
{
if (pWebView)
{
delete pWebView;
}
return NULL;
}
}
void CloseWin32WebView(void *pWebView)
{
if (pWebView)
{
CWin32WebView *pView = (CWin32WebView*)pWebView;
pView->close();
}
}
void SwitchWin32WebViewUrl(void *pWebView, const char *pszUrl)
{
if (pWebView)
{
CWin32WebView *pView = (CWin32WebView*)pWebView;
pView->switchUrl(pszUrl);
}
}
} | 20.357143 | 141 | 0.654971 | ScutGame |
1f263b9edbcfca1a85f53837cb55d2c013497e61 | 1,607 | cpp | C++ | Nacro/SDK/FN_SpeechBubbleWidget_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_SpeechBubbleWidget_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_SpeechBubbleWidget_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | // Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function SpeechBubbleWidget.SpeechBubbleWidget_C.InitFromObject
// (Event, Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UObject* InitObject (Parm, ZeroConstructor, IsPlainOldData)
void USpeechBubbleWidget_C::InitFromObject(class UObject* InitObject)
{
static auto fn = UObject::FindObject<UFunction>("Function SpeechBubbleWidget.SpeechBubbleWidget_C.InitFromObject");
USpeechBubbleWidget_C_InitFromObject_Params params;
params.InitObject = InitObject;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SpeechBubbleWidget.SpeechBubbleWidget_C.ExecuteUbergraph_SpeechBubbleWidget
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void USpeechBubbleWidget_C::ExecuteUbergraph_SpeechBubbleWidget(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function SpeechBubbleWidget.SpeechBubbleWidget_C.ExecuteUbergraph_SpeechBubbleWidget");
USpeechBubbleWidget_C_ExecuteUbergraph_SpeechBubbleWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 26.783333 | 137 | 0.679527 | Milxnor |
1f2a00d5500b776e4c4e83265b682523580237c6 | 1,258 | cpp | C++ | EZOJ/Contests/1276/C.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 6 | 2019-09-30T16:11:00.000Z | 2021-11-01T11:42:33.000Z | EZOJ/Contests/1276/C.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-11-21T08:17:42.000Z | 2020-07-28T12:09:52.000Z | EZOJ/Contests/1276/C.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-07-26T05:54:06.000Z | 2020-09-30T13:35:38.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cmath>
#include <vector>
using namespace std;
typedef long long lint;
inline bool is_num(char c){
return c>='0'&&c<='9';
}
inline int ni(){
int i=0;char c;
while(!is_num(c=getchar()));
while(i=i*10-'0'+c,is_num(c=getchar()));
return i;
}
inline long long nl(){
long long i=0;char c;
while(!is_num(c=getchar()));
while(i=i*10-'0'+c,is_num(c=getchar()));
return i;
}
const int K=65;
const lint N=1000000000000000010ll;
vector<lint>f[K];
inline lint solve2(lint n){
lint i=(sqrt(n*8+1)-1)/2;
for(;i*(i+1)<n*2;i++);
return i;
}
inline int solve(lint n,vector<lint>&f){
int l=0,r=f.size()-1,mid;
while(l<r){
mid=(l+r)>>1;
if(f[mid]<n){
l=mid+1;
}else{
r=mid;
}
}
return l;
}
int main(){
f[3].push_back(0);
for(int i=1;f[3].back()<N;i++){
f[3].push_back(f[3][i-1]+(lint)i*(i-1)/2+1);
}
for(int i=4;i<K;i++){
f[i].push_back(0);
for(int j=1;f[i].back()<N;j++){
f[i].push_back(f[i][j-1]+f[i-1][j-1]+1);
}
}
lint n;
int k;
for(int tot=ni();tot--;){
n=nl(),k=ni();
if(n==0){
puts("0");
}else if(k==1){
printf("%lld\n",n);
}else if(k==2){
printf("%lld\n",solve2(n));
}else{
printf("%d\n",solve(n,f[k]));
}
}
}
| 17.971429 | 46 | 0.566773 | sshockwave |
1f2d106268014876fff0e7d309e9a757540c0297 | 8,055 | cpp | C++ | src/software/world/world_test.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/world/world_test.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/world/world_test.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | #include "software/world/world.h"
#include <gtest/gtest.h>
#include <include/gmock/gmock-matchers.h>
#include "proto/message_translation/tbots_protobuf.h"
#include "shared/parameter/cpp_dynamic_parameters.h"
#include "software/test_util/test_util.h"
class WorldTest : public ::testing::Test
{
protected:
WorldTest()
: current_time(Timestamp::fromSeconds(123)),
field(Field::createSSLDivisionBField()),
ball(Point(1, 2), Vector(-0.3, 0), current_time),
friendly_team(Duration::fromMilliseconds(1000)),
enemy_team(Duration::fromMilliseconds(1000)),
world(field, ball, friendly_team, enemy_team)
{
}
void SetUp() override
{
// An arbitrary fixed point in time
// We use this fixed point in time to make the tests deterministic.
Robot friendly_robot_0 = Robot(0, Point(0, 1), Vector(-1, -2), Angle::half(),
AngularVelocity::threeQuarter(), current_time);
Robot friendly_robot_1 = Robot(1, Point(3, -1), Vector(), Angle::zero(),
AngularVelocity::zero(), current_time);
friendly_team.updateRobots({friendly_robot_0, friendly_robot_1});
friendly_team.assignGoalie(1);
Robot enemy_robot_0 = Robot(0, Point(0.5, -2.5), Vector(), Angle::fromRadians(1),
AngularVelocity::fromRadians(2), current_time);
Robot enemy_robot_1 = Robot(1, Point(), Vector(-0.5, 4), Angle::quarter(),
AngularVelocity::half(), current_time);
enemy_team.updateRobots({enemy_robot_0, enemy_robot_1});
enemy_team.assignGoalie(0);
// Construct the world with arguments
world = World(field, ball, friendly_team, enemy_team);
}
Timestamp current_time;
Field field;
Ball ball;
Team friendly_team;
Team enemy_team;
World world;
};
TEST_F(WorldTest, construction_with_parameters)
{
// Check that objects used for construction are returned by the accessors
EXPECT_EQ(field, world.field());
EXPECT_EQ(ball, world.ball());
EXPECT_EQ(friendly_team, world.friendlyTeam());
EXPECT_EQ(enemy_team, world.enemyTeam());
}
TEST_F(WorldTest, construct_with_protobuf)
{
auto world_proto = createWorld(world);
World proto_converted_world(*world_proto);
// Can not compare the two World objects since TbotsProto::Team does not store the
// robot_expiry_buffer_duration
EXPECT_EQ(world.field(), proto_converted_world.field());
EXPECT_EQ(world.ball(), proto_converted_world.ball());
EXPECT_EQ(world.gameState(), proto_converted_world.gameState());
EXPECT_EQ(world.enemyTeam().getGoalieId(),
proto_converted_world.enemyTeam().getGoalieId());
EXPECT_THAT(
world.friendlyTeam().getAllRobots(),
::testing::ContainerEq(proto_converted_world.friendlyTeam().getAllRobots()));
EXPECT_THAT(world.enemyTeam().getAllRobots(),
::testing::ContainerEq(proto_converted_world.enemyTeam().getAllRobots()));
}
// Test that most recent timestamp from member objects works
TEST_F(WorldTest, get_most_recent_timestamp_from_members)
{
EXPECT_EQ(world.getMostRecentTimestamp(), current_time);
}
TEST_F(WorldTest, equality_basic_tests)
{
World world1 = world;
World world2 = world;
EXPECT_EQ(world1, world2);
EXPECT_EQ(world2, world1);
EXPECT_EQ(world1, world1);
}
TEST_F(WorldTest, equality_different_timestamp)
{
World world1 = world;
World world3 = world;
world3.updateTimestamp(current_time + Duration::fromSeconds(100));
EXPECT_EQ(world1, world3);
}
TEST_F(WorldTest, equality_different_ball)
{
World world1 = world;
Ball ball = Ball(Point(1, 0), Vector(13, 0), Timestamp::fromSeconds(0));
Team friendly_team = Team(Duration::fromMilliseconds(0));
Team enemy_team = Team(Duration::fromMilliseconds(0));
World world2 = World(field, ball, friendly_team, enemy_team);
EXPECT_NE(world1, world2);
}
TEST_F(WorldTest, equality_different_field)
{
Field field1 = field;
Field field2 = Field(2, 5, 3, 1, 3, 1, 2, 8);
Ball ball = Ball(Point(0, 0), Vector(0, 0), Timestamp::fromSeconds(0));
Team friendly_team = Team(Duration::fromMilliseconds(0));
Team enemy_team = Team(Duration::fromMilliseconds(0));
World world1 = World(field1, ball, friendly_team, enemy_team);
World world2 = World(field2, ball, friendly_team, enemy_team);
EXPECT_NE(world1, world2);
}
TEST_F(WorldTest, equality_different_friendly_team)
{
World world1 = world;
Ball ball = Ball(Point(0, 0), Vector(0, 0), Timestamp::fromSeconds(0));
Team friendly_team = Team(Duration::fromMilliseconds(1500));
Team enemy_team = Team(Duration::fromMilliseconds(0));
World world2 = World(field, ball, friendly_team, enemy_team);
EXPECT_NE(world1, world2);
}
TEST_F(WorldTest, equality_different_enemy_team)
{
World world1 = world;
Ball ball = Ball(Point(0, 0), Vector(0, 0), Timestamp::fromSeconds(0));
Team friendly_team = Team(Duration::fromMilliseconds(0));
Team enemy_team = Team(Duration::fromMilliseconds(1300));
World world2 = World(field, ball, friendly_team, enemy_team);
EXPECT_NE(world1, world2);
}
TEST_F(WorldTest, update_referee_command)
{
world.updateRefereeCommand(RefereeCommand::HALT);
EXPECT_EQ(world.gameState().getRefereeCommand(), RefereeCommand::HALT);
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE - 1; i++)
{
world.updateRefereeCommand(RefereeCommand::FORCE_START);
EXPECT_NE(world.gameState().getRefereeCommand(), RefereeCommand::FORCE_START);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE; i++)
{
world.updateRefereeCommand(RefereeCommand::FORCE_START);
EXPECT_EQ(world.gameState().getRefereeCommand(), RefereeCommand::FORCE_START);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE - 1; i++)
{
world.updateRefereeCommand(RefereeCommand::BALL_PLACEMENT_US, Point(0, 0));
EXPECT_NE(world.gameState().getRefereeCommand(),
RefereeCommand::BALL_PLACEMENT_US);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE; i++)
{
world.updateRefereeCommand(RefereeCommand::BALL_PLACEMENT_US, Point(0, 0));
EXPECT_EQ(world.gameState().getRefereeCommand(),
RefereeCommand::BALL_PLACEMENT_US);
}
}
TEST_F(WorldTest, update_referee_stage)
{
world.updateRefereeStage(RefereeStage::NORMAL_FIRST_HALF_PRE);
EXPECT_EQ(world.getRefereeStage(), RefereeStage::NORMAL_FIRST_HALF_PRE);
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE - 1; i++)
{
world.updateRefereeStage(RefereeStage::NORMAL_FIRST_HALF);
EXPECT_NE(world.getRefereeStage(), RefereeStage::NORMAL_FIRST_HALF);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE; i++)
{
world.updateRefereeStage(RefereeStage::NORMAL_FIRST_HALF);
EXPECT_EQ(world.getRefereeStage(), RefereeStage::NORMAL_FIRST_HALF);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE - 1; i++)
{
world.updateRefereeStage(RefereeStage::NORMAL_SECOND_HALF_PRE);
EXPECT_NE(world.getRefereeStage(), RefereeStage::NORMAL_SECOND_HALF_PRE);
}
for (unsigned int i = 0; i < World::REFEREE_COMMAND_BUFFER_SIZE; i++)
{
world.updateRefereeStage(RefereeStage::NORMAL_SECOND_HALF_PRE);
EXPECT_EQ(world.getRefereeStage(), RefereeStage::NORMAL_SECOND_HALF_PRE);
}
}
TEST_F(WorldTest, set_team_with_possession)
{
world.setTeamWithPossession(TeamSide::FRIENDLY);
EXPECT_EQ(world.getTeamWithPossession(), TeamSide::FRIENDLY);
world.setTeamWithPossession(TeamSide::ENEMY);
EXPECT_EQ(world.getTeamWithPossession(), TeamSide::ENEMY);
}
| 37.119816 | 90 | 0.681688 | jonl112 |
1f2fa872325ae64e4492f854c686f00b07153594 | 2,734 | cpp | C++ | Nagi/Source/Input/Keyboard.cpp | nfginola/VkPlayground | b512117f47497d2c8f24b501e9fd3d8861504187 | [
"MIT"
] | 1 | 2022-01-09T05:30:29.000Z | 2022-01-09T05:30:29.000Z | Nagi/Source/Input/Keyboard.cpp | nfginola/VkPlayground | b512117f47497d2c8f24b501e9fd3d8861504187 | [
"MIT"
] | null | null | null | Nagi/Source/Input/Keyboard.cpp | nfginola/VkPlayground | b512117f47497d2c8f24b501e9fd3d8861504187 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Input/Keyboard.h"
#include <GLFW/glfw3.h>
namespace Nagi
{
Keyboard::Keyboard()
{
}
void Keyboard::handleKeyEvent(GLFWwindow* win, int key, int scancode, int action, int mods)
{
// Perhaps we can add an intermediary between GLFW and Keyboard.
// This way, only the intermediary knows about GLFW and Keyboard while Keyboard doesn't have to know about GLFW
// but it will add complexity since we would have to maintain the intermediary in the case of added functionality
// Save it for sometime later maybe
if (key == GLFW_KEY_Q) handleKeyAction(KeyName::Q, action);
if (key == GLFW_KEY_W) handleKeyAction(KeyName::W, action);
if (key == GLFW_KEY_E) handleKeyAction(KeyName::E, action);
if (key == GLFW_KEY_R) handleKeyAction(KeyName::R, action);
if (key == GLFW_KEY_T) handleKeyAction(KeyName::T, action);
if (key == GLFW_KEY_Y) handleKeyAction(KeyName::Y, action);
if (key == GLFW_KEY_U) handleKeyAction(KeyName::U, action);
if (key == GLFW_KEY_I) handleKeyAction(KeyName::I, action);
if (key == GLFW_KEY_O) handleKeyAction(KeyName::O, action);
if (key == GLFW_KEY_P) handleKeyAction(KeyName::P, action);
if (key == GLFW_KEY_A) handleKeyAction(KeyName::A, action);
if (key == GLFW_KEY_S) handleKeyAction(KeyName::S, action);
if (key == GLFW_KEY_D) handleKeyAction(KeyName::D, action);
if (key == GLFW_KEY_F) handleKeyAction(KeyName::F, action);
if (key == GLFW_KEY_G) handleKeyAction(KeyName::G, action);
if (key == GLFW_KEY_H) handleKeyAction(KeyName::H, action);
if (key == GLFW_KEY_J) handleKeyAction(KeyName::J, action);
if (key == GLFW_KEY_K) handleKeyAction(KeyName::K, action);
if (key == GLFW_KEY_L) handleKeyAction(KeyName::L, action);
if (key == GLFW_KEY_Z) handleKeyAction(KeyName::Z, action);
if (key == GLFW_KEY_X) handleKeyAction(KeyName::X, action);
if (key == GLFW_KEY_C) handleKeyAction(KeyName::C, action);
if (key == GLFW_KEY_V) handleKeyAction(KeyName::V, action);
if (key == GLFW_KEY_B) handleKeyAction(KeyName::B, action);
if (key == GLFW_KEY_N) handleKeyAction(KeyName::N, action);
if (key == GLFW_KEY_M) handleKeyAction(KeyName::M, action);
if (key == GLFW_KEY_SPACE) handleKeyAction(KeyName::Space, action);
if (key == GLFW_KEY_LEFT_SHIFT) handleKeyAction(KeyName::LShift, action);
}
bool Keyboard::isKeyDown(KeyName key)
{
return m_keyStates[key].isDown();
}
bool Keyboard::isKeyPressed(KeyName key)
{
return m_keyStates[key].justPressed();
}
void Keyboard::handleKeyAction(KeyName key, int action)
{
if (action == GLFW_PRESS)
m_keyStates[key].onPress();
else if (action == GLFW_RELEASE)
m_keyStates[key].onRelease();
}
}
| 38.507042 | 115 | 0.70117 | nfginola |
1f31d6fd566d687bc8afbb8baca1657844ef5628 | 8,665 | hpp | C++ | src/area776.hpp | r6eve/area776 | c39b9d2393a7cdaaa056933fa452ec9adfc8fdce | [
"BSL-1.0"
] | null | null | null | src/area776.hpp | r6eve/area776 | c39b9d2393a7cdaaa056933fa452ec9adfc8fdce | [
"BSL-1.0"
] | 1 | 2018-06-02T05:38:40.000Z | 2018-06-02T07:47:41.000Z | src/area776.hpp | r6eve/area776 | c39b9d2393a7cdaaa056933fa452ec9adfc8fdce | [
"BSL-1.0"
] | null | null | null | //
// Copyright r6eve 2019 -
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include <iomanip>
#include <memory>
#include <sstream>
#include "boss.hpp"
#include "def_global.hpp"
#include "effect.hpp"
#include "enemy.hpp"
#include "fighter.hpp"
#include "font_manager.hpp"
#include "image_manager.hpp"
#include "input_manager.hpp"
#include "mixer_manager.hpp"
#include "snow.hpp"
#include "wipe.hpp"
struct RGB {
Uint8 r;
Uint8 g;
Uint8 b;
};
namespace rgb {
const RGB black = RGB{0x00, 0x00, 0x00};
const RGB red = RGB{0xff, 0x00, 0x00};
const RGB dark_red = RGB{0xb0, 0x00, 0x00};
const RGB green = RGB{0x00, 0xff, 0x00};
const RGB white = RGB{0xff, 0xff, 0xff};
} // namespace rgb
class Area776 {
enum class game_state {
title,
start,
clear,
playing,
gameover,
pause,
};
const bool fullscreen_mode_;
const bool debug_mode_;
SDL_Window *window_;
SDL_Renderer *renderer_;
int blink_count_;
int game_count_;
game_state game_state_;
int game_level_;
enemy_type enemy_select_;
std::unique_ptr<ImageManager> image_manager_;
std::unique_ptr<InputManager> input_manager_;
std::unique_ptr<MixerManager> mixer_manager_;
std::unique_ptr<Fighter> fighter_;
std::unique_ptr<Enemies> enemies_;
std::unique_ptr<Boss> boss_;
std::unique_ptr<Effects> effects_;
std::unique_ptr<Wipe> wipe_;
std::unique_ptr<Snow> snow_;
FontManager font_manager_;
void game_title() noexcept;
void game_start() noexcept;
void play_game() noexcept;
void game_clear() noexcept;
void game_over() noexcept;
void game_pause() noexcept;
inline void draw_text(const unsigned char font_size, const RGB &rgb,
const Point &p, const char *str) const noexcept {
const SDL_Color color = {rgb.r, rgb.g, rgb.b, 255};
SDL_Surface *font_surface =
TTF_RenderUTF8_Blended(font_manager_.get(font_size), str, color);
SDL_Texture *font_texture =
SDL_CreateTextureFromSurface(renderer_, font_surface);
const SDL_Rect src = {0, 0, static_cast<Uint16>(font_surface->w),
static_cast<Uint16>(font_surface->h)};
SDL_Rect dst;
dst.x = static_cast<Sint16>(p.x);
dst.y = static_cast<Sint16>(p.y);
SDL_QueryTexture(font_texture, nullptr, nullptr, &dst.w, &dst.h);
SDL_RenderCopy(renderer_, font_texture, &src, &dst);
SDL_DestroyTexture(font_texture);
}
inline void draw_text(const unsigned char font_size, const RGB &&rgb,
const Point &p, const char *str) const noexcept {
draw_text(font_size, rgb, p, str);
}
inline void draw_text(const unsigned char font_size, const RGB &rgb,
const Point &&p, const char *str) const noexcept {
draw_text(font_size, rgb, p, str);
}
inline void draw_text(const unsigned char font_size, const RGB &&rgb,
const Point &&p, const char *str) const noexcept {
draw_text(font_size, rgb, p, str);
}
inline void draw_life() noexcept {
switch (enemy_select_) {
case enemy_type::enemy: {
std::stringstream ss;
ss << "ENEMY LIFE: " << enemies_->get_life();
draw_text(font_size::x16, rgb::white, Point{32, 24}, ss.str().c_str());
break;
}
case enemy_type::boss: {
std::stringstream ss;
ss << "BOSS LIFE: " << boss_->get_life();
draw_text(font_size::x16, rgb::white, Point{32, 24}, ss.str().c_str());
break;
}
}
std::stringstream ss;
ss << "LIFE: " << fighter_->get_life();
draw_text(font_size::x16, rgb::white, fighter_->get_pos() + Point{0, 55},
ss.str().c_str());
}
inline bool poll_event() noexcept {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_ESCAPE) {
return false;
}
break;
default:
// do nothing
break;
}
}
return true;
}
inline void wait_game() noexcept {
static Uint32 pre_count;
const double wait_time = 1000.0 / screen::max_fps;
const Uint32 wait_count = (wait_time + 0.5);
if (pre_count) {
const Uint32 now_count = SDL_GetTicks();
const Uint32 interval = now_count - pre_count;
if (interval < wait_count) {
const Uint32 delay_time = wait_count - interval;
SDL_Delay(delay_time);
}
}
pre_count = SDL_GetTicks();
}
inline void draw_fps() noexcept {
static Uint32 pre_count;
const Uint32 now_count = SDL_GetTicks();
if (pre_count) {
static double frame_rate;
Uint32 mut_interval = now_count - pre_count;
if (mut_interval < 1) {
mut_interval = 1;
}
const Uint32 interval = mut_interval;
if (!(pre_count % 30)) {
frame_rate = 1000.0 / interval;
}
std::stringstream ss;
ss << "FrameRate[" << std::setprecision(2)
<< std::setiosflags(std::ios::fixed) << frame_rate << "]";
draw_text(font_size::x16, rgb::green, Point{screen::width - 140, 16},
ss.str().c_str());
}
pre_count = now_count;
}
inline void draw_map() noexcept {
SDL_Texture *map_texture = image_manager_->get(image::map);
const SDL_Rect src = {0, 0, screen::width, screen::height};
const SDL_Rect dst = {0, 0, screen::width, screen::height};
SDL_RenderCopy(renderer_, map_texture, &src, &dst);
SDL_DestroyTexture(map_texture);
}
inline void draw_translucence() noexcept {
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
SDL_Surface *trans_surface =
SDL_CreateRGBSurface(SDL_SWSURFACE, screen::width, screen::height, 32,
rmask, gmask, bmask, amask);
if (trans_surface == nullptr) {
std::cerr << "CreateRGBSurface failed: " << SDL_GetError() << '\n';
exit(EXIT_FAILURE);
}
SDL_Texture *trans_texture =
SDL_CreateTextureFromSurface(renderer_, trans_surface);
SDL_FreeSurface(trans_surface);
const SDL_Rect src = {0, 0, screen::width, screen::height};
const SDL_Rect dst = {0, 0, screen::width, screen::height};
SDL_RenderCopy(renderer_, trans_texture, &src, &dst);
SDL_DestroyTexture(trans_texture);
if (blink_count_ < 30) {
draw_text(font_size::x36, rgb::white, Point{220, 180}, "P a u s e");
++blink_count_;
} else if (blink_count_ < 60) {
++blink_count_;
} else {
blink_count_ = 0;
}
}
public:
Area776(const bool fullscreen_mode, const bool debug_mode) noexcept
: fullscreen_mode_(fullscreen_mode),
debug_mode_(debug_mode),
blink_count_(0),
game_count_(0),
game_state_(game_state::title) {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
std::cerr << "error: " << SDL_GetError() << '\n';
exit(EXIT_FAILURE);
}
Uint32 flags = SDL_WINDOW_SHOWN;
if (fullscreen_mode_) {
flags |= SDL_WINDOW_FULLSCREEN;
}
window_ = SDL_CreateWindow("Area776", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, screen::width,
screen::height, flags);
if (window_ == nullptr) {
std::cerr << "error: " << SDL_GetError() << '\n';
exit(EXIT_FAILURE);
}
renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED);
if (renderer_ == nullptr) {
std::cerr << "error: " << SDL_GetError() << '\n';
exit(EXIT_FAILURE);
}
image_manager_ = std::make_unique<ImageManager>(renderer_);
input_manager_ = std::make_unique<InputManager>();
mixer_manager_ = std::make_unique<MixerManager>();
fighter_ = std::make_unique<Fighter>(
image_manager_.get(), input_manager_.get(), mixer_manager_.get());
enemies_ =
std::make_unique<Enemies>(image_manager_.get(), mixer_manager_.get());
boss_ = std::make_unique<Boss>(image_manager_.get(), mixer_manager_.get());
effects_ = std::make_unique<Effects>(image_manager_.get());
wipe_ = std::make_unique<Wipe>(renderer_);
snow_ = std::make_unique<Snow>(image_manager_.get());
SDL_ShowCursor(SDL_DISABLE);
}
void run() noexcept;
~Area776() noexcept { atexit(SDL_Quit); }
};
| 30.403509 | 79 | 0.63416 | r6eve |
1f327aadd4b254c47bdf5dd03c2390ad82891df2 | 3,788 | cpp | C++ | src/common/EnumStringMapper.cpp | cgodkin/fesapi | d25c5e30ccec537c471adc3bb036c48f2c51f2c9 | [
"Apache-2.0"
] | 1 | 2021-01-04T16:19:33.000Z | 2021-01-04T16:19:33.000Z | src/common/EnumStringMapper.cpp | philippeVerney/fesapi | 5aff682d8e707d4682a0d8674b5f6353be24ed55 | [
"Apache-2.0"
] | null | null | null | src/common/EnumStringMapper.cpp | philippeVerney/fesapi | 5aff682d8e707d4682a0d8674b5f6353be24ed55 | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------
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.
-----------------------------------------------------------------------*/
#include "EnumStringMapper.h"
#include "../proxies/gsoap_resqml2_0_1H.h"
#include "../proxies/gsoap_eml2_1H.h"
using namespace COMMON_NS;
EnumStringMapper::EnumStringMapper()
{
gsoapContext = soap_new2(SOAP_XML_STRICT | SOAP_C_UTFSTRING | SOAP_XML_IGNORENS, SOAP_XML_TREE | SOAP_XML_INDENT | SOAP_XML_CANONICAL | SOAP_C_UTFSTRING);
}
EnumStringMapper::~EnumStringMapper()
{
soap_destroy(gsoapContext); // remove deserialized C++ objects
soap_end(gsoapContext); // remove deserialized data
soap_done(gsoapContext); // finalize last use of the context
soap_free(gsoapContext); // Free the context
}
std::string EnumStringMapper::getEnergisticsPropertyKindName(gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind energisticsPropertyKind) const
{
return gsoap_resqml2_0_1::soap_resqml20__ResqmlPropertyKind2s(gsoapContext, energisticsPropertyKind);
}
gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind EnumStringMapper::getEnergisticsPropertyKind(const std::string & energisticsPropertyKindName) const
{
gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind result;
return gsoap_resqml2_0_1::soap_s2resqml20__ResqmlPropertyKind(gsoapContext, energisticsPropertyKindName.c_str(), &result) == SOAP_OK ? result : gsoap_resqml2_0_1::resqml20__ResqmlPropertyKind__RESQML_x0020root_x0020property;
}
std::string EnumStringMapper::getEnergisticsUnitOfMeasureName(gsoap_resqml2_0_1::resqml20__ResqmlUom energisticsUom) const
{
return gsoap_resqml2_0_1::soap_resqml20__ResqmlUom2s(gsoapContext, energisticsUom);
}
gsoap_resqml2_0_1::resqml20__ResqmlUom EnumStringMapper::getEnergisticsUnitOfMeasure(const std::string & energisticsUomName) const
{
gsoap_resqml2_0_1::resqml20__ResqmlUom result;
return gsoap_resqml2_0_1::soap_s2resqml20__ResqmlUom(gsoapContext, energisticsUomName.c_str(), &result) == SOAP_OK ? result : gsoap_resqml2_0_1::resqml20__ResqmlUom__Euc;
}
std::string EnumStringMapper::getFacet(gsoap_resqml2_0_1::resqml20__Facet facet) const
{
return gsoap_resqml2_0_1::soap_resqml20__Facet2s(gsoapContext, facet);
}
gsoap_resqml2_0_1::resqml20__Facet EnumStringMapper::getFacet(const std::string & facet) const
{
gsoap_resqml2_0_1::resqml20__Facet result;
return gsoap_resqml2_0_1::soap_s2resqml20__Facet(gsoapContext, facet.c_str(), &result) == SOAP_OK ? result : gsoap_resqml2_0_1::resqml20__Facet__what;
}
std::string EnumStringMapper::lengthUomToString(gsoap_eml2_1::eml21__LengthUom witsmlUom) const
{
return gsoap_eml2_1::soap_eml21__LengthUom2s(gsoapContext, witsmlUom);
}
std::string EnumStringMapper::verticalCoordinateUomToString(gsoap_eml2_1::eml21__VerticalCoordinateUom witsmlUom) const
{
return gsoap_eml2_1::soap_eml21__VerticalCoordinateUom2s(gsoapContext, witsmlUom);
}
std::string EnumStringMapper::planeAngleUomToString(gsoap_eml2_1::eml21__PlaneAngleUom witsmlUom) const
{
return gsoap_eml2_1::soap_eml21__PlaneAngleUom2s(gsoapContext, witsmlUom);
}
| 44.046512 | 225 | 0.802798 | cgodkin |
1f38f894c5c4f23f8b23ee8e6d6ca7870503bc6e | 2,543 | cpp | C++ | openbr/plugins/imgproc/gradient.cpp | gaatyin/openbr | a55fa7bd0038b323ade2340c69f109146f084218 | [
"Apache-2.0"
] | 1 | 2021-04-26T12:53:42.000Z | 2021-04-26T12:53:42.000Z | openbr/plugins/imgproc/gradient.cpp | William-New/openbr | 326f9bbb84de35586e57b1b0449c220726571c6c | [
"Apache-2.0"
] | null | null | null | openbr/plugins/imgproc/gradient.cpp | William-New/openbr | 326f9bbb84de35586e57b1b0449c220726571c6c | [
"Apache-2.0"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2012 The MITRE Corporation *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <opencv2/imgproc/imgproc.hpp>
#include <openbr/plugins/openbr_internal.h>
using namespace cv;
namespace br
{
/*!
* \ingroup transforms
* \brief Computes magnitude and/or angle of image.
* \author Josh Klontz \cite jklontz
*/
class GradientTransform : public UntrainableTransform
{
Q_OBJECT
Q_ENUMS(Channel)
Q_PROPERTY(Channel channel READ get_channel WRITE set_channel RESET reset_channel STORED false)
public:
enum Channel { Magnitude, Angle, MagnitudeAndAngle };
private:
BR_PROPERTY(Channel, channel, Angle)
void project(const Template &src, Template &dst) const
{
Mat dx, dy, magnitude, angle;
Sobel(src, dx, CV_32F, 1, 0, FILTER_SCHARR);
Sobel(src, dy, CV_32F, 0, 1, FILTER_SCHARR);
cartToPolar(dx, dy, magnitude, angle, true);
std::vector<Mat> mv;
if ((channel == Magnitude) || (channel == MagnitudeAndAngle)) {
const float theoreticalMaxMagnitude = sqrt(2*pow(float(2*(3+10+3)*255), 2.f));
mv.push_back(magnitude / theoreticalMaxMagnitude);
}
if ((channel == Angle) || (channel == MagnitudeAndAngle))
mv.push_back(angle);
Mat result;
merge(mv, result);
dst.append(result);
}
};
BR_REGISTER(Transform, GradientTransform)
} // namespace br
#include "imgproc/gradient.moc"
| 37.955224 | 99 | 0.527723 | gaatyin |
1f3a12449f40616e430b3e7bb6eb9998fdc8fcfc | 1,384 | cc | C++ | DataFormats/L1Trigger/src/L1PFTau.cc | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null | DataFormats/L1Trigger/src/L1PFTau.cc | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null | DataFormats/L1Trigger/src/L1PFTau.cc | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null |
#include "DataFormats/L1Trigger/interface/L1PFTau.h"
using std::ostream;
using std::endl;
using std::hex;
using std::dec;
typedef std::vector<l1t::L1PFTau> L1PFTauCollection;
// default constructor
l1t::L1PFTau::L1PFTau() : m_data(0), m_tauType(12), m_tauIsoQual(0), m_tauRelIsoQual(0), m_relativeIsolation(100), m_rawIsolation(0), m_chargedIsolation(0), m_passTightIso(0), m_passMediumIso(0),m_passLooseIso(0), m_passVLooseIso(0), m_passTightRelIso(0), m_passMediumRelIso(0),m_passLooseRelIso(0), m_passVLooseRelIso(0){ };
// destructor
l1t::L1PFTau::~L1PFTau() { }
// print to stream
/*
ostream& l1t::operator<<(ostream& os, const l1t::L1PFTau& tau) {
os << "L1PFTau:";
os << " Reco -> ET = " <<tau.p4().Pt();
os <<" Eta = " <<tau.p4().Eta();
os <<" Phi = " <<tau.p4().Phi() << std::endl;
os << " Tau Decay Mode = "<< tau.tauType() << std::endl;
os << " Et = " << tau.et();
os << " towerEta = "<< tau.towerEta();
os << " towerPhi = "<< tau.towerPhi()<<std::endl;
os << " ecalEnergy = "<< tau.ecalEnergy();
os << " hcalEnergy = "<< tau.hcalEnergy();
os << " caloEnergy = "<< tau.caloEnergy()<<std::endl;
os << " EoH = "<<tau.EoH();
os <<" HoE = "<<tau.HoE()<<std::endl;
os <<" rawIso = "<<tau.rawIso()<<std::endl;
os <<" relIso = "<<tau.relIso()<<std::endl;
os << " raw = "<<tau.raw()<<std::endl;
return os;
}
*/
| 27.68 | 326 | 0.596821 | thesps |
1f3c3aaebd967b19bd4b6bc76baf6de9c5647988 | 6,846 | cpp | C++ | sim/config.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 7 | 2016-03-01T13:16:59.000Z | 2021-08-20T07:41:43.000Z | sim/config.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | null | null | null | sim/config.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 5 | 2015-04-20T14:29:38.000Z | 2018-12-29T11:09:17.000Z | #include "sim/config.h"
#include "programs/mgsim.h"
#include <set>
#include <map>
#include <vector>
using namespace std;
void Config::collectPropertiesByType(Config::types_t& types,
Config::typeattrs_t& typeattrs)
{
map<Symbol, set<Symbol> > collect;
for (auto& i : m_objects)
{
types[m_objects[i.first]].clear();
typeattrs[m_objects[i.first]].clear();
}
for (auto& i : m_objprops)
{
for (auto& j : i.second)
collect[m_objects[i.first]].insert(j.first);
}
for (auto& i : collect)
{
size_t j = 0;
for (auto k : i.second)
{
types[i.first].push_back(k);
typeattrs[i.first][k] = j++;
}
}
}
vector<uint32_t> Config::GetConfWords()
{
types_t types;
typeattrs_t typeattrs;
collectPropertiesByType(types, typeattrs);
vector<uint32_t> db;
map<Symbol, vector<size_t> > attrtable_backrefs;
map<Symbol, vector<size_t> > sym_backrefs;
map<ObjectRef, vector<size_t> > obj_backrefs;
map<Symbol, size_t> type_table;
map<Symbol, size_t> attrtable_table;
map<ObjectRef, size_t> obj_table;
map<Symbol, size_t> sym_table;
size_t cur_next_offset;
db.push_back(CONF_MAGIC);
// types: number of types, then type entries
// format for each type entry:
// word 0: global offset to symbol
// word 1: global offset to attribute table
// HEADER
db.push_back(CONF_TAG_TYPETABLE);
cur_next_offset = db.size(); db.push_back(0);
// CONTENT - HEADER
db.push_back(types.size());
// ENTRIES
size_t typecnt = 0;
for (auto& i : types)
{
sym_backrefs[i.first].push_back(db.size());
db.push_back(0);
if (!i.second.empty())
attrtable_backrefs[i.first].push_back(db.size());
db.push_back(0);
type_table[i.first] = typecnt++;
}
db[cur_next_offset] = db.size();
// attribute tables. For each table:
// word 0: number of entries,
// word 1: logical offset to object type in type table
// then entries. Each entry is a global symbol offset (1 word)
for (auto& i : types)
{
if (i.second.empty())
continue;
// HEADER
db.push_back(CONF_TAG_ATTRTABLE);
cur_next_offset = db.size(); db.push_back(0);
// CONTENT - HEADER
attrtable_table[i.first] = db.size();
db.push_back(i.second.size());
db.push_back(type_table[i.first]);
// ENTRIES
for (auto j : i.second)
{
sym_backrefs[j].push_back(db.size());
db.push_back(0);
}
db[cur_next_offset] = db.size();
}
// objects. For each object:
// word 0: logical offset to object type in type table
// then properties. Each property is a pair (entity type, global offset/value)
// each property's position matches the attribute name offsets
// in the type-attribute table.
//
for (auto& i : m_objects)
{
// HEADER
db.push_back(CONF_TAG_OBJECT);
cur_next_offset = db.size(); db.push_back(0);
// CONTENT - HEADER
obj_table[i.first] = db.size();
db.push_back(type_table[i.second]);
// ENTRIES
// collect the attributes actually defined in the
// order defined by the type
auto& propdescs = typeattrs.find(i.second)->second;
vector<EntityRef> collect;
collect.resize(propdescs.size(), 0);
auto op = m_objprops.find(i.first);
if (op != m_objprops.end())
{
auto& props = op->second;
for (auto& j : props)
{
collect[propdescs.find(j.first)->second] = j.second;
}
}
// populate according to logical attribute order defined by type
for (auto j : collect)
{
if (j != 0)
{
const Entity& e = *j;
db.push_back(e.type);
size_t cur_offset = db.size();
switch(e.type)
{
case Entity::VOID: db.push_back(0); break;
case Entity::SYMBOL: sym_backrefs[e.symbol].push_back(cur_offset); db.push_back(0); break;
case Entity::OBJECT: obj_backrefs[e.object].push_back(cur_offset); db.push_back(0); break;
case Entity::UINT: db.push_back(e.value); break;
}
}
else
{
db.push_back(0);
db.push_back(0);
}
}
db[cur_next_offset] = db.size();
}
// raw configuration table.
// word 0: number of entries.
// then entries. Each entry is a pair (symbol, symbol)
auto rawconf = getRawConfiguration();
// HEADER
db.push_back(CONF_TAG_RAWCONFIG);
cur_next_offset = db.size(); db.push_back(0);
// CONTENT - HEADER
db.push_back(rawconf.size());
// ENTRIES
for (auto& i : rawconf)
{
Symbol key = makeSymbol(i.first);
Symbol val = makeSymbol(i.second);
sym_backrefs[key].push_back(db.size());
db.push_back(0);
sym_backrefs[val].push_back(db.size());
db.push_back(0);
}
db[cur_next_offset] = db.size();
// symbols. For each symbol:
// word 0: size (number of characters)
// then characters, nul-terminated
for (auto& i : m_symbols)
{
// HEADER
db.push_back(CONF_TAG_SYMBOL);
cur_next_offset = db.size(); db.push_back(0);
// CONTENT - HEADER
sym_table[&i] = db.size();
db.push_back(i.size());
// ENTRIES - CHARACTERS
size_t first_pos = db.size();
// we want to enforce byte order, so we cannot use memcpy
// because the host might be big endian.
vector<char> raw(i.begin(), i.end());
raw.resize(((raw.size() / sizeof(uint32_t)) + 1) * sizeof(uint32_t), 0);
db.resize(db.size() + raw.size() / sizeof(uint32_t));
for (size_t j = first_pos, k = 0; j < db.size(); ++j, k += 4)
{
uint32_t val = (uint32_t)raw[k]
| ((uint32_t)raw[k+1] << 8)
| ((uint32_t)raw[k+2] << 16)
| ((uint32_t)raw[k+3] << 24);
db[j] = val;
}
db[cur_next_offset] = db.size();
}
// terminate the chain with a nul tag
db.push_back(0);
// now resolve all back references
for (auto& i : attrtable_backrefs)
for (auto j : i.second)
db[j] = attrtable_table[i.first];
for (auto& i : sym_backrefs)
for (auto j : i.second)
db[j] = sym_table[i.first];
for (auto& i : obj_backrefs)
for (auto j : i.second)
db[j] = obj_table[i.first];
return db;
}
| 27.384 | 106 | 0.551417 | svp-dev |
1f3f71f2c7fb4c372c14046673ea851a9d6fb79f | 355 | hpp | C++ | include/rect.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | include/rect.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | include/rect.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | #pragma once
namespace Prova
{
class Vector2;
class Rect
{
public:
Rect();
Rect(float left, float top, float width, float height);
float left;
float top;
float width;
float height;
Vector2 GetTopLeft();
Vector2 GetTopRight();
Vector2 GetBottomLeft();
Vector2 GetBottomRight();
};
} | 16.904762 | 61 | 0.594366 | teamprova |
1f40b744c830dbb7b3165bde25fdc7f0091c7e02 | 1,221 | cpp | C++ | workshop5-6/Sum.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | workshop5-6/Sum.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | workshop5-6/Sum.cpp | PavanKamra96/BTP200 | 516f5ed60452da53d47206caef22423825a3145e | [
"MIT"
] | null | null | null | /**
Name: Pavan Kumar Kamra
Course: BTP200
**/
#include <iostream>
#include <cstring>
#include "Sum.h"
using namespace std;
// constructor with defaults
Sum::Sum() {
array = nullptr;
size = 0;
counter = 0;
sum = 0;
}
// recieves the size of the array
Sum::Sum(int s) {
if (s > 0)
size = s;
else
size = 0;
array = new int[size];
counter = 0;
sum = 0;
}
// recieves an array of numbers + size
Sum::Sum(const int * tArray, int o) {
if (o > 0) {
array = new int[o];
size = o;
sum = 0;
counter = 0;
for (int i = 0; i < size; i++) {
array[i] = tArray[i];
}
for (int k = 0; k < size; k++) {
sum = array[k] + sum;
}
} else
size = 0;
}
// displays the results
void Sum::display() const {
int j = 0;
while (j < size - 1) {
cout << array[j] << "+";
j++;
}
cout << array[size - 1] << "=" << sum << endl;
}
// mem operator that adds a num to current obj and returns ref to the current obj
Sum & Sum::operator += (int n) {
if (counter < size) {
array[counter] = n;
sum = sum + n;
counter = counter + 1;
} else {
cerr << "No room for anymore numbers " << n << " has not been added" << endl;
}
return *this;
} | 18.223881 | 81 | 0.530713 | PavanKamra96 |
1f4236929b5440ffed877c85b19e07125f382c81 | 4,329 | cpp | C++ | Ouroboros/Source/oString/codify_data.cpp | jiangzhu1212/oooii | fc00ff81e74adaafd9c98ba7c055f55d95a36e3b | [
"MIT"
] | null | null | null | Ouroboros/Source/oString/codify_data.cpp | jiangzhu1212/oooii | fc00ff81e74adaafd9c98ba7c055f55d95a36e3b | [
"MIT"
] | null | null | null | Ouroboros/Source/oString/codify_data.cpp | jiangzhu1212/oooii | fc00ff81e74adaafd9c98ba7c055f55d95a36e3b | [
"MIT"
] | null | null | null | // Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use.
#include <oString/string.h>
#include <iterator>
int snprintf(char* dst, size_t dst_size, const char* fmt, ...);
using namespace std;
namespace ouro {
errno_t replace(char* oRESTRICT result, size_t result_size, const char* oRESTRICT src, const char* find, const char* replace);
template<typename T> struct StaticArrayTraits {};
template<> struct StaticArrayTraits<unsigned char>
{
static const size_t WORDS_PER_LINE = 20;
static inline const char* GetFormat() { return "0x%02x,"; }
static inline const char* GetType() { return "unsigned char"; }
};
template<> struct StaticArrayTraits<unsigned short>
{
static const size_t WORDS_PER_LINE = 16;
static inline const char* GetFormat() { return "0x%04x,"; }
static inline const char* GetType() { return "unsigned short"; }
};
template<> struct StaticArrayTraits<unsigned int>
{
static const size_t WORDS_PER_LINE = 10;
static inline const char* GetFormat() { return "0x%08x,"; }
static inline const char* GetType() { return "unsigned int"; }
};
template<> struct StaticArrayTraits<uint64_t>
{
static const size_t WORDS_PER_LINE = 10;
static inline const char* GetFormat() { return "0x%016llx,"; }
static inline const char* GetType() { return "uint64_t"; }
};
static const char* file_base(const char* path)
{
const char* p = path + strlen(path) - 1;
while (p >= path)
{
if (*p == '/' || *p == '\\')
return p + 1;
p--;
}
return nullptr;
}
static char* codify_buffer_name(char* dst, size_t dst_size, const char* path)
{
if (replace(dst, dst_size, file_base(path), ".", "_"))
return nullptr;
return dst;
}
template<size_t size> inline char* codify_buffer_name(char (&dst)[size], const char* path) { return codify_buffer_name(dst, size, path); }
template<typename T>
static size_t codify_data(char* dst, size_t dst_size, const char* buffer_name, const T* buf, size_t buf_size)
{
const T* words = static_cast<const T*>(buf);
char* str = dst;
char* end = str + dst_size - 1; // -1 for terminator
const size_t nWords = buf_size / sizeof(T);
str += snprintf(str, dst_size, "const %s sBuffer[] = \n{ // *** AUTO-GENERATED BUFFER, DO NOT EDIT ***", StaticArrayTraits<T>::GetType());
for (size_t i = 0; i < nWords; i++)
{
size_t numberOfElementsLeft = std::distance(str, end);
if ((i % StaticArrayTraits<T>::WORDS_PER_LINE) == 0 && numberOfElementsLeft > 2)
{
*str++ = '\n';
*str++ = '\t';
numberOfElementsLeft -= 2;
}
str += snprintf(str, numberOfElementsLeft, StaticArrayTraits<T>::GetFormat(), *words++);
}
// handle any remaining bytes
const size_t nExtraBytes = buf_size % sizeof(T);
if (nExtraBytes)
{
uint64_t tmp = 0;
memcpy(&tmp, &reinterpret_cast<const unsigned char*>(buf)[sizeof(T) * nWords], nExtraBytes);
str += snprintf(str, std::distance(str, end), StaticArrayTraits<T>::GetFormat(), static_cast<T>(tmp));
}
str += snprintf(str, std::distance(str, end), "\n};\n");
// add accessor function
char bufferId[_MAX_PATH];
codify_buffer_name(bufferId, buffer_name);
uint64_t sz = buf_size; // explicitly size this out so printf formatting below can remain the same between 32- and 64-bit
str += snprintf(str, std::distance(str, end), "void get_%s(const char** ppBufferName, const void** ppBuffer, size_t* pSize) { *ppBufferName = \"%s\"; *ppBuffer = sBuffer; *pSize = %llu; }\n", bufferId, file_base(buffer_name), sz);
if (str < end)
*str++ = 0;
return std::distance(dst, str);
}
size_t codify_data(char* oRESTRICT dst, size_t dst_size, const char* oRESTRICT buffer_name, const void* oRESTRICT buf, size_t buf_size, size_t word_size)
{
switch (word_size)
{
case sizeof(unsigned char): return codify_data(dst, dst_size, buffer_name, static_cast<const unsigned char*>(buf), buf_size);
case sizeof(unsigned short): return codify_data(dst, dst_size, buffer_name, static_cast<const unsigned short*>(buf), buf_size);
case sizeof(unsigned int): return codify_data(dst, dst_size, buffer_name, static_cast<const unsigned int*>(buf), buf_size);
case sizeof(uint64_t): return codify_data(dst, dst_size, buffer_name, static_cast<const uint64_t*>(buf), buf_size);
default: break;
}
return 0;
}
}
| 35.195122 | 232 | 0.68353 | jiangzhu1212 |
1f436e92f7674bd40f703105967be8cc1a00b10e | 3,438 | cpp | C++ | Engine/WindowManager.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | 5 | 2018-11-17T18:15:44.000Z | 2020-04-26T11:27:16.000Z | Engine/WindowManager.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | 1 | 2020-04-22T13:03:52.000Z | 2020-04-23T12:57:40.000Z | Engine/WindowManager.cpp | tairoman/CraftClone | b50e40f5fb4a10febe8a17a37a439aa238d8deb3 | [
"MIT"
] | null | null | null | #include <SDL2/SDL_video.h>
#include <cstdint>
#include <iostream>
#include "WindowManager.h"
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/glu.h>
namespace
{
using namespace Engine;
std::uint32_t windowModeToSDL(WindowMode mode)
{
switch (mode) {
case WindowMode::Windowed:
return 0;
case WindowMode::Fullscreen:
return SDL_WINDOW_FULLSCREEN;
case WindowMode::WindowedFullscreen:
return SDL_WINDOW_FULLSCREEN_DESKTOP;
}
}
}
namespace Engine {
WindowManager::WindowManager()
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
std::cerr << "Couldn't initialize SDL: " << SDL_GetError() << ".\n";
exit(0);
}
SDL_GL_LoadLibrary(nullptr);
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
m_window.reset(SDL_CreateWindow(
"",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
0,
0,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED));
if (m_window == nullptr) {
std::cerr << "Couldn't set video mode: " << SDL_GetError() << ".\n";
exit(0);
}
SDL_SetRelativeMouseMode(SDL_TRUE);
// Create OpenGL context
m_context = SDL_GL_CreateContext(m_window.get());
if (m_context == nullptr) {
std::cerr << "Failed to create OpenGL context: " << SDL_GetError() << ".\n";
exit(0);
}
SDL_GL_MakeCurrent(m_window.get(), m_context);
glewExperimental = GL_TRUE;
const auto init_res = glewInit();
if(init_res != GLEW_OK)
{
std::cerr << "Failed to initialize GLEW!\n";
std::cerr << glewGetErrorString(glewInit()) << "\n";
exit(1);
}
if (SDL_GetDesktopDisplayMode(0, &m_currentDisplayMode) != 0) {
std::cerr << SDL_GetError() << "\n";
exit(0);
}
setSize(m_currentDisplayMode.w, m_currentDisplayMode.h);
setVSync(false);
}
void WindowManager::setSize(int w, int h)
{
m_width = w;
m_height = h;
if (m_windowMode == WindowMode::Fullscreen) {
m_currentDisplayMode.w = m_width;
m_currentDisplayMode.h = m_height;
SDL_SetWindowDisplayMode(m_window.get(), &m_currentDisplayMode);
}
else {
SDL_SetWindowSize(m_window.get(), m_width, m_height);
}
SDL_WarpMouseInWindow(m_window.get(), m_width / 2, m_height / 2);
glViewport(0, 0, m_width, m_height); // Set viewport
std::cout << "New width: " << m_width << "\n";
std::cout << "New height: " << m_height << "\n";
}
void WindowManager::setWindowMode(WindowMode mode)
{
m_windowMode = mode;
SDL_SetWindowFullscreen(m_window.get(), windowModeToSDL(mode));
if (mode == WindowMode::Fullscreen) {
setSize(m_width, m_height);
}
}
SDL_Window* WindowManager::sdlWindow() const
{
return m_window.get();
}
int WindowManager::width() const
{
return m_width;
}
int WindowManager::height() const
{
return m_height;
}
void WindowManager::setVSync(bool setEnabled)
{
SDL_GL_SetSwapInterval(static_cast<int>(setEnabled));
}
} | 23.547945 | 84 | 0.656486 | tairoman |
1f4567327732139e8ac9da14afab1935c571db55 | 1,242 | cc | C++ | src/posix-pid.cc | afett/clingeling | e6f6810dde5a1076e70f261ef738ae8f4dbd4e54 | [
"BSD-2-Clause"
] | null | null | null | src/posix-pid.cc | afett/clingeling | e6f6810dde5a1076e70f261ef738ae8f4dbd4e54 | [
"BSD-2-Clause"
] | null | null | null | src/posix-pid.cc | afett/clingeling | e6f6810dde5a1076e70f261ef738ae8f4dbd4e54 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2021 Andreas Fett. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
#include "posix/pid.h"
#include "posix/signal.h"
#include "posix/system-error.h"
#include "posix/wait.h"
#include <signal.h>
#include <sys/wait.h>
namespace Posix {
class PidImpl : public Pid {
public:
explicit PidImpl(int value)
:
value_{value}
{
static_assert(std::is_same_v<pid_t, int>);
}
void kill(Signal) override;
Wait::Status wait(Wait::Option) override;
private:
pid_t value_ = -1;
};
std::shared_ptr<Pid> Pid::create(int value)
{
return std::make_shared<PidImpl>(value);
}
void PidImpl::kill(Signal sig)
{
auto res = ::kill(value_, static_cast<int>(sig));
if (res == -1) {
throw make_system_error(errno, "::kill(%s, %s)", value_, static_cast<int>(sig));
}
}
namespace {
int waitpid_opts(Wait::Option opt)
{
return opt == Wait::Option::NoHang ? WNOHANG : 0;
}
}
Wait::Status PidImpl::wait(Wait::Option opt)
{
int status{0};
auto res = ::waitpid(value_, &status, waitpid_opts(opt));
if (res == -1) {
throw make_system_error(errno, "::waitpid(%s, %x, %s)", value_, &status, waitpid_opts(opt));
}
return Wait::Status{status};
}
}
| 18.537313 | 94 | 0.673913 | afett |
1f4b21f86baa27718b6ea5a3cbf0c166bf2fdbc5 | 7,634 | cpp | C++ | src/configuration/RunConfig.cpp | Childcity/copyright_notice | 3f343d42bc47a1d48a945ceb214ca9aa5da7ed69 | [
"MIT"
] | null | null | null | src/configuration/RunConfig.cpp | Childcity/copyright_notice | 3f343d42bc47a1d48a945ceb214ca9aa5da7ed69 | [
"MIT"
] | null | null | null | src/configuration/RunConfig.cpp | Childcity/copyright_notice | 3f343d42bc47a1d48a945ceb214ca9aa5da7ed69 | [
"MIT"
] | null | null | null | #include "RunConfig.h"
#include <mutex>
#include <QCommandLineParser>
#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include "src/file_utils/file_utils.h"
#include "src/logger/log.h"
#include "StaticConfig.h"
namespace environment {
void init()
{
qputenv("QT_ENABLE_REGEXP_JIT", "1");
}
bool copyrightUpdateNotAllowed()
{
static constexpr const char *falseValues[]{"False", "false", "F", "f", "0"};
const auto enabled = qgetenv("LINT_ENABLE_COPYRIGHT_UPDATE");
return std::any_of(std::cbegin(falseValues), std::cend(falseValues),
[&enabled](const auto &fv) { return enabled == fv; });
}
} // namespace environment
namespace {
using Msg = logger::MsgCode;
// clang-format off
QCommandLineOption componentName{"component", "Add or replace software component mention.", "name"};
QCommandLineOption updateCopyright{"update-copyright", "Add or update copyright field (Year, Company, etc...)."};
QCommandLineOption updateFileName{"update-filename", "Add or fix 'File' field."};
QCommandLineOption updateAuthors{"update-authors", "Add or update author list."};
QCommandLineOption updateAuthorsOnlyIfEmpty{
"update-authors-only-if-empty",
"Update author list only if this list is empty in author field (edited by someone else)."};
QCommandLineOption maxBlameAuthors{
"max-blame-authors-to-start-update",
"Update author list only if blame authors <= some limit. "
"Should be a positive number (0 or -1 mean 'unlimited' and used by default).", "number", "0"};
QCommandLineOption dontSkipBrokenMerges{
"dont-skip-broken-merges", "Do not skip broken merge commits."};
QCommandLineOption staticConfigPath{
"static-config", "Json configuration file with static configuration.", "path"};
QCommandLineOption dry{"dry", "Do not modify files, print to stdout instead."};
QCommandLineOption verbose{"verbose", "Print verbose output."};
// clang-format on
void addOptions(QCommandLineParser &parser)
{
parser.setApplicationDescription(appconst::cAppDescription);
parser.addHelpOption();
parser.addVersionOption();
// clang-format off
parser.addOptions({
componentName
, updateCopyright
, updateFileName
, updateAuthors
, updateAuthorsOnlyIfEmpty
, maxBlameAuthors
, dontSkipBrokenMerges
, staticConfigPath
, dry
, verbose
});
// clang-format on
parser.addPositionalArgument("file_or_dir", "File or directory to process.", "[paths...]");
}
} // namespace
RunConfig::RunConfig(const QStringList &arguments) noexcept
{
QCommandLineParser parser;
addOptions(parser);
parser.process(arguments);
if (parser.isSet(verbose)) {
m_runOptions |= RunOption::Verbose;
}
if (parser.isSet(::componentName)) {
m_runOptions |= RunOption::UpdateComponent;
m_componentName = parser.value(::componentName);
if (m_componentName.isEmpty()) {
CN_WARN(Msg::BadComponentName,
"Component name is empty, that is why this field will be deleted.");
}
}
if (parser.isSet(updateCopyright)) {
m_runOptions |= RunOption::UpdateCopyright;
}
if (parser.isSet(updateFileName)) {
m_runOptions |= RunOption::UpdateFileName;
}
if (parser.isSet(updateAuthors) && qgetenv("LINT_ENABLE_COPYRIGHT_UPDATE") == "") {
m_runOptions |= RunOption::UpdateAuthors;
}
if (parser.isSet(updateAuthorsOnlyIfEmpty)) {
m_runOptions |= RunOption::UpdateAuthorsOnlyIfEmpty;
}
if (parser.isSet(::maxBlameAuthors)) {
bool isOk{};
m_maxBlameAuthors = parser.value(::maxBlameAuthors).toInt(&isOk);
if (!isOk) {
CN_ERR(Msg::BadMaxBlameAuthors,
::maxBlameAuthors.names().first() << " should be a positive number (0 or -1 "
"mean 'unlimited' and used by default).");
parser.showHelp(apperror::RunArgError);
}
constexpr auto maxInt = std::numeric_limits<int>::max();
m_maxBlameAuthors = m_maxBlameAuthors > 0 ? m_maxBlameAuthors : maxInt;
}
if (parser.isSet(dontSkipBrokenMerges)) {
m_runOptions |= RunOption::DontSkipBrokenMerges;
}
if (parser.isSet(::staticConfigPath)) {
m_staticConfigPath = parser.value(::staticConfigPath);
if (m_staticConfigPath.isEmpty()) {
CN_ERR(Msg::BadStaticConfigPaths,
::staticConfigPath.names().first() << " should not be empty string.");
parser.showHelp(apperror::RunArgError);
}
} else {
QDir appDir(qApp->applicationDirPath());
m_staticConfigPath = appDir.canonicalPath() + QDir::separator() + appconst::cStaticConfig;
}
m_staticConfigPath = QDir::cleanPath(m_staticConfigPath);
if (m_runOptions & RunOption::Verbose) {
CN_DEBUG("Using static-config path " << m_staticConfigPath);
}
if (parser.isSet(dry) || environment::copyrightUpdateNotAllowed()) {
m_runOptions |= RunOption::ReadOnlyMode;
}
m_targetPaths = parser.positionalArguments();
if (m_targetPaths.isEmpty() || m_targetPaths.first().isEmpty()) {
CN_ERR(Msg::BadTargetPaths, "'file_or_dir' should not be empty string.");
parser.showHelp(apperror::RunArgError);
}
std::transform(m_targetPaths.cbegin(), m_targetPaths.cend(), m_targetPaths.begin(),
[](const auto &path) { return QDir::cleanPath(path); });
}
namespace impl {
StaticConfig getStaticConfig(const QString &path)
{
using namespace appconst::json;
const auto handleError = [&path](const auto &action) {
CN_ERR(Msg::BadStaticConfigFormat,
QString("Error parsing static config '%1': %2").arg(path, action));
std::exit(apperror::RunArgError);
};
const auto content = file_utils::readFile(path);
const auto doc = QJsonDocument::fromJson(content);
const auto root = doc.object();
if (root.isEmpty()) {
handleError("root object is empty");
return {};
}
const auto aliasesVal = root.value(cAuthorAliases);
if (!root.contains(cAuthorAliases) || !aliasesVal.isObject()) {
handleError(QString("map '%1' not found").arg(cAuthorAliases));
return {};
}
AuthorAliasesMap authorAliases;
const auto aliasesVariantHash = aliasesVal.toObject().toVariantHash();
std::for_each(aliasesVariantHash.constKeyValueBegin(), aliasesVariantHash.constKeyValueEnd(),
[&authorAliases](const auto &keyValue) {
authorAliases[keyValue.first] = keyValue.second.toString();
});
const auto copyrightFieldTemplateVal = root.value(cCopyrightFieldTemplate);
if (!root.contains(cCopyrightFieldTemplate) || !copyrightFieldTemplateVal.isString()) {
handleError(QString("string '%1' not found").arg(cCopyrightFieldTemplate));
return {};
}
const auto excludedPathSectionsVal = root.value(cExcludedPathSections);
if (!root.contains(cExcludedPathSections) || !excludedPathSectionsVal.isArray()) {
handleError(QString("array '%1' not found").arg(cExcludedPathSections));
return {};
}
ExcludedPathSections excludedPathSections;
const auto excludedPathSectionsArr = excludedPathSectionsVal.toArray();
std::transform(excludedPathSectionsArr.cbegin(), excludedPathSectionsArr.cend(),
std::back_inserter(excludedPathSections),
[](const auto &value) { return value.toString(); });
// clang-format off
return {
std::move(authorAliases),
copyrightFieldTemplateVal.toString(),
std::move(excludedPathSections)
};
// clang-format on
}
static std::unique_ptr<StaticConfig> gStaticConfigInstance;
static std::once_flag create;
} // namespace impl
const StaticConfig &RunConfig::getStaticConfig(const QString &path)
{
std::call_once(impl::create, [=] {
impl::gStaticConfigInstance = std::make_unique<StaticConfig>(impl::getStaticConfig(path));
});
return *::impl::gStaticConfigInstance;
}
| 31.415638 | 113 | 0.716269 | Childcity |
1f4dc3123b91d623e648da04e7f74492d58ee1aa | 1,092 | cpp | C++ | Engine/Base/GameTime.cpp | Antd23rus/S2DE_DirectX11 | 4f729278e6c795f7d606afc70a292c6501b0cafd | [
"MIT"
] | null | null | null | Engine/Base/GameTime.cpp | Antd23rus/S2DE_DirectX11 | 4f729278e6c795f7d606afc70a292c6501b0cafd | [
"MIT"
] | 4 | 2021-10-21T12:42:04.000Z | 2022-02-03T08:41:31.000Z | Engine/Base/GameTime.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 1 | 2021-09-06T08:30:20.000Z | 2021-09-06T08:30:20.000Z | #include "GameTime.h"
#include "Base/Utils/Logger.h"
namespace S2DE::Core
{
GameTime::GameTime() :
m_time(std::chrono::high_resolution_clock::now()),
m_time_begin(std::chrono::high_resolution_clock::now()),
m_fps(0),
m_frame_count(0),
m_deltaTime(0.0f),
m_timer(0.0f)
{
}
GameTime::~GameTime()
{
}
void GameTime::Tick()
{
m_frame_count++;
m_time = std::chrono::high_resolution_clock::now();
m_deltaTime = std::chrono::duration_cast<std::chrono::microseconds>(m_time - m_time_lastUpdate).count() / 1000000.0f;
m_timer_duration = m_time - m_time_begin;
m_timer_duration = std::chrono::duration_cast<std::chrono::microseconds>(m_timer_duration);
m_timer += m_timer_duration.count() / 10;
if (m_time - m_time_begin >= std::chrono::seconds{ 1 })
{
m_fps = m_frame_count;
m_time_begin = m_time;
m_frame_count = 0;
}
m_time_lastUpdate = m_time;
}
float GameTime::GetTime() const
{
return m_timer;
}
float GameTime::GetDeltaTime() const
{
return m_deltaTime;
}
std::int32_t GameTime::GetFPS() const
{
return m_fps;
}
} | 18.2 | 119 | 0.685897 | Antd23rus |
1f524ece0c720ba2b1f74b40b87a0ac8f7a9a08a | 4,768 | cpp | C++ | drivers/adagfx/lvdrv-adagfx-ssd1306.cpp | yhfudev/lv_platformio | 45c9c2b1cdb14dac07fe59dc2993d6e33f07bc1d | [
"MIT"
] | null | null | null | drivers/adagfx/lvdrv-adagfx-ssd1306.cpp | yhfudev/lv_platformio | 45c9c2b1cdb14dac07fe59dc2993d6e33f07bc1d | [
"MIT"
] | null | null | null | drivers/adagfx/lvdrv-adagfx-ssd1306.cpp | yhfudev/lv_platformio | 45c9c2b1cdb14dac07fe59dc2993d6e33f07bc1d | [
"MIT"
] | null | null | null | /**
* \file lvdrv-adagfx-ssd1306.cpp
* \brief SSD1306 driver for LittlevGL
* \author Yunhui Fu (yhfudev@gmail.com)
* \version 1.0
* \date 2020-02-03
* \copyright GPL/BSD
*/
#include "lvgl.h"
#include "lvdrv-adagfx-ssd1306.h"
#include "setuprotary.h"
#include "lvdrv-rotarygrp.h"
////////////////////////////////////////////////////////////////////////////////
#include <Wire.h>
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 //4 // Reset pin # (or -1 if sharing Arduino reset pin)
#if defined(ARDUINO_ARCH_ESP32)
#define USE_ESP32_HELTEC_LORA2 1
#endif
#if defined(USE_ESP32_HELTEC_LORA2)
#define I2C_SDA 4 // heltec WIFI LoRa 32(V2)
#define I2C_SCL 15 // heltec WIFI LoRa 32(V2)
TwoWire twi = TwoWire(1);
void init_heltec_lora2() {
#if 0
pinMode(16, OUTPUT);
digitalWrite(16, LOW); // set GPIO16 low to reset OLED
delay(50);
digitalWrite(16, HIGH); // while OLED is running, must set GPIO16 to high
#else
#undef OLED_RESET
#define OLED_RESET 16
#endif
twi.begin(I2C_SDA, I2C_SCL);
}
#define PTR_WIRE (&twi)
#else
#define init_heltec_lora2()
#define PTR_WIRE (&Wire)
#endif
Adafruit_SSD1306 display(LV_HOR_RES_MAX,LV_VER_RES_MAX, PTR_WIRE, OLED_RESET);
/**
* Flush a buffer to the marked area
* @param drv pointer to driver where this function belongs
* @param area an area where to copy `color_p`
* @param color_p an array of pixel to copy to the `area` part of the screen
*/
void cb_flush_adagfx(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
int row, col;
lv_color_t * p = color_p;
for (row = area->y1; row <= area->y2; row++) {
for (col = area->x1; col <= area->x2; col++) {
if (lv_color_brightness(*p) < 128) {
//if (*p == LV_COLOR_BLACK) {
display.drawPixel(col, row, SSD1306_BLACK);
} else {
display.drawPixel(col, row, SSD1306_WHITE);
}
p ++;
}
}
lv_disp_flush_ready(disp_drv);
}
void cb_rounder_adagfx(struct _disp_drv_t * disp_drv, lv_area_t *a)
{
a->x1 = a->x1 & ~(0x7);
a->x2 = a->x2 | (0x7);
}
void cb_set_px_adagfx(struct _disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa)
{
buf += buf_w/8 * y;
buf += x/8;
if(lv_color_brightness(color) < 128) {
//if (*p == LV_COLOR_BLACK) {
(*buf) &= ~(1 << (7 - x % 8));
} else {
(*buf) |= (1 << (7 - x % 8));
}
}
////////////////////////////////////////////////////////////////////////////////
void hw_init(void)
{
#if defined(ARDUINO)
Serial.begin(115200);
// Wait for USB Serial.
while (!Serial) {}
delay(200);
// Read any input
while (Serial.read() >= 0) {}
#endif
setup_rotary();
/* Add a display
* Use the 'monitor' driver which creates window on PC's monitor to simulate a display*/
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
static lv_disp_buf_t disp_buf;
static lv_color_t buf[LV_HOR_RES_MAX * LV_VER_RES_MAX / 8 / 8]; /*Declare a buffer for 10 lines*/
lv_disp_buf_init(&disp_buf, buf, NULL, LV_HOR_RES_MAX * LV_VER_RES_MAX / 8 / 8); /*Initialize the display buffer*/
lv_disp_drv_t disp_drv;
lv_disp_drv_init(&disp_drv); /*Basic initialization*/
disp_drv.flush_cb = cb_flush_adagfx; /*Used when `LV_VDB_SIZE != 0` in lv_conf.h (buffered drawing)*/
//disp_drv.set_px_cb = cb_set_px_adagfx;
//disp_drv.rounder_cb = cb_rounder_adagfx;
disp_drv.buffer = &disp_buf;
//disp_drv.disp_fill = monitor_fill; /*Used when `LV_VDB_SIZE == 0` in lv_conf.h (unbuffered drawing)*/
//disp_drv.disp_map = monitor_map; /*Used when `LV_VDB_SIZE == 0` in lv_conf.h (unbuffered drawing)*/
lv_disp_drv_register(&disp_drv);
/* Add the rotary encoder as input device */
lv_indev_drv_t indev_drv;
lv_indev_drv_init(&indev_drv); /*Basic initialization*/
indev_drv.type = LV_INDEV_TYPE_ENCODER;
indev_drv.read_cb = rotary_encoder_lv_read;
lv_indev_t* encoder_indev = lv_indev_drv_register(&indev_drv);
rotary_group_init(encoder_indev);
/* Tick init.
* You have to call 'lv_tick_inc()' in periodically to inform LittelvGL about how much time were elapsed
* Create an SDL thread to do this*/
}
static int pre_lvtick = 0;
static int pre_disp = 0;
void hw_loop(void)
{
int cur;
loop_rotary();
cur = millis();
if (pre_lvtick + 5 < cur) {
pre_lvtick = cur;
lv_tick_inc(5);
lv_task_handler();
}
if (pre_disp + 50 < cur) {
pre_disp = cur;
display.display();
}
}
| 29.614907 | 145 | 0.630663 | yhfudev |
1f595b1d26cbca32ab1722cc106f0f695510ce3f | 3,105 | cpp | C++ | source/Debug/debug.cpp | Vadru93/LevelMod | 85738a89f6df2dbd50deacdbc895b30c77e016b9 | [
"BSD-2-Clause"
] | 13 | 2020-08-24T10:46:26.000Z | 2022-02-08T23:59:11.000Z | source/Debug/debug.cpp | Vadru93/LevelMod | 85738a89f6df2dbd50deacdbc895b30c77e016b9 | [
"BSD-2-Clause"
] | 112 | 2020-08-25T11:42:53.000Z | 2022-01-04T14:25:26.000Z | source/Debug/debug.cpp | Vadru93/LevelMod | 85738a89f6df2dbd50deacdbc895b30c77e016b9 | [
"BSD-2-Clause"
] | 1 | 2021-02-17T18:11:52.000Z | 2021-02-17T18:11:52.000Z | #define _CRT_SECURE_NO_WARNINGS
#include "pch.h"
#include "debug.h"
void Tracer(LPCSTR format, ...)
{
if (format)
{
va_list vl;
char str[4096];
va_start(vl, format);
_vsnprintf(str, (sizeof(str) - 1), format, vl);
str[(sizeof(str) - 1)] = 0;
va_end(vl);
// Output to debugger channel
OutputDebugString(str);
printf(str);
}
}
#ifdef _DEBUG
namespace LevelModSettings
{
extern bool bLogging;
}
#endif
extern FILE* logFile;
extern CRITICAL_SECTION critical;
void DebugPrint(const char* file, DWORD line, const char* date, const char* string, ...)
{
EnterCriticalSection(&critical);
static char debug_msg[MAX_PATH];
va_list myargs;
va_start(myargs, string);
vsprintf(debug_msg, string, myargs);
va_end(myargs);
printf(debug_msg);
if (logFile)
{
if (*debug_msg != '\n')
fprintf(logFile, "File %s line %u compiled %s\n", file, line, date);
fprintf(logFile, debug_msg);
fflush(logFile);
}
LeaveCriticalSection(&critical);
}
char* AddressToMappedName(HANDLE hOwner, PVOID pAddress, char* szBuffer, int iSize)
{
if (szBuffer && (iSize > 0))
{
ZeroMemory(szBuffer, iSize);
char szFullPath[MAX_PATH];
if (GetMappedFileName(hOwner, pAddress, szFullPath, (sizeof(szFullPath) - 1)))
{
// Remove the path, keeping just the base name
// TODO: You might optionally want the full path
szFullPath[sizeof(szFullPath) - 1] = 0;
char szFileName[_MAX_FNAME + _MAX_EXT], szExtension[_MAX_EXT];
_splitpath(szFullPath, NULL, NULL, szFileName, szExtension);
_snprintf(szBuffer, (iSize - 1), "%s%s", szFileName, szExtension);
szBuffer[(iSize - 1)] = 0;
return(szBuffer);
}
// Try alternate way, since first failed
{
HMODULE hModule = NULL;
if (pAddress)
{
// Try it as a module handle first
GetModuleHandleEx((GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS), (LPCTSTR)pAddress, &hModule);
if (!hModule) hModule = (HMODULE)pAddress;
}
if (GetModuleBaseName(hOwner, hModule, szBuffer, (iSize - 1)) > 0)
return(szBuffer);
else
// Fix weird bug where GetModuleBaseName() puts a random char in [0] on failure
szBuffer[0] = 0;
}
}
return(NULL);
}
bool ReportException(LPCTSTR pszFunction, LPEXCEPTION_POINTERS pExceptionInfo)
{
char szModule[MAX_PATH] = { "Unknown" };
AddressToMappedName(GetCurrentProcess(), pExceptionInfo->ExceptionRecord->ExceptionAddress, szModule, sizeof(szModule));
Tracer("DLL: ** Exception: %08X, @ %08X, in \"%s\", from Module: \"%s\", Base: %08X **\n", pExceptionInfo->ExceptionRecord->ExceptionCode, pExceptionInfo->ExceptionRecord->ExceptionAddress, pszFunction, szModule, GetModuleHandle(szModule));
return(false);
} | 31.683673 | 245 | 0.612238 | Vadru93 |
1f59c7b1a279e2ea91dec75bcbd966f4f23c1e62 | 1,512 | cpp | C++ | source-code/Numerics/limits.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 115 | 2015-03-23T13:34:42.000Z | 2022-03-21T00:27:21.000Z | source-code/Numerics/limits.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 56 | 2015-02-25T15:04:26.000Z | 2022-01-03T07:42:48.000Z | source-code/Numerics/limits.cpp | gjbex/Scientific-C- | d7aeb88743ffa2a43b1df1569a9200b2447f401c | [
"CC-BY-4.0"
] | 59 | 2015-11-26T11:44:51.000Z | 2022-03-21T00:27:22.000Z | #include <cmath>
#include <iostream>
#include <limits>
using namespace std;
int main() {
cout << numeric_limits<short>::min() << " < int < "
<< numeric_limits<short>::max() << endl;
cout << numeric_limits<int>::min() << " < int < "
<< numeric_limits<int>::max() << endl;
cout << numeric_limits<long>::min() << " < long < "
<< numeric_limits<long>::max() << endl;
cout << "float < " << numeric_limits<float>::max() << endl;
cout << "0.0f < " << numeric_limits<float>::min() << endl;
cout << "1.0f < 1.0f + " << numeric_limits<float>::epsilon() << endl;
cout << "float digits: " << numeric_limits<float>::digits10 << endl;
cout << "double < " << numeric_limits<double>::max() << endl;
cout << "0.0 < " << numeric_limits<double>::min() << endl;
cout << "1.0 < 1.0 + " << numeric_limits<double>::epsilon() << endl;
cout << "double digits: " << numeric_limits<double>::digits10 << endl;
cout << "long double < " << numeric_limits<long double>::max() << endl;
cout << "0.0 < " << numeric_limits<long double>::min() << endl;
cout << "1.0 < 1.0 + " << numeric_limits<long double>::epsilon()
<< endl;
cout << "long double digits: " << numeric_limits<long double>::digits10 << endl;
double x {1000.0};
if (!isfinite(exp(x)))
cout << "exp(" << x << ") is infinity: " << exp(x) << endl;
x = -1.0;
if (!isfinite(sqrt(x)))
cout << "sqrt(" << x << ") is NaN: " << sqrt(x) << endl;
return 0;
}
| 43.2 | 84 | 0.539683 | gjbex |
1f5a9c503a6f3e954afa28cc780371de281c749f | 907 | cc | C++ | epoch/ayla/src/ayla/serialization/triangle_mesh_serializer.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 47 | 2020-03-30T14:36:46.000Z | 2022-03-06T07:44:54.000Z | epoch/ayla/src/ayla/serialization/triangle_mesh_serializer.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | null | null | null | epoch/ayla/src/ayla/serialization/triangle_mesh_serializer.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 8 | 2020-04-01T01:22:45.000Z | 2022-01-02T13:06:09.000Z | #include "ayla/serialization/triangle_mesh_serializer.hpp"
#include "ayla/geometry/triangle_mesh.hpp"
#include "ayla/serialization/boost/explicit_instantiation_macros.hpp"
#include <boost/serialization/vector.hpp>
namespace boost {
namespace serialization {
template <class Archive>
void serialize(Archive& ar, ayla::TriangleMesh& mesh, const unsigned int version) {
ar & make_nvp("vertices", mesh._vertices);
ar & make_nvp("faces", mesh._faces);
}
template<class Archive>
void load_construct_data(Archive& ar, ayla::TriangleMesh* mesh, const unsigned int version) {
::new(mesh)ayla::TriangleMesh();
}
EXPLICIT_INSTANTIATION_SERIALIZE_FUNC_P(ayla::TriangleMesh, AYLA_API);
EXPLICIT_INSTANTIATION_LOAD_CONSTRUCT_DATA_FUNC_P(ayla::TriangleMesh, AYLA_API);
}
}
namespace ayla {
TriangleMeshSerializer::TriangleMeshSerializer()
: Serializer<TriangleMesh>([](){ return "kaskdjhgbfvnsdm348"; })
{ }
} | 27.484848 | 93 | 0.788313 | oprogramadorreal |
1f5aa6bd8d4afdad744fe799c239f71a9fb1893c | 5,586 | cpp | C++ | src/ui/c_load_builder_dialog.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | src/ui/c_load_builder_dialog.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | src/ui/c_load_builder_dialog.cpp | Mankio/Wakfu-Builder | d2ce635dde2da21eee3639cf3facebd07750ab78 | [
"MIT"
] | null | null | null | #include "c_load_builder_dialog.h"
#include "ui_c_load_builder_dialog.h"
c_save_builder_model *c_load_builder_dialog::model = nullptr;
c_load_builder_dialog::c_load_builder_dialog(c_dbmanager *manager, QWidget *parent) :
QDialog(parent),
ui(new Ui::c_load_builder_dialog)
{
ui->setupUi(this);
ui->widget->setStyleSheet(QString("QWidget#widget{background-color : %1;} QLabel{color : white;}").arg(app_color::grey_blue_2));
this->setWindowTitle("Ouvrir un build");
if (model == nullptr) {
model = new c_save_builder_model(manager);
}
ui->tableView->setModel(model);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->resizeColumnsToContents();
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QObject::connect(ui->tableView,&QTableView::clicked,this,&c_load_builder_dialog::slot_table_cliked);
ui->label_2->setStyleSheet("color:white;");
ui->label_4->setStyleSheet("color:white;");
ui->label_5->setStyleSheet("color:white;");
ui->niveau->setText("");
ui->niveau->setStyleSheet("color:white;");
ui->name->setText("");
ui->name->setStyleSheet("color:white;");
ui->classe->setPixmap(QPixmap(":/images/portrait/aleat.png"));
ui->label_4->hide();
ui->tableView->verticalHeader()->setVisible(false);
qDebug() << ui->tableView->styleSheet();
ui->tableView->setFocusPolicy(Qt::NoFocus);
ui->tableView->setShowGrid(false);
ui->tableView->setStyleSheet(QString(" QTableView#tableView{"
" border : 1px solid white;"
" border-radius : 3px;"
" background-color : %1;"
"} "
"QTableView::item{"
" background-color : %1; "
" border-bottom : 1px solid #BBBBBB;"
" border-top : 1px solid #BBBBBB; "
"}"
"QTableView::item:selected {"
" color : white;"
" background-color: %2; "
" border-bottom : 1px solid #BBBBBB;"
" border-top : 1px solid #BBBBBB; "
"} "
"QHeaderView::section { "
" background-color: %1; border : 1px solid %1; color : white;"
"}"
"QHeaderView {"
" border-bottom : 1px solid white;"
"} ").arg(app_color::grey_blue).arg(app_color::green_blue));
QObject::connect(ui->tableView,&QTableView::doubleClicked,this,&c_load_builder_dialog::slot_double_clicked);
button_deleg = new c_button_delegate(ui->tableView);
button_deleg->setModel(model);
ui->tableView->setItemDelegate(button_deleg);
ui->tableView->setSelectionMode(QAbstractItemView::NoSelection);
ui->tableView->setColumnWidth(0,30);
ui->tableView->setColumnWidth(1,50);
ui->tableView->setColumnWidth(2,193);
ui->tableView->setColumnWidth(3,30);
correct_scroll = false;
ui->tableView->horizontalScrollBar()->setEnabled(false);
QObject::connect(ui->tableView->horizontalScrollBar(),&QScrollBar::sliderMoved,this,&c_load_builder_dialog::slot_scrollbar_moved);
QObject::connect(ui->tableView->horizontalScrollBar(),&QScrollBar::rangeChanged,this,&c_load_builder_dialog::slot_scrollbar_moved);
// ui->tableView->horizontalHeader();
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
}
c_load_builder_dialog::~c_load_builder_dialog() {
delete ui;
}
QString c_load_builder_dialog::getCurrent_json() const {
return current_json;
}
int c_load_builder_dialog::getCurrent_id() const {
return current_id;
}
void c_load_builder_dialog::init_model(c_dbmanager *manager) {
model = new c_save_builder_model(manager);
}
void c_load_builder_dialog::slot_table_cliked(const QModelIndex &index) {
ui->tableView->selectionModel()->clearSelection();
for (int i = 0; i < model->columnCount(index); ++i) {
ui->tableView->selectionModel()->setCurrentIndex(model->index(index.row(),i),QItemSelectionModel::Select);
}
qDebug() << ui->tableView->verticalHeader()->size();
ui->tableView->horizontalScrollBar()->setValue(0);
//ui.textEdit->verticalScrollBar()->setValue(0);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
current_json = model->getJson(index);
current_id = model->getId(index);
ui->niveau->setNum(model->getLvl(index));
ui->name->setText(model->getName(index));
QString url = model->getUrlImage(index);
ui->classe->setPixmap(QPixmap(url));
}
void c_load_builder_dialog::slot_double_clicked() {
if (current_json.isEmpty()) return;
accept();
}
void c_load_builder_dialog::slot_scrollbar_moved() {
qDebug() << "slide moved" << correct_scroll;
if (!correct_scroll) {
ui->tableView->horizontalScrollBar()->setValue(0);
correct_scroll = true;
} else {
correct_scroll = false;
}
}
void c_load_builder_dialog::slot_debug() {
qDebug() << "focused changed";
}
| 44.333333 | 135 | 0.591837 | Mankio |
48f2c40de243e4ad583a87975cfab95a08567263 | 2,467 | cpp | C++ | snippets/0x05/b_pointer_05_swap.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | snippets/0x05/b_pointer_05_swap.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | snippets/0x05/b_pointer_05_swap.cpp | pblan/fha-cpp | 5008f54133cf4913f0ca558a3817b01b10d04494 | [
"CECILL-B"
] | null | null | null | // author: a.voss@fh-aachen.de
#include <iostream>
using std::cout;
using std::endl;
// #pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
void init1(int n); // (A)
void init2(int& n);
void init3(int* n);
void swap1(int n, int m);
void swap2(int& n, int& m);
void swap3(int* n, int* m);
int main()
{
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
int n{}, m{};
n=1; init1(n); // (B)
cout << "01| n=" << n << endl;
n=2; init2(n);
cout << "02| n=" << n << endl;
n=3; init3(&n);
cout << "03| n=" << n << endl;
cout << "-----" << endl;
n=1; m=-1; swap1(n,m);
cout << "04| n=" << n << ", m=" << m << endl;
n=2; m=-2; swap2(n,m);
cout << "05| n=" << n << ", m=" << m << endl;
n=3; m=-3; swap3(&n,&m);
cout << "06| n=" << n << ", m=" << m << endl;
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
return 0;
}
void init1(int n) {
n=0;
}
void init2(int& n) {
n=0;
}
void init3(int* n) {
*n=0;
}
void swap1(int n, int m) {
int k = n;
n = m;
m = k;
}
void swap2(int& n, int& m) {
int k = n;
n = m;
m = k;
}
void swap3(int* n, int* m) {
int k = *n;
*n = *m;
*m = k;
}
/* Kommentierung
*
* (A) Es gibt zwei Funktionen 'init' und 'swap'. Die erste soll das
* aufrufende Argument auf 0 setzen, die zweite soll die Argumente
* tauschen - und zwar jeweils die Originalparameter vom Aufruf!
* Das klappt nicht immer, waum?
* Beide Funktionen gibt es in jeweils drei Varianten:
* In der ersten wird die Funktion 'call-by-value'
* aufgerufen, in der zweiten und dritten 'call-by-ref' einmal
* mit Referenzen und einmal mit Zeigern.
* Die Frage lautet immer: was steht nach dem Aufruf in den Parametern
* bzw. wurden sie verändert oder nicht?
*
* (B) Wie beschrieben, zuerst setzen wir Werte, damit man sieht, ob sich
* was verändert hat oder nicht.
* Die Lösung ist, dass beim Aufruf 'call-by-value' die Parameter kopiert
* werden und daher die Originalparameter vom Aufruf nicht verändert werden.
* Bei 'call-by-ref' dagegen werden die Originalparameter verändert,
* entweder weil es sich um Referenzen, also Aliase, handelt oder
* weil über die Zeiger auch die Originalparameter im Zugriff sind.
*
*/
| 25.43299 | 81 | 0.535063 | pblan |
48f339e44b91598999d4ecc386d476f568dacefd | 96 | cpp | C++ | test/cpp_prj/src/file_set_test/house/included_file_in_partition2.cpp | JaniHonkanen/RabbitCall | 2652e201ebcd6697cd25ec7e18163afa002c1016 | [
"MIT"
] | null | null | null | test/cpp_prj/src/file_set_test/house/included_file_in_partition2.cpp | JaniHonkanen/RabbitCall | 2652e201ebcd6697cd25ec7e18163afa002c1016 | [
"MIT"
] | null | null | null | test/cpp_prj/src/file_set_test/house/included_file_in_partition2.cpp | JaniHonkanen/RabbitCall | 2652e201ebcd6697cd25ec7e18163afa002c1016 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "included_file_in_partition2.h"
int partition2Test() {
return 22;
}
| 13.714286 | 40 | 0.739583 | JaniHonkanen |
48f5eef9a4716bd5ccc2d46650eb59ee06b9deaf | 1,551 | cpp | C++ | python/popart._internal.ir/bindings/op/ipucopy.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | python/popart._internal.ir/bindings/op/ipucopy.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | python/popart._internal.ir/bindings/op/ipucopy.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include "bindings/op/ipucopy.hpp"
#include "bindings/op.hpp"
#include "bindings/op/optional.hpp"
#include "bindings/basicoptionals.hpp"
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <popart/op/ipucopy.hpp>
#include <popart/vendored/optional.hpp>
namespace py = pybind11;
namespace popart {
namespace _internal {
namespace ir {
namespace op {
void bindIpuCopy(py::module &m) {
auto sm = m;
sm = sm.def_submodule("op", "Python bindings for PopART ops.");
py::class_<IpuCopyOp, popart::Op, std::shared_ptr<IpuCopyOp>>(sm, "IpuCopyOp")
.def(py::init<const popart::OperatorIdentifier &,
uint64_t,
const Op::Settings &>(),
py::arg("opid"),
py::arg("destIpu"),
py::arg("settings"))
.def("connectInTensor",
py::overload_cast<InIndex, TensorId, uint64_t>(
&IpuCopyOp::connectInTensor))
.def("getDestIpu", &IpuCopyOp::getDestIpu)
.def("getSourceIpu",
py::overload_cast<>(&IpuCopyOp::getSourceIpu, py::const_))
.def("getSourceIpu",
py::overload_cast<const TensorId &>(&IpuCopyOp::getSourceIpu,
py::const_))
.def("getMinSourceIpu", &IpuCopyOp::getMinSourceIpu)
.def("getMaxSourceIpu", &IpuCopyOp::getMaxSourceIpu);
}
} // namespace op
} // namespace ir
} // namespace _internal
} // namespace popart
| 30.411765 | 80 | 0.632495 | gglin001 |
48faacf0e2f20b3c180d5df92460100f13054828 | 37,790 | cpp | C++ | inetcore/setup/iexpress/advpext/patchdownload.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/setup/iexpress/advpext/patchdownload.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/setup/iexpress/advpext/patchdownload.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include <windows.h>
#include <urlmon.h>
#include <wininet.h>
#include "resource.h"
#include "advpext.h"
#include "download.h"
#include "patchdownload.h"
#include "util.h"
extern "C"
{
#include "patchapi.h"
#include "redblack.h"
#include "crc32.h"
}
extern HINF g_hInf;
extern HINSTANCE g_hInstance;
extern HWND g_hProgressDlg;
extern BOOL g_fAbort;
HANDLE g_hDownloadProcess = NULL;
HRESULT WINAPI DownloadAndPatchFiles(DWORD dwFileCount, DOWNLOAD_FILEINFO* pFileInfo, LPCSTR lpszUrl,
LPCSTR lpszPath, PATCH_DOWNLOAD_CALLBACK pfnCallback, LPVOID lpvContext)
{
HRESULT hr = S_OK;
CSiteMgr csite;
hr = LoadSetupAPIFuncs();
if(FAILED(hr))
{
return hr;
}
SetProgressText(IDS_INIT);
//Download the sites.dat file
hr = csite.Initialize(lpszUrl);
if(FAILED(hr))
{
return hr;
}
CPatchDownloader cpdwn(pFileInfo, dwFileCount, pfnCallback);
return cpdwn.InternalDownloadAndPatchFiles(lpszPath, &csite, lpvContext);
}
HRESULT CPatchDownloader::InternalDownloadAndPatchFiles(LPCTSTR lpszPath, CSiteMgr* pSite, LPVOID lpvContext)
{
HRESULT hr = S_OK;
PATCH_THREAD_INFO PatchThreadInfo;
HANDLE hThreadPatcher = NULL;
ULONG DownloadClientId = 0;
int nCount = 0;
LPTSTR lpszUrl;
BOOL fUseWin9xDirectory = FALSE;
if(!GetTempPath(sizeof(m_lpszDownLoadDir), m_lpszDownLoadDir))
{
//Unable to get temp folder, Create a folder in the path sent to us
wsprintf(m_lpszDownLoadDir, "%s\\%s", lpszPath, "AdvExt");
}
//Since the binary is different for NT and 9x, because of binding, we cannot put the files
//under same directory on server. So for 9x put it under a subdirectory and modify the
//url accordingly.
HKEY hKey;
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionEx(&osvi);
if(VER_PLATFORM_WIN32_NT != osvi.dwPlatformId &&
ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Advanced INF Setup", 0,
KEY_ALL_ACCESS, &hKey))
{
DWORD dwSize = sizeof(DWORD);
if(ERROR_SUCCESS == RegQueryValueEx(hKey, "Usewin9xDirectory", 0, 0,
(LPBYTE)&fUseWin9xDirectory, &dwSize))
{
RegDeleteValue(hKey, "Usewin9xDirectory");
}
RegCloseKey(hKey);
}
if (DownloadClientId == 0)
{
// Need to generate a unique DownloadClientId for this machine, but
// it needs to be consistent (persistent) if same machine downloads
// twice, even across process destroy/restart. First we check the
// registry to see if we have previously generated a unique Id for
// this machine, and use that if we find it. Otherwise, we generate
// a unique DownloadClientId and store it in the registry so future
// instances will use the same value.
//
LONG RegStatus;
HKEY hKey;
DWORD dwHow;
DWORD dwValueSize;
DWORD dwValueType;
DWORD dwValue;
RegStatus = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Advanced INF Setup\\AdvExt",
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&hKey,
&dwHow
);
if ( RegStatus == ERROR_SUCCESS )
{
dwValueSize = sizeof(dwValue);
RegStatus = RegQueryValueEx(hKey, "DownloadClientId", NULL, &dwValueType, (LPBYTE)&dwValue, &dwValueSize);
dwValue &= 0xFFFFFFF0;
if ((RegStatus == ERROR_SUCCESS) && (dwValueType == REG_DWORD) && (dwValue != 0))
{
DownloadClientId = dwValue;
}
else
{
DownloadClientId = GenerateUniqueClientId();
dwValue = DownloadClientId;
RegSetValueEx(hKey, "DownloadClientId", 0, REG_DWORD, (LPBYTE)&dwValue, sizeof(dwValue));
}
RegCloseKey( hKey );
}
else
{
// Failed to open/create registry key, so fall back to just
// creating a unique ID for this process instance. At least
// it will show the same client id if the user hits "retry".
//
DownloadClientId = GenerateUniqueClientId();
}
}
m_hSubAllocator = CreateSubAllocator(0x10000, 0x10000);
if(!m_hSubAllocator)
{
hr = HRESULT_FROM_WIN32(GetLastError());
WriteToLog("Memory allocation failed. Can't do much. Exiting with hr=%1!lx!\n", hr);
goto done;
}
//Set the parameters that needs to be passed on to the thread.
if(!m_lpfnCallback)
{
m_lpfnCallback = PatchCallback;
m_lpvContext = (LPVOID)lpszPath;
}
else
{
m_lpvContext = lpvContext;
}
PatchThreadInfo.hFileDownloadEvent = _hDL;
PatchThreadInfo.FileListInfo.FileList = m_lpFileInfo;
PatchThreadInfo.FileListInfo.FileCount = m_dwFileCount;
PatchThreadInfo.FileListInfo.Callback = m_lpfnCallback;
PatchThreadInfo.FileListInfo.CallbackContext = m_lpvContext;
PatchThreadInfo.lpdwnProgressInfo = &m_DownloadInfo;
m_DownloadInfo.dwFilesRemaining = m_dwFileCount;
m_DownloadInfo.dwFilesToDownload = m_dwFileCount;
m_DownloadInfo.dwBytesToDownload = 0;
m_DownloadInfo.dwBytesRemaining = 0;
//Create an event to signal patchthread is ready to process download request
g_hDownloadProcess = CreateEvent(NULL, TRUE, FALSE, NULL);
if(!g_hDownloadProcess)
{
hr = HRESULT_FROM_WIN32(GetLastError());
WriteToLog("Create event failed with error code:%1!lx!\n", hr);
goto done;
}
//Do till we have download files or we retry 3 times
while(nCount++ < 3 && m_DownloadInfo.dwFilesRemaining && !g_fAbort)
{
WriteToLog("\n%1!d! try: Number of Files:%2!d!\n", nCount, m_DownloadInfo.dwFilesRemaining);
_hDLResult = 0;
ResetEvent(g_hDownloadProcess);
hThreadPatcher = CreateThread(NULL, 0, PatchThread, &PatchThreadInfo, 0, &m_dwPatchThreadId);
if(!hThreadPatcher)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto done;
}
//Generate the request buffer that would be sent on POST
hr = CreateRequestBuffer(DownloadClientId);
if(FAILED(hr))
{
WriteToLog("\nCreateRequestBuffer failed with error code:%1!lx!\n", hr);
goto done;
}
//Get the url from where bytes needs to be downloaded.
if(!pSite->GetNextSite(&lpszUrl, &m_lpszSiteName))
{
WriteToLog("GetNextSite returned false. No site info??");
hr = E_UNEXPECTED;
goto done;
}
TCHAR szURL[INTERNET_MAX_URL_LENGTH];
if(fUseWin9xDirectory)
{
lstrcpy(szURL, lpszUrl);
if(*(lpszUrl + lstrlen(lpszUrl) - 1) == '/')
{
lstrcat(szURL, "win9x");
}
else
{
lstrcat(szURL, "/win9x");
}
lpszUrl = szURL;
}
//Notify callback we are about to begin download
ProtectedPatchDownloadCallback(m_lpfnCallback, PATCH_DOWNLOAD_BEGIN, (LPVOID)lpszUrl, m_lpvContext);
hr = DoDownload(lpszUrl, NULL);
WriteToLog("DownloadFile returned:%1!lx!\n\n", hr);
SetProgressText(IDS_CLEANUP);
//Ask the patch thread to quit once it finishes download.
SetEvent(_hDL);
//Wait till patch thread finishes its work
while(1)
{
DWORD dw = MsgWaitForMultipleObjects(1, &hThreadPatcher, FALSE, 1000, QS_ALLINPUT);
if(dw == WAIT_OBJECT_0)
{
break;
}
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
DispatchMessage(&msg);
}
}
CloseHandle(hThreadPatcher);
hThreadPatcher = NULL;
//Setup the downloadinfo structure, incase we need to re-download some files
m_DownloadInfo.dwFilesToDownload = m_DownloadInfo.dwFilesRemaining;
m_DownloadInfo.dwBytesToDownload = 0;
m_DownloadInfo.dwBytesRemaining = 0;
if(m_DownloadInfo.dwFilesToDownload)
{
SetProgressText(IDS_RETRY);
}
m_dwServerFileCount=0;
ResetEvent(_hDL);
}
done:
if(g_hDownloadProcess)
{
CloseHandle(g_hDownloadProcess);
}
if(!hr && m_DownloadInfo.dwFilesToDownload)
{
hr = E_FAIL;
WriteToLog("\nSome files could not be downloaded\n");
}
WriteToLog("DownloadAndPatchFiles returning:%1!lx!\n", hr);
return hr;
}
HRESULT CPatchDownloader :: CreateRequestBuffer(DWORD dwDownloadClientID)
{
LPTSTR lpRequestPointer, lpFileNamePortionOfRequest;
HRESULT hr = S_OK;
DWORD i;
DWORD dwHeapSize = 64*1024;
if(!m_lpFileInfo)
{
return E_INVALIDARG;
}
m_lpszRequestBuffer = (LPTSTR)ResizeBuffer(NULL, dwHeapSize, FALSE);
if(!m_lpszRequestBuffer)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto done;
}
lpRequestPointer = m_lpszRequestBuffer;
lpRequestPointer += wsprintf(lpRequestPointer, "SessionId:%u\n", dwDownloadClientID);
lpRequestPointer += wsprintf(lpRequestPointer, "FileList:%d\n", m_DownloadInfo.dwFilesToDownload);
WriteToLog("Download ClientID:%1!lx! Number of Files:%2!d!\n", dwDownloadClientID, m_DownloadInfo.dwFilesToDownload);
lpFileNamePortionOfRequest = lpRequestPointer;
for(i=0; i < m_dwFileCount; i++)
{
if ((DWORD)( lpRequestPointer - m_lpszRequestBuffer ) > (DWORD)( dwHeapSize - (DWORD)MAX_PATH ))
{
dwHeapSize = dwHeapSize * 2;
m_lpszRequestBuffer = (LPTSTR)ResizeBuffer(m_lpszRequestBuffer, dwHeapSize, FALSE);
if(!m_lpszRequestBuffer)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto done;
}
}
if(m_lpFileInfo[i].dwFlags != PATCHFLAG_DOWNLOAD_NEEDED)
{
//Probably already downloaded
continue;
}
if ((m_lpFileInfo[i].lpszExistingFilePatchSignature == NULL ) ||
(*m_lpFileInfo[i].lpszExistingFilePatchSignature == 0 ))
{
// No file to patch from, request whole file.
lpRequestPointer += wsprintf(lpRequestPointer, "%s\n", m_lpFileInfo[i].lpszFileNameToDownload);
}
else
{
lpRequestPointer += wsprintf(lpRequestPointer, "%s,%s\n", m_lpFileInfo[i].lpszFileNameToDownload,
m_lpFileInfo[i].lpszExistingFilePatchSignature);
}
}
// Now terminate list with "empty" entry.
*lpRequestPointer++ = '\n';
*lpRequestPointer++ = 0;
m_dwRequestDataLength = lpRequestPointer - m_lpszRequestBuffer;
// Now lowercase all the filenames in the request (this offloads the case consistency work from
// the server -- the server expects the request to be all lowercase).
MyLowercase(lpFileNamePortionOfRequest);
WriteToLog("RequestBuffer: Size=%1!d!\n\n", m_dwRequestDataLength);
WriteToLog("%1", m_lpszRequestBuffer);
done:
if(FAILED(hr))
{
ResizeBuffer(m_lpszRequestBuffer, 0, 0);
}
WriteToLog("\nCreateRequestBuffer returning %1!lx!\n", hr);
return hr;
}
CPatchDownloader::CPatchDownloader(DOWNLOAD_FILEINFO* pdwn, DWORD dwFileCount, PATCH_DOWNLOAD_CALLBACK lpfn)
{
m_lpFileInfo = pdwn;
m_dwFileCount = dwFileCount;
m_lpfnCallback = lpfn;
m_hCurrentFileHandle = NULL;
m_dwCurrentFileIndex = 0;
m_lpFileList = NULL;
m_dwServerFileCount = 0;
}
CPatchDownloader::~CPatchDownloader()
{
DestroySubAllocator(m_hSubAllocator);
}
STDMETHODIMP CPatchDownloader::GetBindInfo( DWORD *grfBINDF, BINDINFO *pbindInfo)
{
*grfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA | BINDF_RESYNCHRONIZE | BINDF_NOWRITECACHE;
pbindInfo->cbSize = sizeof(BINDINFO);
memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM));
pbindInfo->stgmedData.tymed = TYMED_HGLOBAL;
pbindInfo->stgmedData.hGlobal = m_lpszRequestBuffer;
pbindInfo->grfBindInfoF = BINDINFOF_URLENCODESTGMEDDATA;
pbindInfo->dwBindVerb = BINDVERB_POST;
pbindInfo->szCustomVerb = NULL;
pbindInfo->cbstgmedData = m_dwRequestDataLength;
pbindInfo->szExtraInfo = NULL;
return(NOERROR);
}
STDMETHODIMP CPatchDownloader::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR pwzStatusText)
{
int PatchStatusCode = -1;
UINT uID;
switch(ulStatusCode)
{
case BINDSTATUS_FINDINGRESOURCE:
PatchStatusCode = PATCH_DOWNLOAD_FINDINGSITE;
uID = IDS_BINDS_FINDING;
break;
case BINDSTATUS_CONNECTING:
PatchStatusCode = PATCH_DOWNLOAD_CONNECTING;
uID = IDS_BINDS_CONN;
break;
case BINDSTATUS_BEGINDOWNLOADDATA:
PatchStatusCode = PATCH_DOWNLOAD_DOWNLOADINGDATA;
uID = IDS_BINDS_DOWNLOADING;
break;
case BINDSTATUS_ENDDOWNLOADDATA:
PatchStatusCode = PATCH_DOWNLOAD_ENDDOWNLOADINGDATA;
uID = IDS_BINDS_ENDDOWNLOAD;
break;
}
if(PatchStatusCode != -1 && pwzStatusText)
{
TCHAR szBuffer[MAX_PATH], szTemplate[MAX_PATH];
LoadString(g_hInstance, uID, szTemplate, sizeof(szTemplate));
wsprintf(szBuffer, szTemplate, m_lpszSiteName);
ProtectedPatchDownloadCallback(m_lpfnCallback, (PATCH_DOWNLOAD_REASON)PatchStatusCode, szBuffer, m_lpvContext);
}
return NOERROR;
}
STDMETHODIMP CPatchDownloader::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC *pFmtetc, STGMEDIUM *pstgmed)
{
HRESULT hr = NOERROR;
TCHAR szBuffer[4096];
DWORD dwRead = 0, dwWritten=0;
do
{
hr = pstgmed->pstm->Read(szBuffer, 4096, &dwRead);
if((SUCCEEDED(hr) || (hr == E_PENDING)) && dwRead > 0)
{
if(!ProcessDownloadChunk(szBuffer, dwRead))
{
WriteToLog("ProcessDownloadChunk returning FALSE. Aborting downloading\n");
hr = E_ABORT;
}
}
} while (hr == NOERROR && !g_fAbort);
if(g_fAbort)
Abort();
return hr;
}
BOOL CPatchDownloader :: ProcessDownloadChunk(LPTSTR lpBuffer, DWORD dwLength)
{
CHAR TargetFile[ MAX_PATH ];
ULONG Actual;
ULONG WriteSize;
BOOL Success;
if ( m_dwServerFileCount == 0 )
{
//
// Haven't processed headers yet.
//
// We expect header to look like this:
//
// "<head><title>"
// "Download Stream of Files"
// "</title></head>\n"
// "<body>\n"
// "FileList:%d\n"
// "filename,%d\n"
// "filename,%d\n"
// ...etc...
// "filename,%d\n"
// "</body>\n"
//
// BUGBUG: if headers don't all fit in first chunk, we're screwed.
//
PCHAR EndOfHeader;
PCHAR FileCountText;
PCHAR FileNameText;
PCHAR FileSizeText;
ULONG FileSize;
ULONG FileBytes;
ULONG i;
PCHAR p;
EndOfHeader = ScanForSequence(lpBuffer, dwLength,
"</body>\n",
sizeof( "</body>\n" ) - 1 // not including terminator
);
if( EndOfHeader == NULL ) {
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
EndOfHeader += sizeof( "</body>\n" ) - 1 ;
p = ScanForSequence(lpBuffer, EndOfHeader - lpBuffer, "FileList:", sizeof( "FileList:" ) - 1);
if ( p == NULL )
{
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
p += sizeof( "FileList:" ) - 1;
FileCountText = p;
p = ScanForChar( p, '\n', EndOfHeader - p );
*p++ = 0;
m_dwServerFileCount = StrToInt( FileCountText );
WriteToLog("Total Files to be downloaded:%1!d!\n", m_dwServerFileCount);
if(m_dwServerFileCount == 0 )
{
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
m_lpFileList = (LPFILE) SubAllocate(m_hSubAllocator, m_dwServerFileCount * sizeof(FILE));
if(!m_lpFileList)
{
return FALSE;
}
m_dwCurrentFileIndex = 0;
FileBytes = 0;
for ( i = 0; i < m_dwServerFileCount; i++ )
{
FileNameText = p;
p = ScanForChar( p, ',', EndOfHeader - p );
if (( p == NULL ) || ( p == FileNameText ))
{
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
*p++ = 0;
FileSizeText = p;
p = ScanForChar( p, '\n', EndOfHeader - p );
if ( p == NULL )
{
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
*p++ = 0;
FileSize = TextToUnsignedNum(FileSizeText);
if ( FileSize == 0 )
{
SetLastError( ERROR_INVALID_DATA );
return FALSE;
}
FileBytes += FileSize;
m_lpFileList[i].dwFileSize = FileSize;
m_lpFileList[i].lpszFileName = MySubAllocStrDup(m_hSubAllocator, FileNameText);
if (m_lpFileList[i].lpszFileName == NULL)
{
return FALSE;
}
WriteToLog("File Name:%1 \t File Size:%2!d!\n", m_lpFileList[i].lpszFileName, m_lpFileList[i].dwFileSize);
}
// If we get to here, all the files in the header have been processed,
// so we can set the state variables and continue with parsing raw
// file data.
m_DownloadInfo.dwBytesToDownload = FileBytes;
m_DownloadInfo.dwBytesRemaining = FileBytes;
dwLength -= ( EndOfHeader - lpBuffer );
lpBuffer = EndOfHeader;
WriteToLog("\nTotal %1!d! bytes(%2!d! Files) to be downloaded\n", FileBytes, m_dwServerFileCount);
}
// Process raw file info.
m_DownloadInfo.dwBytesRemaining -= dwLength;
if(!ProtectedPatchDownloadCallback(m_lpfnCallback, PATCH_DOWNLOAD_PROGRESS, (LPVOID)&m_DownloadInfo, m_lpvContext))
{
g_fAbort = TRUE;
return FALSE;
}
while(dwLength > 0)
{
if (m_hCurrentFileHandle == NULL || m_hCurrentFileHandle == INVALID_HANDLE_VALUE)
{
if (m_dwCurrentFileIndex >= m_dwServerFileCount)
{
SetLastError( ERROR_INVALID_DATA );
return FALSE; // more data than we expected
}
// Now open this file.
CombinePaths(m_lpszDownLoadDir, m_lpFileList[m_dwCurrentFileIndex].lpszFileName, TargetFile );
m_dwCurrentFileSize = m_lpFileList[m_dwCurrentFileIndex].dwFileSize;
m_dwCurrFileSizeRemaining = m_dwCurrentFileSize;
m_hCurrentFileHandle = CreateFile(TargetFile, GENERIC_WRITE, FILE_SHARE_READ, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
if (m_hCurrentFileHandle == INVALID_HANDLE_VALUE )
{
return FALSE;
}
}
WriteSize = min( dwLength, m_dwCurrFileSizeRemaining);
Success = WriteFile(m_hCurrentFileHandle, lpBuffer, WriteSize, &Actual, NULL);
if(!Success)
{
return FALSE;
}
if(Actual != WriteSize)
{
SetLastError( ERROR_INVALID_PARAMETER );
WriteToLog("Error:Actual size not equal to write size for %1. Aborting\n",
m_lpFileList[m_dwCurrentFileIndex].lpszFileName);
return FALSE;
}
m_dwCurrFileSizeRemaining -= WriteSize;
if(m_dwCurrFileSizeRemaining == 0 )
{
CloseHandle(m_hCurrentFileHandle);
m_hCurrentFileHandle = NULL;
// Pass this file off to the patch thread.
LPTSTR lpszFileName = (LPTSTR)ResizeBuffer(NULL, MAX_PATH, FALSE);
CombinePaths(m_lpszDownLoadDir, m_lpFileList[m_dwCurrentFileIndex].lpszFileName, TargetFile );
lstrcpy(lpszFileName, TargetFile);
WaitForSingleObject(g_hDownloadProcess, 10000);
PostThreadMessage(m_dwPatchThreadId, WM_FILEAVAILABLE, 0, (LPARAM)lpszFileName);
m_dwCurrentFileIndex += 1;
}
lpBuffer += WriteSize;
dwLength -= WriteSize;
}
return TRUE;
}
DWORD WINAPI PatchThread(IN LPVOID ThreadParam)
{
PPATCH_THREAD_INFO PatchThreadInfo = (PPATCH_THREAD_INFO) ThreadParam;
PFILE_LIST_INFO FileListInfo = &PatchThreadInfo->FileListInfo;
PDOWNLOAD_INFO ProgressInfo = PatchThreadInfo->lpdwnProgressInfo;
NAME_TREE FileNameTree;
PNAME_NODE FileNameNode;
PDOWNLOAD_FILEINFO FileInfo;
DWORD Status;
BOOL bIsPatch;
HANDLE hSubAllocator;
ULONG i;
BOOL fSuccess, fQuit = FALSE;
MSG msg;
//
// First thing we need to do is construct a btree of the filenames
// we expect to get in the queue so we can quickly find the corresponding
// FileList entry when given a filename by the downloader. It will take
// the downloader a little while to get connected, so this CPU intensive
// task shouldn't slow anything down.
//
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
hSubAllocator = CreateSubAllocator( 0x10000, 0x10000 );
if ( hSubAllocator == NULL )
{
return ERROR_NOT_ENOUGH_MEMORY;
}
NameRbInitTree( &FileNameTree, hSubAllocator );
TCHAR SourceFileName[MAX_PATH];
for ( i = 0; i < FileListInfo->FileCount; i++ )
{
if(FileListInfo->FileList[ i ].dwFlags != PATCHFLAG_DOWNLOAD_NEEDED)
{
//Probably already downloaded and this is the second attempt
continue;
}
lstrcpy( SourceFileName, FileListInfo->FileList[ i ].lpszFileNameToDownload);
MyLowercase( SourceFileName );
FileNameNode = NameRbInsert(&FileNameTree, SourceFileName);
if ( FileNameNode == NULL )
{
DestroySubAllocator( hSubAllocator );
return ERROR_NOT_ENOUGH_MEMORY;
}
if (FileNameNode->Context != NULL )
{
//
// BUGBUG: Same filename in list twice. Should never be the
// case since we check for duplicates before putting
// them in the queue.
//
}
FileNameNode->Context = &FileListInfo->FileList[ i ];
// Now add another node in the tree based on the compressed filename.
ConvertToCompressedFileName( SourceFileName );
FileNameNode = NameRbInsert(&FileNameTree, SourceFileName);
if ( FileNameNode == NULL )
{
DestroySubAllocator( hSubAllocator );
return ERROR_NOT_ENOUGH_MEMORY;
}
if ( FileNameNode->Context != NULL )
{
// BUGBUG: Same filename in list twice. This can happen if two
// different files collide on a compressed name (like
// foo.db1 and foo.db2 colliding on foo.db_).
//
// We don't have a good solution for this right now.
//
}
//Set the contect to the file info. When we get back the file from server, we can get the full
//info about this
FileNameNode->Context = &FileListInfo->FileList[ i ];
//Make sure we are not asked to quit
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) && msg.message == WM_QUIT)
{
goto done;
}
}
//
// Now wait for file downloads to be delivered to us.
//
SetEvent(g_hDownloadProcess);
while (!g_fAbort && !fQuit)
{
LPTSTR lpszDownloadFileName, lpszSourceFileName;
TCHAR szRealFileName[MAX_PATH];
//
// We're going to wait here with a timeout so that if the download
// is stuck in InternetReadFile waiting for data, we can keep a
// heartbeat going to the progress dialog and also check for cancel.
//
Status = MsgWaitForMultipleObjects(1, &PatchThreadInfo->hFileDownloadEvent, FALSE, 1000, QS_ALLINPUT);
if (Status == WAIT_TIMEOUT )
{
//Keep updating the callback
fSuccess = ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_PROGRESS,
ProgressInfo, FileListInfo->CallbackContext);
if (!fSuccess)
{
g_fAbort = TRUE;
break;
}
continue;
}
if(Status == WAIT_OBJECT_0)
{
fQuit = TRUE;
}
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_FILEAVAILABLE)
{
lpszDownloadFileName = (LPTSTR)msg.lParam;
}
else
{
continue;
}
// Ok, now we have a filename lpszDownloadFileName that was just downloaded to the
// temp directory.The filename may be in one of the following
// forms:
// foo.dll
// foo.dl_
// foo.dll._p
//
// We have both "foo.dll" and "foo.dl_" in our name tree, but we
// don't have "foo.dll._p", so we look for that form of the name
// first and convert it to "foo.dll" before looking in name tree.
fSuccess = TRUE;
lpszSourceFileName = PathFindFileName(lpszDownloadFileName);
ASSERT(lpszSourceFileName);
lstrcpyn(szRealFileName, lpszDownloadFileName, lpszSourceFileName - lpszDownloadFileName + 1);
MyLowercase(lpszSourceFileName);
LPTSTR lpExt = PathFindExtension(lpszSourceFileName);
bIsPatch = FALSE;
if(lpExt && !lstrcmp(lpExt, "._p"))
{
bIsPatch = TRUE;
*lpExt = 0; // truncate trailing "._p" to leave base file name
}
FileNameNode = NameRbFind( &FileNameTree, lpszSourceFileName);
if ( bIsPatch )
{
*lpExt = '.'; // restore complete patch source file name
}
if (FileNameNode != NULL)
{
FileInfo = (PDOWNLOAD_FILEINFO)FileNameNode->Context;
lstrcat(szRealFileName, FileInfo->lpszFileNameToDownload);
if ( bIsPatch )
{
fSuccess = ApplyPatchToFile(
lpszDownloadFileName, // patch file
FileInfo->lpszExistingFileToPatchFrom, // old file
szRealFileName, // new file
0
);
}
else
{
FixTimeStampOnCompressedFile(lpszSourceFileName);
if(lstrcmpi(lpszDownloadFileName, szRealFileName))
{
fSuccess = MySetupDecompressOrCopyFile(
lpszDownloadFileName, // compressed or whole file
szRealFileName // new file
);
}
}
if (fSuccess)
{
//Notify callback. If it thinks that the hash is incorrect, don't mark the file
//as downloaded, so that we may retry download of this file.
fSuccess = VerifyHash(szRealFileName);
if(fSuccess)
{
fSuccess = ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_FILE_COMPLETED,
szRealFileName, FileListInfo->CallbackContext);
if(fSuccess == FALSE)
{
//If callback returned false, we need to abort
WriteToLog("\tDownload complete callback returned false. Aborting\n");
ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_ABORT,
NULL, FileListInfo->CallbackContext);
break;
}
else
{
FileInfo->dwFlags = 0;
//Notify callback that 1 file was successfully downloaded
WriteToLog("\tSuccesssfully downloaded %1\n", FileInfo->lpszFileNameToDownload);
ProgressInfo->dwFilesRemaining -= 1;
fSuccess = ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_PROGRESS,
ProgressInfo, FileListInfo->CallbackContext);
if(!fSuccess)
{
g_fAbort = TRUE;
return FALSE;
}
}
}
else
{
//Mark it so that we resend the request. Remove patch signature so we get full files instead
// of patches.
WriteToLog("\tHash Incorrect. Need to Re-download %1\n", FileInfo->lpszFileNameToDownload);
FileInfo->dwFlags = PATCHFLAG_DOWNLOAD_NEEDED;
if(FileInfo->lpszExistingFilePatchSignature)
{
LocalFree(FileInfo->lpszExistingFilePatchSignature);
FileInfo->lpszExistingFilePatchSignature = NULL;
}
}
}
else
{
// Patch or decompress failed. notify callback it failed.
WriteToLog("\tPatch or decompression failed for %1\n", FileInfo->lpszFileNameToDownload);
fSuccess = ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_FILE_FAILED,
FileInfo, FileListInfo->CallbackContext);
//If callback says to continue or retry download, we do so. If it needs to abort, it return 0
if (!fSuccess)
{
ProtectedPatchDownloadCallback(FileListInfo->Callback, PATCH_DOWNLOAD_ABORT,
NULL, FileListInfo->CallbackContext);
break;
}
if(fSuccess == PATCH_DOWNLOAD_FLAG_RETRY)
{
FileInfo->dwFlags = PATCHFLAG_DOWNLOAD_NEEDED;
if(FileInfo->lpszExistingFilePatchSignature)
{
LocalFree(FileInfo->lpszExistingFilePatchSignature);
FileInfo->lpszExistingFilePatchSignature = NULL;
}
}
else if(fSuccess == PATCH_DOWNLOAD_FLAG_CONTINUE)
{
FileInfo->dwFlags = 0;
}
}
//Delete the temp file. We might be having 2 temp files if this was a patch.
if(lstrcmpi(lpszDownloadFileName, szRealFileName))
{
DeleteFile(lpszDownloadFileName);
}
DeleteFile(szRealFileName);
ResizeBuffer(lpszDownloadFileName, 0, 0);
}
}
}
done:
DestroySubAllocator( hSubAllocator ); // free entire btree
return 0;
}
BOOL VerifyHash(LPTSTR lpszFile)
{
TCHAR szHashFromInf[40];
TCHAR szHashFromFile[40];
// Verify MD5 of new file against the MD5 from inf. If we cannot verify
// the MD5 for any reason, then leave the file alone (success).
// Only if computed MD5 does not match do we reject the file.
LPTSTR lpFileName = PathFindFileName(lpszFile);
if(GetHashidFromINF(lpFileName, szHashFromInf, sizeof(szHashFromInf)) &&
GetFilePatchSignatureA(lpszFile, PATCH_OPTION_SIGNATURE_MD5, NULL, 0, 0, 0, 0,
sizeof(szHashFromFile), szHashFromFile))
{
if (lstrcmpi(szHashFromFile, szHashFromInf))
{
WriteToLog("Hash Incorrect. File hash: %1 Inf hash: %2. Need to Re-download %3\n",
szHashFromFile, szHashFromInf, lpFileName);
return FALSE;
}
}
else
{
WriteToLog("Warning:Could not get hashid for %1 in inf file\n", lpFileName);
}
return TRUE;
}
BOOL ProtectedPatchDownloadCallback(PATCH_DOWNLOAD_CALLBACK Callback, IN PATCH_DOWNLOAD_REASON CallbackReason,
IN PVOID CallbackData, IN PVOID CallBackContext)
{
BOOL Success = TRUE;
if (Callback != NULL )
{
__try
{
Success = Callback(CallbackReason, CallbackData, CallBackContext);
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
SetLastError( GetExceptionCode());
Success = FALSE;
}
}
return Success;
}
BOOL WINAPI PatchCallback(PATCH_DOWNLOAD_REASON Reason, PVOID lpvInfo, PVOID lpvCallBackContext)
{
switch (Reason)
{
case PATCH_DOWNLOAD_ENDDOWNLOADINGDATA:
case PATCH_DOWNLOAD_CONNECTING:
case PATCH_DOWNLOAD_FINDINGSITE:
case PATCH_DOWNLOAD_DOWNLOADINGDATA:
{
LPTSTR lpsz = (LPTSTR)lpvInfo;
lpsz[90] = NULL;
SetProgressText(lpsz);
}
break;
case PATCH_DOWNLOAD_PROGRESS:
{
char szBuffer[100], szText[MAX_PATH];
PDOWNLOAD_INFO ProgressInfo = (PDOWNLOAD_INFO)lpvInfo;
LoadString(g_hInstance, IDS_BYTEINFO, szBuffer, sizeof(szBuffer));
DWORD dwBytesDownloaded = ProgressInfo->dwBytesToDownload - ProgressInfo->dwBytesRemaining;
wsprintf(szText, szBuffer, dwBytesDownloaded, ProgressInfo->dwBytesToDownload);
if(g_hProgressDlg && ProgressInfo->dwBytesToDownload)
{
SetProgressText(szText);
}
break;
}
case PATCH_DOWNLOAD_FILE_COMPLETED: // AdditionalInfo is Source file downloaded
{
TCHAR szDstFile[MAX_PATH];
LPTSTR lpFileName = PathFindFileName((LPCTSTR)lpvInfo);
CombinePaths((LPTSTR)lpvCallBackContext, lpFileName, szDstFile);
CopyFile((LPCTSTR)lpvInfo, szDstFile, FALSE);
}
break;
case PATCH_DOWNLOAD_FILE_FAILED:
//ask it to retry
return PATCH_DOWNLOAD_FLAG_RETRY;
default:
break;
}
return TRUE;
}
| 33.178227 | 124 | 0.542154 | npocmaka |
48fb908b5742af84c3a526c8030fea32af382ba7 | 3,726 | cpp | C++ | src/meshInfo/geometry.cpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | src/meshInfo/geometry.cpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | src/meshInfo/geometry.cpp | guhanfeng/HSF | d2f091e990bb5a18473db0443872e37de6b6a83f | [
"Apache-2.0"
] | null | null | null | /**
* @file: geometry.cpp
* @author: Liu Hongbin
* @brief:
* @date: 2019-11-28 10:57:45
* @last Modified by: lenovo
* @last Modified time: 2019-11-28 16:14:40
*/
#include "geometry.hpp"
namespace HSF
{
scalar calculateQUADArea(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z)
{
scalar v1[3], v2[3], v3[3];
/// v1 = coord(1)-coord(0)
v1[0] = x[1] - x[0];
v1[1] = y[1] - y[0];
v1[2] = z[1] - z[0];
/// v2 = coord(3)-coord(0)
v2[0] = x[3] - x[0];
v2[1] = y[3] - y[0];
v2[2] = z[3] - z[0];
/// v3 = v1xv2
v3[0] = v1[1]*v2[2]-v2[1]*v1[2];
v3[1] = v1[2]*v2[0]-v2[2]*v1[0];
v3[2] = v1[0]*v2[1]-v2[0]*v1[1];
// v3(1) = v1(2)*v2(3)-v2(2)*v1(3)
// v3(2) = v1(3)*v2(1)-v1(1)*v2(3)
// v3(3) = v1(1)*v2(2)-v2(1)*v1(2)
return sqrt(v3[0]*v3[0]+v3[1]*v3[1]+v3[2]*v3[2]);
}
scalar calculateTRIArea(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z)
{
}
scalar calculateFaceArea(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, label nnodes)
{
switch(nnodes)
{
// case 3: return calculateTRIArea(x, y, z);
case 4: return calculateQUADArea(x, y, z); break;
default:
Terminate("calculateFaceArea", "unrecognized face type");
}
}
void calculateQUADNormVec(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, scalar* normVec)
{
scalar v1[3], v2[3], v3[3];
// for (int i = 0; i < x.size(); ++i)
// {
// printf("%f, %f, %f\n", x[i], y[i], z[i]);
// }
/// v1 = coord(1)-coord(0)
v1[0] = x[1] - x[0];
v1[1] = y[1] - y[0];
v1[2] = z[1] - z[0];
/// v2 = coord(3)-coord(0)
v2[0] = x[3] - x[0];
v2[1] = y[3] - y[0];
v2[2] = z[3] - z[0];
/// v3 = v1xv2
v3[0] = v1[1]*v2[2]-v2[1]*v1[2];
v3[1] = v1[2]*v2[0]-v2[2]*v1[0];
v3[2] = v1[0]*v2[1]-v2[0]*v1[1];
scalar norm = sqrt(v3[0]*v3[0]+v3[1]*v3[1]+v3[2]*v3[2]);
normVec[0] = v3[0]/norm;
normVec[1] = v3[1]/norm;
normVec[2] = v3[2]/norm;
// printf("normVec: %f, %f, %f\n", normVec[0], normVec[1], normVec[2]);
}
void calculateFaceNormVec(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, label nnodes, scalar* normVec)
{
switch(nnodes)
{
case 4: calculateQUADNormVec(x, y, z, normVec); break;
default:
Terminate("calculateFaceNormVec", "unrecognized face type");
}
}
void calculateFaceCenter(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, label nnodes, scalar* center)
{
center[0] = 0;
center[1] = 0;
center[2] = 0;
for (int i = 0; i < nnodes; ++i)
{
center[0] += x[i];
center[1] += y[i];
center[2] += z[i];
}
center[0] /= nnodes;
center[1] /= nnodes;
center[2] /= nnodes;
}
scalar calculateCellVol(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, label nnodes)
{
switch(nnodes)
{
// case 3: return calculateTRIArea(x, y, z);
case 8: return calculateHEXAVol(x, y, z); break;
default:
Terminate("calculateCellVol", "unrecognized cell type");
}
}
scalar calculateHEXAVol(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z)
{
scalar v1[3], v2[3], v3[3];
v1[0] = x[1] - x[0];
v1[1] = y[1] - y[0];
v1[2] = z[1] - z[0];
v2[0] = x[3] - x[0];
v2[1] = y[3] - y[0];
v2[2] = z[3] - z[0];
v3[0] = x[4] - x[0];
v3[1] = y[4] - y[0];
v3[2] = z[4] - z[0];
scalar vol;
vol = v3[0]*(v1[1]*v2[2]-v2[1]*v1[2]);
vol = vol+v3[1]*(v1[2]*v2[0]-v1[0]*v2[2]);
vol = vol+v3[2]*(v1[0]*v2[1]-v2[0]*v1[1]);
return vol;
}
void calculateCellCenter(const Array<scalar>& x, const Array<scalar>& y,
const Array<scalar>& z, label nnodes, scalar* center)
{
calculateFaceCenter(x, y, z, nnodes, center);
}
} | 23 | 75 | 0.553945 | guhanfeng |
48fcaffb5e2c08a64895be09ec2083923ec00ff5 | 1,690 | cpp | C++ | tests/runtime_test.cpp | ElDesalmado/endian_converter | 6cdaae26e01d3f5b77b053fce7a0b494e69b1605 | [
"MIT"
] | null | null | null | tests/runtime_test.cpp | ElDesalmado/endian_converter | 6cdaae26e01d3f5b77b053fce7a0b494e69b1605 | [
"MIT"
] | null | null | null | tests/runtime_test.cpp | ElDesalmado/endian_converter | 6cdaae26e01d3f5b77b053fce7a0b494e69b1605 | [
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <endian_converter/endian_converter.h>
#include <array>
#include <numeric>
#include <algorithm>
using namespace eld;
template<typename T>
bool test_endian_conversion()
{
std::array<uint8_t, sizeof(T)> input{},
expected{},
output{};
std::iota(input.begin(), input.end(), 1);
std::copy(input.rbegin(), input.rend(), expected.begin());
T from{};
std::copy(input.cbegin(), input.cend(), reinterpret_cast<uint8_t *>(&from));
T swapped = swap_endian_v(from);
uint8_t *begin = reinterpret_cast<uint8_t *>(&swapped),
*end = std::next(begin, sizeof(T));
std::copy(begin, end, output.begin());
return std::equal(expected.cbegin(), expected.cend(),
output.cbegin());
}
TEST(EndianConversion, uint8_t)
{
ASSERT_TRUE(test_endian_conversion<uint8_t>());
}
TEST(EndianConversion, uint16_t)
{
ASSERT_TRUE(test_endian_conversion<uint16_t>());
}
TEST(EndianConversion, uint32_t)
{
ASSERT_TRUE(test_endian_conversion<uint32_t>());
}
TEST(EndianConversion, uint64_t)
{
ASSERT_TRUE(test_endian_conversion<uint64_t>());
}
TEST(EndianConversion, TestFloat)
{
ASSERT_TRUE(test_endian_conversion<float>());
}
TEST(EndianConversio, TestDouble)
{
ASSERT_TRUE(test_endian_conversion<double>());
}
struct abc
{
int a;
float b;
int c;
};
TEST(EndianConversio, TestStruct)
{
ASSERT_TRUE(test_endian_conversion<abc>());
}
//TEST(EndianConversio, TestLongDouble)
//{
// ASSERT_TRUE(test_endian_conversion<long double>());
//}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 19.882353 | 80 | 0.672189 | ElDesalmado |
48fe27e5cab98f6389e1795176c3f4da009c043b | 713 | cpp | C++ | CSC201/in-class/Wk8/Wk-8b.cpp | ochudi/ochudi-CSC201 | 3a792beef4780960c725ef9bf6c4af96110c373d | [
"MIT"
] | null | null | null | CSC201/in-class/Wk8/Wk-8b.cpp | ochudi/ochudi-CSC201 | 3a792beef4780960c725ef9bf6c4af96110c373d | [
"MIT"
] | null | null | null | CSC201/in-class/Wk8/Wk-8b.cpp | ochudi/ochudi-CSC201 | 3a792beef4780960c725ef9bf6c4af96110c373d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class csc201
{
public: // access specifier
int score; // attribute score
string name; // attribute name
char grade; // attribute grade
};
int main()
{
csc201 student1;
csc201 student2;
student1.score = 20;
student1.grade = 'F';
student1.name = "Bello Moses Eromosele";
student2.score = 100;
student2.grade = 'A';
student2.name = "Chudi Peter Ofoma";
cout << "(Student 1) Name: " << student1.name << "; Grade: " << student1.grade << "; Score: " << student1.score << endl;
cout << "(Student 2) Name: " << student2.name << "; Grade: " << student2.grade << "; Score: " << student2.score << endl;
}
| 28.52 | 124 | 0.58906 | ochudi |
48fe4f78ca022862ef87f873388f1dacd0873158 | 6,259 | cpp | C++ | libconsensus/ConsensusEngineBase.cpp | michealbrownm/phantom | a1a41a6f9317c26e621952637c7e331c8dacf79d | [
"Apache-2.0"
] | 27 | 2020-09-24T03:14:13.000Z | 2021-11-29T14:00:36.000Z | libconsensus/ConsensusEngineBase.cpp | david2011dzha/phantom | eff76713e03966eb44e20a07806b8d47ec73ad09 | [
"Apache-2.0"
] | null | null | null | libconsensus/ConsensusEngineBase.cpp | david2011dzha/phantom | eff76713e03966eb44e20a07806b8d47ec73ad09 | [
"Apache-2.0"
] | 10 | 2020-09-24T14:34:30.000Z | 2021-02-22T06:50:31.000Z | /*
* @CopyRight:
* FISCO-BCOS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/>
* (c) 2016-2018 fisco-dev contributors.
*/
/**
* @brief : implementation of PBFT consensus
* @file: ConsensusEngineBase.cpp
* @author: yujiechen
* @date: 2018-09-28
*/
#include "ConsensusEngineBase.h"
using namespace dev::eth;
using namespace dev::db;
using namespace dev::blockverifier;
using namespace dev::blockchain;
using namespace dev::p2p;
namespace dev
{
namespace consensus
{
void ConsensusEngineBase::start()
{
if (m_startConsensusEngine)
{
ENGINE_LOG(WARNING) << "[ConsensusEngineBase has already been started]";
return;
}
ENGINE_LOG(INFO) << "[Start ConsensusEngineBase]";
/// start a thread to execute doWork()&&workLoop()
startWorking();
m_startConsensusEngine = true;
}
void ConsensusEngineBase::stop()
{
if (m_startConsensusEngine == false)
{
return;
}
ENGINE_LOG(INFO) << "[Stop ConsensusEngineBase]";
m_startConsensusEngine = false;
doneWorking();
if (isWorking())
{
stopWorking();
// will not restart worker, so terminate it
terminate();
}
}
/// update m_sealing and receiptRoot
dev::blockverifier::ExecutiveContext::Ptr ConsensusEngineBase::executeBlock(Block& block)
{
auto parentBlock = m_blockChain->getBlockByNumber(m_blockChain->number());
BlockInfo parentBlockInfo{parentBlock->header().hash(), parentBlock->header().number(),
parentBlock->header().stateRoot()};
/// reset execute context
return m_blockVerifier->executeBlock(block, parentBlockInfo);
}
void ConsensusEngineBase::checkBlockValid(Block const& block)
{
h256 block_hash = block.blockHeader().hash();
/// check transaction num
if (block.getTransactionSize() > maxBlockTransactions())
{
ENGINE_LOG(DEBUG) << LOG_DESC("checkBlockValid: overthreshold transaction num")
<< LOG_KV("blockTransactionLimit", maxBlockTransactions())
<< LOG_KV("blockTransNum", block.getTransactionSize());
BOOST_THROW_EXCEPTION(
OverThresTransNum() << errinfo_comment("overthreshold transaction num"));
}
/// check the timestamp
if (block.blockHeader().timestamp() > utcTime() && !m_allowFutureBlocks)
{
ENGINE_LOG(DEBUG) << LOG_DESC("checkBlockValid: future timestamp")
<< LOG_KV("timestamp", block.blockHeader().timestamp())
<< LOG_KV("utcTime", utcTime()) << LOG_KV("hash", block_hash.abridged());
BOOST_THROW_EXCEPTION(DisabledFutureTime() << errinfo_comment("Future time Disabled"));
}
/// check the block number
if (block.blockHeader().number() <= m_blockChain->number())
{
ENGINE_LOG(DEBUG) << LOG_DESC("checkBlockValid: old height")
<< LOG_KV("highNumber", m_blockChain->number())
<< LOG_KV("blockNumber", block.blockHeader().number())
<< LOG_KV("hash", block_hash.abridged());
BOOST_THROW_EXCEPTION(InvalidBlockHeight() << errinfo_comment("Invalid block height"));
}
/// check the existence of the parent block (Must exist)
if (!blockExists(block.blockHeader().parentHash()))
{
ENGINE_LOG(DEBUG) << LOG_DESC("checkBlockValid: Parent doesn't exist")
<< LOG_KV("hash", block_hash.abridged());
BOOST_THROW_EXCEPTION(ParentNoneExist() << errinfo_comment("Parent Block Doesn't Exist"));
}
if (block.blockHeader().number() > 1)
{
if (m_blockChain->numberHash(block.blockHeader().number() - 1) !=
block.blockHeader().parentHash())
{
ENGINE_LOG(DEBUG)
<< LOG_DESC("checkBlockValid: Invalid block for unconsistent parentHash")
<< LOG_KV("block.parentHash", block.blockHeader().parentHash().abridged())
<< LOG_KV("parentHash",
m_blockChain->numberHash(block.blockHeader().number() - 1).abridged());
BOOST_THROW_EXCEPTION(
WrongParentHash() << errinfo_comment("Invalid block for unconsistent parentHash"));
}
}
}
void ConsensusEngineBase::updateConsensusNodeList()
{
try
{
std::stringstream s2;
s2 << "[updateConsensusNodeList] Sealers:";
{
WriteGuard l(m_sealerListMutex);
m_sealerList = m_blockChain->sealerList();
/// to make sure the index of all sealers are consistent
std::sort(m_sealerList.begin(), m_sealerList.end());
for (dev::h512 node : m_sealerList)
s2 << node.abridged() << ",";
}
s2 << "Observers:";
dev::h512s observerList = m_blockChain->observerList();
for (dev::h512 node : observerList)
s2 << node.abridged() << ",";
ENGINE_LOG(TRACE) << s2.str();
if (m_lastNodeList != s2.str())
{
ENGINE_LOG(TRACE) << "[updateConsensusNodeList] update P2P List done.";
updateNodeListInP2P();
m_lastNodeList = s2.str();
}
}
catch (std::exception& e)
{
ENGINE_LOG(ERROR)
<< "[updateConsensusNodeList] update consensus node list failed [EINFO]: "
<< boost::diagnostic_information(e);
}
}
void ConsensusEngineBase::updateNodeListInP2P()
{
dev::h512s nodeList = m_blockChain->sealerList() + m_blockChain->observerList();
std::pair<GROUP_ID, MODULE_ID> ret = getGroupAndProtocol(m_protocolId);
m_service->setNodeListByGroupID(ret.first, nodeList);
}
} // namespace consensus
} // namespace dev
| 36.389535 | 99 | 0.634926 | michealbrownm |
48fff39706b19c8bd6ffbfef4cf9ceff56e06f2e | 779 | hpp | C++ | Nacro/SDK/FN_EnemyPawn_Interface_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_EnemyPawn_Interface_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_EnemyPawn_Interface_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function EnemyPawn_Interface.EnemyPawn_Interface_C.Orphaned
struct UEnemyPawn_Interface_C_Orphaned_Params
{
bool IsOrphaned; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
class AFortPawn* AttachedPawn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 26.862069 | 161 | 0.441592 | Milxnor |
5b00dbaed900c014c0f55a03f2d3b29e0ef65f38 | 14,063 | cpp | C++ | jni/paint/PaintPlugin.cpp | mogoweb/video-plugin | c48407e1d524aa6c33ed25c63060c4bd2c089972 | [
"Apache-2.0"
] | null | null | null | jni/paint/PaintPlugin.cpp | mogoweb/video-plugin | c48407e1d524aa6c33ed25c63060c4bd2c089972 | [
"Apache-2.0"
] | null | null | null | jni/paint/PaintPlugin.cpp | mogoweb/video-plugin | c48407e1d524aa6c33ed25c63060c4bd2c089972 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009, The Android Open Source Project
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 APPLE COMPUTER, INC. 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.
*/
#include "PaintPlugin.h"
#include <fcntl.h>
#include <math.h>
#include <string.h>
extern NPNetscapeFuncs* browser;
extern ANPLogInterfaceV0 gLogI;
extern ANPCanvasInterfaceV0 gCanvasI;
extern ANPPaintInterfaceV0 gPaintI;
extern ANPPathInterfaceV0 gPathI;
extern ANPSurfaceInterfaceV0 gSurfaceI;
extern ANPTypefaceInterfaceV0 gTypefaceI;
///////////////////////////////////////////////////////////////////////////////
PaintPlugin::PaintPlugin(NPP inst) : SurfaceSubPlugin(inst) {
m_isTouchActive = false;
m_isTouchCurrentInput = true;
m_activePaintColor = s_redColor;
memset(&m_drawingSurface, 0, sizeof(m_drawingSurface));
memset(&m_inputToggle, 0, sizeof(m_inputToggle));
memset(&m_colorToggle, 0, sizeof(m_colorToggle));
memset(&m_clearSurface, 0, sizeof(m_clearSurface));
// initialize the drawing surface
m_surface = NULL;
m_vm = NULL;
// initialize the path
m_touchPath = gPathI.newPath();
if(!m_touchPath)
gLogI.log(inst, kError_ANPLogType, "----%p Unable to create the touch path", inst);
// initialize the paint colors
m_paintSurface = gPaintI.newPaint();
gPaintI.setFlags(m_paintSurface, gPaintI.getFlags(m_paintSurface) | kAntiAlias_ANPPaintFlag);
gPaintI.setColor(m_paintSurface, 0xFFC0C0C0);
gPaintI.setTextSize(m_paintSurface, 18);
m_paintButton = gPaintI.newPaint();
gPaintI.setFlags(m_paintButton, gPaintI.getFlags(m_paintButton) | kAntiAlias_ANPPaintFlag);
gPaintI.setColor(m_paintButton, 0xFFA8A8A8);
// initialize the typeface (set the colors)
ANPTypeface* tf = gTypefaceI.createFromName("serif", kItalic_ANPTypefaceStyle);
gPaintI.setTypeface(m_paintSurface, tf);
gTypefaceI.unref(tf);
//register for touch events
ANPEventFlags flags = kTouch_ANPEventFlag;
NPError err = browser->setvalue(inst, kAcceptEvents_ANPSetValue, &flags);
if (err != NPERR_NO_ERROR) {
gLogI.log(inst, kError_ANPLogType, "Error selecting input events.");
}
}
PaintPlugin::~PaintPlugin() {
gPathI.deletePath(m_touchPath);
gPaintI.deletePaint(m_paintSurface);
gPaintI.deletePaint(m_paintButton);
surfaceDestroyed();
}
bool PaintPlugin::supportsDrawingModel(ANPDrawingModel model) {
return (model == kSurface_ANPDrawingModel);
}
ANPCanvas* PaintPlugin::getCanvas(ANPRectI* dirtyRect) {
ANPBitmap bitmap;
JNIEnv* env = NULL;
if (!m_surface || m_vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK ||
!gSurfaceI.lock(env, m_surface, &bitmap, dirtyRect)) {
return NULL;
}
ANPCanvas* canvas = gCanvasI.newCanvas(&bitmap);
// clip the canvas to the dirty rect b/c the surface is only required to
// copy a minimum of the dirty rect and may copy more. The clipped canvas
// however will never write to pixels outside of the clipped area.
if (dirtyRect) {
ANPRectF clipR;
clipR.left = dirtyRect->left;
clipR.top = dirtyRect->top;
clipR.right = dirtyRect->right;
clipR.bottom = dirtyRect->bottom;
gCanvasI.clipRect(canvas, &clipR);
}
return canvas;
}
ANPCanvas* PaintPlugin::getCanvas(ANPRectF* dirtyRect) {
ANPRectI newRect;
newRect.left = (int) dirtyRect->left;
newRect.top = (int) dirtyRect->top;
newRect.right = (int) dirtyRect->right;
newRect.bottom = (int) dirtyRect->bottom;
return getCanvas(&newRect);
}
void PaintPlugin::releaseCanvas(ANPCanvas* canvas) {
JNIEnv* env = NULL;
if (m_surface && m_vm->GetEnv((void**) &env, JNI_VERSION_1_4) == JNI_OK) {
gSurfaceI.unlock(env, m_surface);
}
gCanvasI.deleteCanvas(canvas);
}
void PaintPlugin::drawCleanPlugin(ANPCanvas* canvas) {
NPP instance = this->inst();
PluginObject *obj = (PluginObject*) instance->pdata;
// if no canvas get a locked canvas
if (!canvas)
canvas = getCanvas();
if (!canvas)
return;
const float buttonWidth = 60;
const float buttonHeight = 30;
const int W = obj->window->width;
const int H = obj->window->height;
// color the plugin canvas
gCanvasI.drawColor(canvas, 0xFFCDCDCD);
// get font metrics
ANPFontMetrics fontMetrics;
gPaintI.getFontMetrics(m_paintSurface, &fontMetrics);
// draw the input toggle button
m_inputToggle.left = 5;
m_inputToggle.top = H - buttonHeight - 5;
m_inputToggle.right = m_inputToggle.left + buttonWidth;
m_inputToggle.bottom = m_inputToggle.top + buttonHeight;
gCanvasI.drawRect(canvas, &m_inputToggle, m_paintButton);
const char* inputText = m_isTouchCurrentInput ? "Touch" : "Mouse";
gCanvasI.drawText(canvas, inputText, strlen(inputText), m_inputToggle.left + 5,
m_inputToggle.top - fontMetrics.fTop, m_paintSurface);
// draw the color selector button
m_colorToggle.left = (W/2) - (buttonWidth/2);
m_colorToggle.top = H - buttonHeight - 5;
m_colorToggle.right = m_colorToggle.left + buttonWidth;
m_colorToggle.bottom = m_colorToggle.top + buttonHeight;
gCanvasI.drawRect(canvas, &m_colorToggle, m_paintButton);
const char* colorText = getColorText();
gCanvasI.drawText(canvas, colorText, strlen(colorText), m_colorToggle.left + 5,
m_colorToggle.top - fontMetrics.fTop, m_paintSurface);
// draw the clear canvas button
m_clearSurface.left = W - buttonWidth - 5;
m_clearSurface.top = H - buttonHeight - 5;
m_clearSurface.right = m_clearSurface.left + buttonWidth;
m_clearSurface.bottom = m_clearSurface.top + buttonHeight;
gCanvasI.drawRect(canvas, &m_clearSurface, m_paintButton);
const char* clearText = "Clear";
gCanvasI.drawText(canvas, clearText, strlen(clearText), m_clearSurface.left + 5,
m_clearSurface.top - fontMetrics.fTop, m_paintSurface);
// draw the drawing surface box (5 px from the edge)
m_drawingSurface.left = 5;
m_drawingSurface.top = 5;
m_drawingSurface.right = W - 5;
m_drawingSurface.bottom = m_colorToggle.top - 5;
gCanvasI.drawRect(canvas, &m_drawingSurface, m_paintSurface);
// release the canvas
releaseCanvas(canvas);
}
const char* PaintPlugin::getColorText() {
if (m_activePaintColor == s_blueColor)
return "Blue";
else if (m_activePaintColor == s_greenColor)
return "Green";
else
return "Red";
}
bool PaintPlugin::isFixedSurface() {
return true;
}
void PaintPlugin::surfaceCreated(JNIEnv* env, jobject surface) {
env->GetJavaVM(&m_vm);
m_surface = env->NewGlobalRef(surface);
drawCleanPlugin();
}
void PaintPlugin::surfaceChanged(int format, int width, int height) {
// get the plugin's dimensions according to the DOM
PluginObject *obj = (PluginObject*) inst()->pdata;
const int pW = obj->window->width;
const int pH = obj->window->height;
// compare to the plugin's surface dimensions
if (pW != width || pH != height)
gLogI.log(inst(), kError_ANPLogType,
"----%p Invalid Surface Dimensions (%d,%d):(%d,%d)",
inst(), pW, pH, width, height);
}
void PaintPlugin::surfaceDestroyed() {
JNIEnv* env = NULL;
if (m_surface && m_vm->GetEnv((void**) &env, JNI_VERSION_1_4) == JNI_OK) {
env->DeleteGlobalRef(m_surface);
m_surface = NULL;
}
}
int16 PaintPlugin::handleEvent(const ANPEvent* evt) {
switch (evt->eventType) {
case kTouch_ANPEventType: {
float x = (float) evt->data.touch.x;
float y = (float) evt->data.touch.y;
if (kDown_ANPTouchAction == evt->data.touch.action && m_isTouchCurrentInput) {
ANPRectF* rect = validTouch(evt->data.touch.x, evt->data.touch.y);
if(rect == &m_drawingSurface) {
m_isTouchActive = true;
gPathI.moveTo(m_touchPath, x, y);
paintTouch();
return 1;
}
} else if (kMove_ANPTouchAction == evt->data.touch.action && m_isTouchActive) {
gPathI.lineTo(m_touchPath, x, y);
paintTouch();
return 1;
} else if (kUp_ANPTouchAction == evt->data.touch.action && m_isTouchActive) {
gPathI.lineTo(m_touchPath, x, y);
paintTouch();
m_isTouchActive = false;
gPathI.reset(m_touchPath);
return 1;
} else if (kCancel_ANPTouchAction == evt->data.touch.action) {
m_isTouchActive = false;
gPathI.reset(m_touchPath);
return 1;
}
break;
}
case kMouse_ANPEventType: {
if (m_isTouchActive)
gLogI.log(inst(), kError_ANPLogType, "----%p Received unintended mouse event", inst());
if (kDown_ANPMouseAction == evt->data.mouse.action) {
ANPRectF* rect = validTouch(evt->data.mouse.x, evt->data.mouse.y);
if (rect == &m_drawingSurface)
paintMouse(evt->data.mouse.x, evt->data.mouse.y);
else if (rect == &m_inputToggle)
toggleInputMethod();
else if (rect == &m_colorToggle)
togglePaintColor();
else if (rect == &m_clearSurface)
drawCleanPlugin();
}
return 1;
}
default:
break;
}
return 0; // unknown or unhandled event
}
ANPRectF* PaintPlugin::validTouch(int x, int y) {
//convert to float
float fx = (int) x;
float fy = (int) y;
if (fx > m_drawingSurface.left && fx < m_drawingSurface.right && fy > m_drawingSurface.top && fy < m_drawingSurface.bottom)
return &m_drawingSurface;
else if (fx > m_inputToggle.left && fx < m_inputToggle.right && fy > m_inputToggle.top && fy < m_inputToggle.bottom)
return &m_inputToggle;
else if (fx > m_colorToggle.left && fx < m_colorToggle.right && fy > m_colorToggle.top && fy < m_colorToggle.bottom)
return &m_colorToggle;
else if (fx > m_clearSurface.left && fx < m_clearSurface.right && fy > m_clearSurface.top && fy < m_clearSurface.bottom)
return &m_clearSurface;
else
return NULL;
}
void PaintPlugin::toggleInputMethod() {
m_isTouchCurrentInput = !m_isTouchCurrentInput;
// lock only the input toggle and redraw the canvas
ANPCanvas* lockedCanvas = getCanvas(&m_inputToggle);
drawCleanPlugin(lockedCanvas);
}
void PaintPlugin::togglePaintColor() {
if (m_activePaintColor == s_blueColor)
m_activePaintColor = s_redColor;
else if (m_activePaintColor == s_greenColor)
m_activePaintColor = s_blueColor;
else
m_activePaintColor = s_greenColor;
// lock only the color toggle and redraw the canvas
ANPCanvas* lockedCanvas = getCanvas(&m_colorToggle);
drawCleanPlugin(lockedCanvas);
}
void PaintPlugin::paintMouse(int x, int y) {
//TODO do not paint outside the drawing surface
//create the paint color
ANPPaint* fillPaint = gPaintI.newPaint();
gPaintI.setFlags(fillPaint, gPaintI.getFlags(fillPaint) | kAntiAlias_ANPPaintFlag);
gPaintI.setStyle(fillPaint, kFill_ANPPaintStyle);
gPaintI.setColor(fillPaint, m_activePaintColor);
// handle the simple "mouse" paint (draw a point)
ANPRectF point;
point.left = (float) x-3;
point.top = (float) y-3;
point.right = (float) x+3;
point.bottom = (float) y+3;
// get a canvas that is only locked around the point and draw it
ANPCanvas* canvas = getCanvas(&point);
gCanvasI.drawOval(canvas, &point, fillPaint);
// clean up
releaseCanvas(canvas);
gPaintI.deletePaint(fillPaint);
}
void PaintPlugin::paintTouch() {
//TODO do not paint outside the drawing surface
//create the paint color
ANPPaint* strokePaint = gPaintI.newPaint();
gPaintI.setFlags(strokePaint, gPaintI.getFlags(strokePaint) | kAntiAlias_ANPPaintFlag);
gPaintI.setColor(strokePaint, m_activePaintColor);
gPaintI.setStyle(strokePaint, kStroke_ANPPaintStyle);
gPaintI.setStrokeWidth(strokePaint, 6.0);
gPaintI.setStrokeCap(strokePaint, kRound_ANPPaintCap);
gPaintI.setStrokeJoin(strokePaint, kRound_ANPPaintJoin);
// handle the complex "touch" paint (draw a line)
ANPRectF bounds;
gPathI.getBounds(m_touchPath, &bounds);
// get a canvas that is only locked around the point and draw the path
ANPCanvas* canvas = getCanvas(&bounds);
gCanvasI.drawPath(canvas, m_touchPath, strokePaint);
// clean up
releaseCanvas(canvas);
gPaintI.deletePaint(strokePaint);
}
| 36.151671 | 127 | 0.663728 | mogoweb |
5b015572de1e4d59c0e08d3d36f482ac8d6d8a6e | 2,517 | hpp | C++ | particle_filter/include/ParticleFilterFileOutput.hpp | giordano/stationsimcpp | e8b7a5c5d7b7aa8f80bd983a170e6afc59f548d4 | [
"MIT"
] | null | null | null | particle_filter/include/ParticleFilterFileOutput.hpp | giordano/stationsimcpp | e8b7a5c5d7b7aa8f80bd983a170e6afc59f548d4 | [
"MIT"
] | 1 | 2020-11-05T13:21:52.000Z | 2020-11-05T13:21:52.000Z | particle_filter/include/ParticleFilterFileOutput.hpp | giordano/stationsimcpp | e8b7a5c5d7b7aa8f80bd983a170e6afc59f548d4 | [
"MIT"
] | 1 | 2020-06-18T17:52:06.000Z | 2020-06-18T17:52:06.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2020 Eleftherios Avramidis <ea461@cam.ac.uk>
// Research Computing Services, University of Cambridge, UK
//
// Distributed under The MIT License (MIT)
// See accompanying file LICENSE
//---------------------------------------------------------------------------//
#ifndef PARTICLE_FILTER_PARTICLEFILTERFILEOUTPUT_HPP
#define PARTICLE_FILTER_PARTICLEFILTERFILEOUTPUT_HPP
#include "H5Cpp.h"
#include "ParticleFilter.hpp"
#include <memory>
#include <vector>
namespace particle_filter {
template <class StateType>
class ParticleFilterFileOutput {
public:
ParticleFilterFileOutput() = default;
~ParticleFilterFileOutput() = default;
void write_particle_filter_data_to_hdf_5(std::string file_name,
const std::vector<StateType> &particles_states) {
// Create a file
H5::H5File file(file_name.c_str(), H5F_ACC_TRUNC);
H5::Group particle_states_group(file.createGroup("/particle_filter"));
// write_model_parameters_to_hdf5(file);
write_particles_states_to_hdf_5(particle_states_group, particles_states);
// write_collisions_history_to_hdf_5(history_group);
// write_wiggle_history_to_hdf_5(history_group);
}
void write_particles_states_to_hdf_5(H5::Group &particle_states_group,
const std::vector<StateType> &particles_states) {
H5::Group agents_locations_group(particle_states_group.createGroup("/particle_filter/particles_states"));
int particle_count = 0;
for (const StateType &particles_state : particles_states) {
// Create the data space for the dataset.
hsize_t dims[1];
dims[0] = particles_state.size();
int rank = 1;
H5::DataSpace dataspace(rank, dims);
std::string dataset_name("particle_");
dataset_name.append(std::to_string(particle_count++));
H5::DataSet dataset =
agents_locations_group.createDataSet(dataset_name.c_str(), H5::PredType::NATIVE_FLOAT, dataspace);
dataset.write(particles_state.data(), H5::PredType::NATIVE_FLOAT);
}
}
};
} // namespace particle_filter
#endif // PARTICLE_FILTER_PARTICLEFILTERFILEOUTPUT_HPP
| 40.596774 | 118 | 0.60151 | giordano |
5b03732d4054b2f2c65bbce4f3fb77cdb6d1794d | 3,665 | cpp | C++ | Source/Windows.Test/HresultTest.cpp | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 65 | 2019-05-08T01:53:22.000Z | 2022-03-25T15:05:38.000Z | Source/Windows.Test/HresultTest.cpp | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 12 | 2019-08-13T03:18:30.000Z | 2022-01-03T20:12:24.000Z | Source/Windows.Test/HresultTest.cpp | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 18 | 2019-05-09T23:07:44.000Z | 2021-12-26T14:24:29.000Z | //
// Copyright (C) Microsoft Corporation. All rights reserved.
//
#include <arcana/hresult.h>
#include <arcana/type_traits.h>
#include <future>
#include <CppUnitTest.h>
#include <bitset>
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace UnitTests
{
namespace
{
constexpr unsigned int bits(int bytes)
{
return bytes * 8;
}
}
TEST_CLASS(HresultTest)
{
TEST_METHOD(ConvertHresult)
{
const arcana::hresult failure = arcana::hresult::dxgi_error_device_removed;
const std::error_code code = arcana::error_code_from_hr(failure);
Assert::AreEqual(arcana::underlying_cast(failure), arcana::hr_from_error_code(code));
}
TEST_METHOD(ConvertStandardErrorCode)
{
const auto code = make_error_code(std::errc::argument_out_of_domain);
const int32_t hresult = arcana::hr_from_error_code(code);
Assert::IsTrue(code == arcana::error_code_from_hr(hresult));
}
TEST_METHOD(VerifyCustomHResultFailureBitIsSet)
{
auto cameraError = make_error_code(std::errc::broken_pipe);
auto hresultError = arcana::hr_from_error_code(cameraError);
::std::bitset<bits(sizeof(int32_t))> hresultBitset(hresultError);
Assert::IsTrue(hresultBitset.test(31));
}
TEST_METHOD(VerifyCustomHResultCustomerBitIsSet)
{
auto cameraError = make_error_code(std::errc::broken_pipe);
auto hresultError = arcana::hr_from_error_code(cameraError);
::std::bitset<bits(sizeof(int32_t))> hresultBitset(hresultError);
Assert::IsTrue(hresultBitset.test(29));
}
TEST_METHOD(VerifyCustomHResultCategoryIsDifferent)
{
auto genericError = arcana::hr_from_error_code(make_error_code(std::errc::bad_file_descriptor));
auto futureError = arcana::hr_from_error_code(make_error_code(std::future_errc::no_state));
::std::bitset<bits(sizeof(int32_t))> genericErrorBits(genericError);
::std::bitset<bits(sizeof(int32_t))> futureErrorBits(futureError);
::std::bitset<bits(sizeof(int32_t))> maxErrC = (0xFFFF);
// verify bits 17 through 26 are not identical between two different categories (they should be unique)
auto filteredGenericBits = (genericErrorBits | maxErrC) ^ maxErrC;
auto filteredarcanaBits = (futureErrorBits | maxErrC) ^ maxErrC;
Assert::IsTrue(filteredGenericBits != filteredarcanaBits);
}
TEST_METHOD(VerifyCanGetGenericErrorFromHResult)
{
auto genericError = arcana::hr_from_error_code(make_error_code(std::errc::broken_pipe));
auto category = arcana::get_category_from_hresult(genericError);
Assert::IsFalse(category == nullptr);
Assert::IsTrue(*category == std::generic_category());
}
TEST_METHOD(VerifyStandardHResultDoesNotReturnCategory)
{
auto category = arcana::get_category_from_hresult(E_FAIL);
Assert::IsTrue(category == nullptr);
}
TEST_METHOD(VerifyConvertToFromHResult)
{
auto cameraError = make_error_code(std::errc::broken_pipe);
auto hresultError = arcana::hr_from_error_code(cameraError);
auto newCameraError = arcana::error_code_from_hr(hresultError);
Assert::IsTrue(cameraError.category() == newCameraError.category());
Assert::IsTrue(cameraError.value() == newCameraError.value());
}
};
}
| 36.287129 | 115 | 0.65075 | andrei-datcu |
5b041a9797da2b0aa8d3df1d5c7efbab983a5262 | 977 | hpp | C++ | src/cpu/interrupts/idt.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | src/cpu/interrupts/idt.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | src/cpu/interrupts/idt.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | #pragma once
#include <kstd/types.hpp>
namespace cpu::interrupts {
struct [[gnu::packed]] IDTR {
u16 limit;
u64 base;
};
enum class IDTType {
INTERRUPT = 0b1110,
TRAP = 0b1111
};
struct [[gnu::packed]] IDTEntry {
u16 offset1;
u16 selector;
u16 attributes;
u16 offset2;
u32 offset3;
u32 reserved;
};
struct [[gnu::packed]] InterruptFrame {
u64 r15, r14, r13, r12, r11, r10, r9, r8;
u64 rbp, rdi, rsi, rdx, rcx, rbx, rax;
u64 vec; // vector number, set by the wrapper
u64 err; // might be pushed by the cpu, set to 0 by the wrapper if not
u64 rip, cs, rflags, rsp, ss; // all pushed by the cpu
};
typedef void (*IDTHandler)(InterruptFrame*);
u8 allocate_vector();
void load_idt_entry(u8 index, void (*wrapper)(), IDTType type);
void load_idt_handler(u8 index, IDTHandler handler);
void load_idt();
}
| 24.425 | 78 | 0.579324 | Tunacan427 |
5b069e9f650eaf38aeb32e77882ce8db6e1141bb | 3,174 | cpp | C++ | src/yars/configuration/data/DataOrbitCam.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 4 | 2017-08-05T03:33:21.000Z | 2021-11-08T09:15:42.000Z | src/yars/configuration/data/DataOrbitCam.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | null | null | null | src/yars/configuration/data/DataOrbitCam.cpp | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 1 | 2019-03-24T08:35:25.000Z | 2019-03-24T08:35:25.000Z | #include "DataOrbitCam.h"
#include "DataPIDFactory.h"
#include "yars/util/macros.h"
# define YARS_STRING_ORBIT_CAM_LOOK_AT_X (char*)"lookAtX"
# define YARS_STRING_ORBIT_CAM_LOOK_AT_Y (char*)"lookAtY"
# define YARS_STRING_ORBIT_CAM_LOOK_AT_Z (char*)"lookAtZ"
# define YARS_STRING_ORBIT_CAM_FROM_X (char*)"fromX"
# define YARS_STRING_ORBIT_CAM_FROM_Y (char*)"fromY"
# define YARS_STRING_ORBIT_CAM_FROM_Z (char*)"fromZ"
# define YARS_STRING_ORBIT_CAM_SPEED (char*)"speed"
DataOrbitCam::DataOrbitCam(DataNode *parent)
: DataNode(parent),
_lookAtX(1, 0, 0, 0, 100),
_lookAtY(1, 0, 0, 0, 100),
_lookAtZ(1, 0, 0, 0, 100),
_fromX( 1, 0, 0, 0, 100),
_fromY( 1, 0, 0, 0, 100),
_fromZ( 1, 0, 0, 0, 100)
{
_speed = 0.01;
}
DataOrbitCam::~DataOrbitCam()
{
}
void DataOrbitCam::add(DataParseElement *element)
{
if(element->closing(YARS_STRING_ORBIT_CAM))
{
current = parent;
}
if(element->opening(YARS_STRING_ORBIT_CAM))
{
element->set(YARS_STRING_ORBIT_CAM_SPEED, _speed);
_speed = DEG_TO_RAD(_speed);
}
if(element->opening(YARS_STRING_ORBIT_CAM_LOOK_AT_X))
{
DataPIDFactory::set(_lookAtX, element);
}
if(element->opening(YARS_STRING_ORBIT_CAM_LOOK_AT_Y))
{
DataPIDFactory::set(_lookAtY, element);
}
if(element->opening(YARS_STRING_ORBIT_CAM_LOOK_AT_Z))
{
DataPIDFactory::set(_lookAtZ, element);
}
if(element->opening(YARS_STRING_ORBIT_CAM_FROM_X))
{
DataPIDFactory::set(_fromX, element);
}
if(element->opening(YARS_STRING_ORBIT_CAM_FROM_Y))
{
DataPIDFactory::set(_fromY, element);
}
if(element->opening(YARS_STRING_ORBIT_CAM_FROM_Z))
{
DataPIDFactory::set(_fromZ, element);
}
}
DataOrbitCam* DataOrbitCam::copy()
{
DataOrbitCam *copy = new DataOrbitCam(NULL);
copy->_lookAtX = _lookAtX;
copy->_lookAtY = _lookAtY;
copy->_lookAtZ = _lookAtZ;
copy->_fromX = _fromX;
copy->_fromY = _fromY;
copy->_fromZ = _fromZ;
copy->_speed = _speed;
return copy;
}
void DataOrbitCam::createXsd(XsdSpecification *spec)
{
XsdSequence *orbitCamConfig = new XsdSequence(YARS_STRING_ORBIT_CAM_DEFINITION);
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_LOOK_AT_X, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_LOOK_AT_Y, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_LOOK_AT_Z, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_FROM_X, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_FROM_Y, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(XE(YARS_STRING_ORBIT_CAM_FROM_Z, YARS_STRING_PID_DEFINITION, 0, 1));
orbitCamConfig->add(NA(YARS_STRING_ORBIT_CAM_SPEED, YARS_STRING_XSD_DECIMAL, false));
spec->add(orbitCamConfig);
}
PID DataOrbitCam::lookAtX()
{
return _lookAtX;
}
PID DataOrbitCam::lookAtY()
{
return _lookAtY;
}
PID DataOrbitCam::lookAtZ()
{
return _lookAtZ;
}
PID DataOrbitCam::fromX()
{
return _fromX;
}
PID DataOrbitCam::fromY()
{
return _fromY;
}
PID DataOrbitCam::fromZ()
{
return _fromZ;
}
double DataOrbitCam::speed()
{
return _speed;
}
| 23.167883 | 94 | 0.726843 | kzahedi |
5b0708656d2aa4b593490d5a3d8f7c449aa258b0 | 615 | cpp | C++ | 41.first_missing_positive.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | 41.first_missing_positive.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | 41.first_missing_positive.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution {
public:
int firstMissingPositive(vector<int> &nums) {
bool find_one = false;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 1)
find_one = true;
if (nums[i] <= 0 || nums[i] > nums.size()) {
nums[i] = 1;
}
}
if (!find_one)
return 1;
for (int i = 0; i < nums.size(); i++) {
nums[abs(nums[i]) - 1] = -1 * abs(nums[abs(nums[i]) - 1]);
}
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > 0) {
return i + 1;
}
}
return nums.size() + 1;
}
};
| 18.088235 | 64 | 0.456911 | willyii |
5b09eb4ade558a19104caf77f9d10022b07d0990 | 1,668 | cpp | C++ | 06_breadth-first_search/c++/01_graph_bfs.cpp | filchyboy/grokking_algorithms_work | 16dace97610e2cb0938704e2b8cfd6e92d6b024d | [
"MIT"
] | 13 | 2021-03-11T00:25:22.000Z | 2022-03-19T00:19:23.000Z | book04grokkingAlgo/06_breadth-first_search/c++/01_graph_bfs.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 160 | 2021-04-26T19:04:15.000Z | 2022-03-26T20:18:37.000Z | book04grokkingAlgo/06_breadth-first_search/c++/01_graph_bfs.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 12 | 2021-04-26T19:43:01.000Z | 2022-01-31T08:36:29.000Z | #include <iostream>
#include <map>
#include <list>
#include <queue>
using namespace std;
template <typename T>
class Graph {
map <T , list<T>> adjList ;
public :
Graph()
{}
void addEdge(T u , T v , bool bidir = true)
{
adjList[u].push_back(v);
if(bidir)
adjList[v].push_back(u) ;
}
void printAdjList()
{
for( auto key : adjList)
{
cout<<key.first<<"->" ;
for(auto neighbours : key.second)
cout<<neighbours<<"," ;
cout<<endl;
}
}
void bfs(T src)
{
queue<T> q;
map<T , bool> visited ;
q.push(src) ;
visited[src] = true ;
while(!q.empty())
{
T node = q.front() ;
cout<<node<<" ," ;
q.pop();
//push the neighbours
for(auto neighbours : adjList[node])
{
if(!visited[neighbours])
{
q.push(neighbours) ;
visited[neighbours] = true ;
}
}
}
}
} ;
int main() {
Graph<int> g ;
//adding the edges in the Graph
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(0,4);
g.addEdge(2,4);
g.addEdge(2,3);
g.addEdge(3,5);
g.addEdge(3,4);
cout <<"The Graph is"<<endl;
g.printAdjList();
cout<<endl;
cout<<"The Breadth First Search from Node 0"<<endl;
g.bfs(0) ;
}
| 20.341463 | 55 | 0.398082 | filchyboy |
5b0fe82587c2b51fcf41f9bc58048d190df3d79e | 495 | cpp | C++ | codes/UVA/01001-01999/uva1160.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/UVA/01001-01999/uva1160.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/UVA/01001-01999/uva1160.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5;
int f[maxn+5];
int getfar(int x) {
return x == f[x] ? x : f[x] = getfar(f[x]);
}
int main () {
int x, y;
while (scanf("%d", &x) == 1) {
int ret = 0;
for (int i = 0; i <= maxn; i++)
f[i] = i;
while (x != -1) {
scanf("%d", &y);
x = getfar(x);
y = getfar(y);
if (x == y)
ret++;
else
f[y] = x;
scanf("%d", &x);
}
printf("%d\n", ret);
}
return 0;
}
| 13.75 | 44 | 0.474747 | JeraKrs |
5b13a6af75f9405f72f173d6f00935fb84678ed5 | 4,191 | cc | C++ | pw_rpc/responder.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | pw_rpc/responder.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | pw_rpc/responder.cc | ffzwadd/pigweed | 75e038f0d852b310d135b93061bc769cb8bf90c4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Pigweed 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
//
// https://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 "pw_rpc/internal/responder.h"
#include "pw_assert/check.h"
#include "pw_rpc/internal/method.h"
#include "pw_rpc/internal/packet.h"
#include "pw_rpc/internal/server.h"
namespace pw::rpc::internal {
namespace {
Packet ResponsePacket(const ServerCall& call,
std::span<const std::byte> payload,
Status status) {
return Packet(PacketType::RESPONSE,
call.channel().id(),
call.service().id(),
call.method().id(),
payload,
status);
}
Packet StreamPacket(const ServerCall& call,
std::span<const std::byte> payload) {
return Packet(PacketType::SERVER_STREAM,
call.channel().id(),
call.service().id(),
call.method().id(),
payload);
}
} // namespace
Responder::Responder(ServerCall& call, HasClientStream has_client_stream)
: call_(call),
rpc_state_(kOpen),
has_client_stream_(has_client_stream),
client_stream_state_(has_client_stream ? kClientStreamOpen
: kClientStreamClosed) {
call_.server().RegisterResponder(*this);
}
Responder& Responder::operator=(Responder&& other) {
// If this RPC was running, complete it before moving in the other RPC.
CloseAndSendResponse(OkStatus())
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
// Move the state variables, which may change when the other client closes.
rpc_state_ = other.rpc_state_;
has_client_stream_ = other.has_client_stream_;
client_stream_state_ = other.client_stream_state_;
if (other.open()) {
other.Close();
other.call_.server().RegisterResponder(*this);
}
// Move the rest of the member variables.
call_ = std::move(other.call_);
response_ = std::move(other.response_);
on_error_ = std::move(other.on_error_);
on_next_ = std::move(other.on_next_);
#if PW_RPC_CLIENT_STREAM_END_CALLBACK
on_client_stream_end_ = std::move(other.on_client_stream_end_);
#endif // PW_RPC_CLIENT_STREAM_END_CALLBACK
return *this;
}
uint32_t Responder::method_id() const { return call_.method().id(); }
Status Responder::CloseAndSendResponse(std::span<const std::byte> response,
Status status) {
if (!open()) {
return Status::FailedPrecondition();
}
// Send a packet indicating that the RPC has terminated.
Status packet_status =
call_.channel().Send(ResponsePacket(call_, response, status));
// If the Responder implementer or user forgets to release an acquired buffer
// before finishing, release it here.
if (!response_.empty()) {
ReleasePayloadBuffer()
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
}
Close();
return packet_status;
}
std::span<std::byte> Responder::AcquirePayloadBuffer() {
PW_DCHECK(open());
// Only allow having one active buffer at a time.
if (response_.empty()) {
response_ = call_.channel().AcquireBuffer();
}
return response_.payload(StreamPacket(call_, {}));
}
Status Responder::ReleasePayloadBuffer(std::span<const std::byte> payload) {
PW_DCHECK(open());
return call_.channel().Send(response_, StreamPacket(call_, payload));
}
Status Responder::ReleasePayloadBuffer() {
PW_DCHECK(open());
call_.channel().Release(response_);
return OkStatus();
}
void Responder::Close() {
PW_DCHECK(open());
call_.server().RemoveResponder(*this);
rpc_state_ = kClosed;
client_stream_state_ = kClientStreamClosed;
}
} // namespace pw::rpc::internal
| 29.935714 | 80 | 0.675257 | ffzwadd |
5b14f4a95cd297d9e5951f64d28481a2b9a7f468 | 4,077 | cpp | C++ | APEX_1.4/common/src/ApexAssetAuthoring.cpp | gongyiling/PhysX-3.4 | 99bc1c62880cf626f9926781e76a528b5276c68b | [
"Unlicense"
] | 1,863 | 2018-12-03T13:06:03.000Z | 2022-03-29T07:12:37.000Z | APEX_1.4/common/src/ApexAssetAuthoring.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 71 | 2018-12-03T19:48:39.000Z | 2022-01-11T09:30:52.000Z | APEX_1.4/common/src/ApexAssetAuthoring.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 265 | 2018-12-03T14:30:03.000Z | 2022-03-25T20:57:01.000Z | //
// 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 NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2018 NVIDIA Corporation. All rights reserved.
#include "ApexAssetAuthoring.h"
#include "P4Info.h"
#include "PsString.h"
#include "PhysXSDKVersion.h"
#include "ApexSDKIntl.h"
namespace nvidia
{
namespace apex
{
void ApexAssetAuthoring::setToolString(const char* toolName, const char* toolVersion, uint32_t toolChangelist)
{
#ifdef WITHOUT_APEX_AUTHORING
PX_UNUSED(toolName);
PX_UNUSED(toolVersion);
PX_UNUSED(toolChangelist);
#else
const uint32_t buflen = 256;
char buf[buflen];
nvidia::strlcpy(buf, buflen, toolName);
nvidia::strlcat(buf, buflen, " ");
if (toolVersion != NULL)
{
nvidia::strlcat(buf, buflen, toolVersion);
nvidia::strlcat(buf, buflen, ":");
}
if (toolChangelist == 0)
{
toolChangelist = P4_TOOLS_CHANGELIST;
}
{
char buf2[14];
shdfnd::snprintf(buf2, 14, "CL %d", toolChangelist);
nvidia::strlcat(buf, buflen, buf2);
nvidia::strlcat(buf, buflen, " ");
}
{
#ifdef WIN64
nvidia::strlcat(buf, buflen, "Win64 ");
#elif defined(WIN32)
nvidia::strlcat(buf, buflen, "Win32 ");
#endif
}
{
nvidia::strlcat(buf, buflen, "(Apex ");
nvidia::strlcat(buf, buflen, P4_APEX_VERSION_STRING);
char buf2[20];
shdfnd::snprintf(buf2, 20, ", CL %d, ", P4_CHANGELIST);
nvidia::strlcat(buf, buflen, buf2);
#ifdef _DEBUG
nvidia::strlcat(buf, buflen, "DEBUG ");
#elif defined(PHYSX_PROFILE_SDK)
nvidia::strlcat(buf, buflen, "PROFILE ");
#endif
nvidia::strlcat(buf, buflen, P4_APEX_BRANCH);
nvidia::strlcat(buf, buflen, ") ");
}
{
nvidia::strlcat(buf, buflen, "(PhysX ");
char buf2[10] = { 0 };
#if PX_PHYSICS_VERSION_MAJOR == 0
shdfnd::snprintf(buf2, 10, "No) ");
#elif PX_PHYSICS_VERSION_MAJOR == 3
shdfnd::snprintf(buf2, 10, "%d.%d) ", PX_PHYSICS_VERSION_MAJOR, PX_PHYSICS_VERSION_MINOR);
#endif
nvidia::strlcat(buf, buflen, buf2);
}
nvidia::strlcat(buf, buflen, "Apex Build Time: ");
nvidia::strlcat(buf, buflen, P4_BUILD_TIME);
nvidia::strlcat(buf, buflen, "Distribution author: ");
nvidia::strlcat(buf, buflen, AUTHOR_DISTRO);
nvidia::strlcat(buf, buflen, "The reason for the creation of the distribution: ");
nvidia::strlcat(buf, buflen, REASON_DISTRO);
//uint32_t len = strlen(buf);
//len = len;
//"<toolName> <toolVersion>:<toolCL> <platform> (Apex <apexVersion>, CL <apexCL> <apexConfiguration> <apexBranch>) (PhysX <physxVersion>) <toolBuildDate>"
setToolString(buf);
#endif
}
void ApexAssetAuthoring::setToolString(const char* /*toolString*/)
{
PX_ALWAYS_ASSERT();
APEX_INVALID_OPERATION("Not Implemented.");
}
} // namespace apex
} // namespace nvidia | 29.330935 | 155 | 0.723817 | gongyiling |
5b19f41a81d83e641e3cffd4ca78d0fc1bbf8c99 | 3,359 | cpp | C++ | Algospot/Algospot boardcover dynamicPrg/main2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | 1 | 2019-02-23T01:17:05.000Z | 2019-02-23T01:17:05.000Z | Algospot/Algospot boardcover dynamicPrg/main2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | null | null | null | Algospot/Algospot boardcover dynamicPrg/main2.cpp | PuppyRush/Algorithms | 1bfb7622ffdc2c7d4b9e408b67a81f31395d9513 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include <set>
#include <vector>
#include <array>
#include <cassert>
using namespace std;
typedef struct COORD {
public:
int x;
int y;
COORD(){}
COORD(const int x, const int y)
:x(x),y(y)
{}
friend bool operator<(const COORD &lhs, const COORD& rhs)
{
if(lhs.x == rhs.x)
return lhs.y < rhs.y;
else
return lhs.x < rhs.x;
}
}COORD;
int figureType[4][3][2] =
{
{
{0,0},{1,0},{0,1}
},
{
{0,0},{0,1},{1,1}
},
{
{0,0},{1,0},{1,1}
},
{
{ 0,0 },{ 1,0 },{ 1,-1 }
}
};
int next[4][2] =
{
{0,-1},
{-1,0},
{1,0},
{0,1},
};
bool draw(int **board,set<COORD> unique, const int W, const int H, const int x,const int y, const int figure, bool dr)
{
int l=0;
array<COORD,3> coord;
for (l = 0; l < 3; l++) {
int next_x = x + figureType[figure][l][0];
int next_y = y + figureType[figure][l][1];
if (next_x < 0 || next_x >= W || next_y < 0 || next_y >= H)
break;
if (board[next_y][next_x] == '#')
break;
coord[l].x = next_x;
coord[l].y = next_y;
}
if(l==3)
{
if(dr)
{
for(int l=0 ; l < 3 ; l++)
{
COORD c(coord[l].y, coord[l].x);
board[c.y][c.x] = '#';
unique.erase(std::move(c));
}
}
else
{
for(int l=0 ; l < 3 ; l++)
{
COORD c(coord[l].y, coord[l].x);
board[c.y][c.x] = '.';
unique.insert(std::move(c));
}
}
}
}
vector<array<COORD,3>> getNext(int **board, const int H, const int W,const int x,const int y)
{
vector<array<COORD,3>> coords;
coords.reserve(4);
for(int i=0 ; i < 4 ; i++) {
int l = 0;
array<COORD,3> coord;
for (l = 0; l < 3; l++) {
int next_x = x + figureType[i][l][0];
int next_y = y + figureType[i][l][1];
if (next_x < 0 || next_x >= W || next_y < 0 || next_y >= H)
break;
if (board[next_y][next_x] == '#')
break;
coord[l].x = next_x;
coord[l].y = next_y;
}
if(l==3) {
coords.push_back(coord);
}
}
return coords;
}
int answer=0;
bool find2(int **board,set<COORD> unique, const int H, const int W,const int x,const int y, const int figure)
{
if(!draw(board,unique,W,H,x,y,figure,true))
return false;
for(int i=0 ; i < 4 ; i++)
{
find2(board,unique,H,W,x,y,i+1);
}
draw(board,unique,W,H,x,y,figure,false);
/*if(unique.empty()) {
return true;
}*/
}
int main()
{
int C=0;
scanf("%d", &C);
for(int i=0 ; i < C ; i++)
{
int H=0;
int W=0;
scanf("%d %d",&H, &W);
int **board = new int*[H];
for(int l=0 ; l < H ; l++)
board[l] = new int[W];
set<COORD> coords;
for(int i=0 ; i < H ; i++) {
for (int l = 0; l < W; ) {
char c = 0;
scanf("%c", &c);
if( c == '\n' || c == ' ')
continue;
board[i][l] = c;
if (board[i][l] == '.')
coords.insert(COORD(l,i));
l++;
}
}
for(const auto coord : coords)
{
find2(board,coords, H, W, coord.x, coord.y);
}
}
} | 18.870787 | 118 | 0.435546 | PuppyRush |
5b1ca84deb08818f9c4d3e36db9805a75fbe8ef9 | 1,811 | hh | C++ | src/Utilities/coarsenBinnedValues.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Utilities/coarsenBinnedValues.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Utilities/coarsenBinnedValues.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// coarsenBinnedValues
//
// Given a lattice of Values, return the multi-level result of progressively
// coarsening the distribution a requeted number of levels. The passed
// in vector<vector<Value> > should have the finest values as the last element,
// and be sized the required number of levels you want to coarsen. This method
// simply changes that vector<vector> in place.
//
// Created by JMO, Fri Feb 19 09:38:29 PST 2010
//----------------------------------------------------------------------------//
#ifndef __Spheral_coarsenBinnedValues__
#define __Spheral_coarsenBinnedValues__
#include <vector>
#include "Geometry/Dimension.hh"
namespace Spheral {
//------------------------------------------------------------------------------
// 1-D.
//------------------------------------------------------------------------------
template<typename Value>
void
coarsenBinnedValues(std::vector<std::vector<Value> >& values,
const unsigned nxFine);
//------------------------------------------------------------------------------
// 2-D.
//------------------------------------------------------------------------------
template<typename Value>
void
coarsenBinnedValues(std::vector<std::vector<Value> >& values,
const unsigned nxFine,
const unsigned nyFine);
//------------------------------------------------------------------------------
// 3-D.
//------------------------------------------------------------------------------
template<typename Value>
void
coarsenBinnedValues(std::vector<std::vector<Value> >& values,
const unsigned nxFine,
const unsigned nyFine,
const unsigned nzFine);
}
#endif
| 36.22 | 80 | 0.44561 | jmikeowen |
5b21267a0977d054ae7cc9600c195fb64bb07e81 | 10,854 | cpp | C++ | SnakePredictor/Entity/SnakeEntity.cpp | DanielMcAssey/SnakePredictor | 2e0c24b51df3089e8fa3bb1a354beec5f8ebfcb2 | [
"MIT"
] | null | null | null | SnakePredictor/Entity/SnakeEntity.cpp | DanielMcAssey/SnakePredictor | 2e0c24b51df3089e8fa3bb1a354beec5f8ebfcb2 | [
"MIT"
] | null | null | null | SnakePredictor/Entity/SnakeEntity.cpp | DanielMcAssey/SnakePredictor | 2e0c24b51df3089e8fa3bb1a354beec5f8ebfcb2 | [
"MIT"
] | null | null | null | /*
// This file is part of SnakePredictor
//
// (c) Daniel McAssey <hello@glokon.me>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
*/
#include "stdafx.h"
#include "../stdafx.h"
#include "SnakeEntity.h"
// Determine priority for path node (in the priority queue)
bool operator<(const PathNode & a, const PathNode & b)
{
return a.Priority > b.Priority;
}
SnakeEntity::SnakeEntity(std::map<std::pair<int, int>, LevelSegment>* _level, int _initial_size, int _level_width, int _level_height, std::pair<int, int>* _level_food_location)
{
LevelGrid = _level;
LevelWidth = _level_width;
LevelHeight = _level_height;
SnakeFoodLocation = _level_food_location;
isDead = false;
isFoodCollected = false;
numFoodPoints = 0;
// Create starting snake
int startPosX = LevelWidth / 2;
int startPosY = LevelHeight / 2;
SnakePart* tmpPart = new SnakePart();
tmpPart->Location = std::make_pair(startPosX, startPosY);
tmpPart->LastMovement = SNAKE_MOVE_LEFT;
tmpPart->NewPart = false;
SnakeParts.push_back(tmpPart);
for (int i = 1; i < _initial_size; i++)
{
tmpPart = new SnakePart();
tmpPart->Location = std::make_pair(startPosX + i, startPosY);
tmpPart->LastMovement = SNAKE_MOVE_LEFT;
tmpPart->NewPart = false;
SnakeParts.push_back(tmpPart);
}
SnakeDirections[SNAKE_MOVE_UP] = std::make_pair(0, -1);
SnakeDirections[SNAKE_MOVE_DOWN] = std::make_pair(0, 1);
SnakeDirections[SNAKE_MOVE_LEFT] = std::make_pair(-1, 0);
SnakeDirections[SNAKE_MOVE_RIGHT] = std::make_pair(1, 0);
UpdateBody();
}
SnakeEntity::~SnakeEntity()
{
}
void SnakeEntity::ClearBody()
{
for (std::vector<std::pair<int, int>>::iterator itr = SnakePartsOld.begin(); itr != SnakePartsOld.end(); ++itr)
{
(*LevelGrid)[(*itr)] = LEVEL_SEGMENT_BLANK;
}
SnakePartsOld.clear();
}
void SnakeEntity::UpdateBody()
{
ClearBody(); // Clear the old body and add the new one
for (std::vector<SnakePart*>::iterator itr = SnakeParts.begin(); itr != SnakeParts.end(); ++itr)
{
if (itr == SnakeParts.begin()) // First element should always be a head
{
(*LevelGrid)[(*itr)->Location] = LEVEL_SEGMENT_PLAYER_SNAKE_HEAD;
}
else
{
(*LevelGrid)[(*itr)->Location] = LEVEL_SEGMENT_PLAYER_SNAKE;
}
}
}
void SnakeEntity::Move(SnakeMovement _Direction)
{
for (std::vector<SnakePart*>::iterator itr = SnakeParts.begin(); itr != SnakeParts.end(); ++itr)
{
SnakePartsOld.push_back((*itr)->Location);
}
std::pair<int, int> newPosition = std::make_pair(SnakeDirections[_Direction].first + SnakeParts.front()->Location.first, SnakeDirections[_Direction].second + SnakeParts.front()->Location.second);
if (!Collision(newPosition)) // Make sure we dont collide with anything
{
SnakeParts.front()->Location = newPosition; // Update snake head position
SnakeMovement parentMovement = SnakeParts.front()->LastMovement;
SnakeMovement oldMovement;
std::pair<int, int> lastPosition;
// Update body
for (std::vector<SnakePart*>::iterator itr = SnakeParts.begin(); itr != SnakeParts.end(); ++itr)
{
if (itr == SnakeParts.begin()) // Ignore head
continue;
if ((*itr)->NewPart) // Expand snake to add new part
{
(*itr)->Location = lastPosition;
(*itr)->LastMovement = oldMovement;
(*itr)->NewPart = false;
}
else
{
lastPosition = (*itr)->Location;
newPosition = std::make_pair(SnakeDirections[parentMovement].first + (*itr)->Location.first, SnakeDirections[parentMovement].second + (*itr)->Location.second);
(*itr)->Location = newPosition;
oldMovement = (*itr)->LastMovement;
(*itr)->LastMovement = parentMovement;
parentMovement = oldMovement;
}
}
SnakeParts.front()->LastMovement = _Direction;
}
}
// Kill the snake
void SnakeEntity::Kill()
{
isDead = true;
printf("SNAKE: Snake Died!\n");
}
bool SnakeEntity::CanMove(LevelSegment _SegmentType)
{
switch (_SegmentType)
{
case LEVEL_SEGMENT_BLANK:
case LEVEL_SEGMENT_PLAYER_FOOD:
return true;
default:
case LEVEL_SEGMENT_WALL:
case LEVEL_SEGMENT_PLAYER_SNAKE:
case LEVEL_SEGMENT_PLAYER_SNAKE_HEAD: // Odd case check would never happen, never hurts to add it though
return false;
}
}
bool SnakeEntity::Collision(std::pair<int, int> _Location)
{
LevelSegment segmentCheck = (*LevelGrid)[_Location];
switch (segmentCheck)
{
case LEVEL_SEGMENT_PLAYER_FOOD:
isFoodCollected = true;
break;
case LEVEL_SEGMENT_WALL:
case LEVEL_SEGMENT_PLAYER_SNAKE:
case LEVEL_SEGMENT_PLAYER_SNAKE_HEAD: // Odd case check would never happen, never hurts to add it though
Kill();
break;
}
if (isFoodCollected) // If food is collected increase snake length by 1
{
SnakePart* tmpPart = new SnakePart();
tmpPart->NewPart = true;
SnakeParts.push_back(tmpPart);
}
return !CanMove(segmentCheck);
}
SnakeMovement SnakeEntity::GetOppositeMovement(SnakeMovement _Movement)
{
switch (_Movement)
{
case SNAKE_MOVE_UP:
return SNAKE_MOVE_DOWN;
case SNAKE_MOVE_DOWN:
return SNAKE_MOVE_UP;
case SNAKE_MOVE_LEFT:
return SNAKE_MOVE_RIGHT;
default:
case SNAKE_MOVE_RIGHT:
return SNAKE_MOVE_LEFT;
}
}
// Path Finding Algorithm
// A* Path finding algorithm originally from: http://code.activestate.com/recipes/577457-a-star-shortest-path-algorithm/
// TODO: Fix this method, it attempts to collide with it self causing it to die.
bool SnakeEntity::CalculatePath(std::pair<int, int> _ToGridReference)
{
std::priority_queue<PathNode> possibleOpenNodesQueue[2];
int queueIndex = 0;
PathNode* gridNode;
PathNode* gridChildNode;
int gridX, gridY, xDirection, yDirection;
std::pair<int, int> gridLocation, gridDirection, startPosition;
startPosition = SnakeParts.front()->Location;
// Clear any remaining paths from old calculations
SnakePath.clear();
// Clear nodes
PathClosedNodes.clear();
PathOpenNodes.clear();
gridNode = new PathNode(startPosition, 0, 0);
gridNode->UpdatePriority(_ToGridReference);
possibleOpenNodesQueue[queueIndex].push(*gridNode);
PathOpenNodes[startPosition] = gridNode->Priority; // Mark first point
while (!possibleOpenNodesQueue[queueIndex].empty())
{
gridNode = new PathNode(possibleOpenNodesQueue[queueIndex].top().Position, possibleOpenNodesQueue[queueIndex].top().Depth, possibleOpenNodesQueue[queueIndex].top().Priority);
gridX = gridNode->Position.first;
gridY = gridNode->Position.second;
gridLocation = std::make_pair(gridX, gridY);
possibleOpenNodesQueue[queueIndex].pop();
PathOpenNodes[gridLocation] = 0;
PathClosedNodes[gridLocation] = true;
if (gridLocation == _ToGridReference)
{
while (gridLocation != startPosition)
{
// Fill Snake path
SnakeMovement tmpMovement = PathDirections[gridLocation];
gridX += SnakeDirections[tmpMovement].first;
gridY += SnakeDirections[tmpMovement].second;
gridLocation = std::make_pair(gridX, gridY);
SnakePath.push_back(GetOppositeMovement(tmpMovement));
}
delete gridNode;
// Empty unused nodes
while (!possibleOpenNodesQueue[queueIndex].empty())
{
possibleOpenNodesQueue[queueIndex].pop();
}
printf("SNAKE (FOOD FOUND): X: %i Y: %i\n", gridX, gridY);
return true;
}
for (int i = 0; i < SnakeDirections.size(); i++)
{
xDirection = gridX + SnakeDirections[(SnakeMovement)i].first;
yDirection = gridY + SnakeDirections[(SnakeMovement)i].second;
gridDirection = std::make_pair(xDirection, yDirection);
// Check to see if snake can move there or that the node isnt closed
if (CanMove((*LevelGrid)[gridDirection]) || !PathClosedNodes[gridDirection])
{
gridChildNode = new PathNode(gridDirection, gridNode->Depth, gridNode->Priority);
gridChildNode->NextDepth((SnakeMovement)i);
gridChildNode->UpdatePriority(_ToGridReference);
if (PathOpenNodes.count(gridDirection) == 0)
{
PathOpenNodes[gridDirection] = gridChildNode->Priority;
possibleOpenNodesQueue[queueIndex].push(*gridChildNode);
PathDirections[gridDirection] = GetOppositeMovement((SnakeMovement)i);
}
else if (PathOpenNodes[gridDirection] > gridChildNode->Priority)
{
PathOpenNodes[gridDirection] = gridChildNode->Priority;
PathDirections[gridDirection] = GetOppositeMovement((SnakeMovement)i);
while (possibleOpenNodesQueue[queueIndex].top().Position != gridDirection)
{
possibleOpenNodesQueue[1 - queueIndex].push(possibleOpenNodesQueue[queueIndex].top());
possibleOpenNodesQueue[queueIndex].pop();
}
possibleOpenNodesQueue[queueIndex].pop();
if (possibleOpenNodesQueue[queueIndex].size() > possibleOpenNodesQueue[1 - queueIndex].size())
{
queueIndex = 1 - queueIndex;
}
while (!possibleOpenNodesQueue[queueIndex].empty())
{
possibleOpenNodesQueue[1 - queueIndex].push(possibleOpenNodesQueue[queueIndex].top());
possibleOpenNodesQueue[queueIndex].pop();
}
queueIndex = 1 - queueIndex;
possibleOpenNodesQueue[queueIndex].push(*gridChildNode);
}
else
{
delete gridChildNode;
}
}
}
delete gridNode;
}
return false;
}
void SnakeEntity::MoveOnPath()
{
if (!SnakePath.empty() && !isFoodCollected) // Move only if there is a next path
{
Move(SnakePath.front());
SnakePath.erase(SnakePath.begin());
}
else
{
if (!CalculatePath(std::make_pair(SnakeFoodLocation->first, SnakeFoodLocation->second))) // Calculate route to food
{
// Cant calculate path, so move to any free space, to see if we can create a path.
if (!MoveToFreeSpace())
{
// Cant move to free space, so set to dead
Kill();
}
}
}
}
// Move to any possible free space, this could be improved on.
bool SnakeEntity::MoveToFreeSpace()
{
std::vector<int> movesAvailable;
for (std::map<SnakeMovement, std::pair<int, int>>::iterator itr = SnakeDirections.begin(); itr != SnakeDirections.end(); ++itr)
movesAvailable.push_back((int)itr->first);
while (movesAvailable.size() > 0)
{
int randomIndex = (rand() % (movesAvailable.size()));
SnakeMovement moveDirection = (SnakeMovement)movesAvailable[randomIndex];
movesAvailable.erase(movesAvailable.begin() + randomIndex);
std::pair<int, int> newPosition = std::make_pair(SnakeDirections[moveDirection].first + SnakeParts.front()->Location.first, SnakeDirections[moveDirection].second + SnakeParts.front()->Location.second);
if (CanMove((*LevelGrid)[newPosition]))
{
Move((SnakeMovement)moveDirection);
return true;
}
}
return false;
}
void SnakeEntity::Unload()
{
LevelGrid = nullptr;
SnakeParts.clear();
SnakePath.clear();
isDead = false;
isFoodCollected = false;
}
void SnakeEntity::Update(float _DeltaTime)
{
if (!isDead) // Dont update if dead
{
// Move the snake on the calculated path, or if no path exists calculate one.
MoveOnPath();
// Update snake body to map with new positions
UpdateBody();
}
} | 28.790451 | 203 | 0.718261 | DanielMcAssey |
5b2247bfe72322a1bbce35b4c9d07ef0ca4eb38e | 4,255 | cpp | C++ | Cellular/Cellular/src/Window.cpp | Hukunaa/SandGame | ec33e942d2a377404b09849d09d6997cc13cf879 | [
"MIT"
] | null | null | null | Cellular/Cellular/src/Window.cpp | Hukunaa/SandGame | ec33e942d2a377404b09849d09d6997cc13cf879 | [
"MIT"
] | null | null | null | Cellular/Cellular/src/Window.cpp | Hukunaa/SandGame | ec33e942d2a377404b09849d09d6997cc13cf879 | [
"MIT"
] | null | null | null | #include <Window.h>
#include <iostream>
std::mutex Window::mtx;
Window::Window()
{
}
Window::Window(int x, int y, std::string name)
{
window = new sf::RenderWindow(sf::VideoMode(x, y), name);
collisionCheck = new ArrData[40000];
for (int i = 0; i < 40000; ++i)
collisionCheck[i].part = nullptr;
if (!m_font.loadFromFile("include/Minecraft.ttf"))
std::cout << "CAN'T LOAD FONT FILE!\n";
m_text.setFont(m_font);
m_fps.setFont(m_font);
particles.reserve(50000);
canDraw.store(false);
isDrawing.store(false);
Game::SetWindow(window);
Game::InitPhysicsThread(collisionCheck, particles, this);
particle_buffer1 = sf::VertexArray(sf::Quads);
RenderingThread = std::thread(&Window::Render, std::ref(particles), std::ref(particle_buffer1), 1, std::ref(canDraw), std::ref(isDrawing));
RenderingThread.detach();
/*ArrayUpdater = std::thread(&Window::UpdateArrays, collisionCheck, std::ref(particles));
ArrayUpdater.detach();*/
}
Window::~Window()
{
delete window;
}
void Window::Update()
{
sf::Clock time;
float oldTime = 0;
float newTime = 0;
float DeltaTime = 0;
float tmpTime = 0;
m_text.setCharacterSize(14);
m_fps.setCharacterSize(14);
m_fps.setPosition(sf::Vector2f(0, 15));
while (window->isOpen())
{
oldTime = newTime;
newTime = time.getElapsedTime().asMicroseconds();
CheckEvents();
std::string text = std::to_string(particles.size());
m_text.setString(text);
if (time.getElapsedTime().asMilliseconds() > tmpTime)
{
m_fps.setString(std::to_string(DeltaTime));
tmpTime = time.getElapsedTime().asMilliseconds() + 100;
}
if (particle_buffer1.getVertexCount() > 3 && canDraw.load())
{
isDrawing.store(true);
window->clear();
window->draw(m_text);
window->draw(m_fps);
window->draw(particle_buffer1);
isDrawing.store(false);
}
window->display();
DeltaTime = 1 / ((newTime - oldTime) / 1000000);
}
}
void Window::CheckEvents()
{
sf::Event event;
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed)
window->close();
}
}
void Window::Render(std::vector<Particle*>& allParticles, sf::VertexArray& particle_buffer, int threadNb, std::atomic_bool& canDraw, std::atomic_bool& isDrawing)
{
while (true)
{
if (!isDrawing.load())
{
canDraw.store(false);
particle_buffer.clear();
for (Particle* particle : allParticles)
{
//particle->mtx.lock();
int screenPos = particle->screenGridPos;
Vector2 roundedPos = Vector2::roundVector(particle->m_pos, 4);
//particle->mtx.unlock();
sf::Vector2f partPos(roundedPos.x, roundedPos.y);
particle_buffer.append(sf::Vertex(sf::Vector2f(partPos.x, partPos.y), sf::Color::Magenta));
particle_buffer.append(sf::Vertex(sf::Vector2f(partPos.x + 4, partPos.y), sf::Color::Cyan));
particle_buffer.append(sf::Vertex(sf::Vector2f(partPos.x + 4, partPos.y + 4), sf::Color::Cyan));
particle_buffer.append(sf::Vertex(sf::Vector2f(partPos.x, partPos.y + 4), sf::Color::Magenta));
}
canDraw.store(true);
}
//Clamp de thread refresh rate by 144FPS, avoinding the thread to use all the CPU Power trying to refresh the buffer an insane amount of times per frame
std::this_thread::sleep_for(std::chrono::microseconds(6900));
}
}
void Window::UpdateArrays(ArrData* arr, std::vector<Particle*>& particles)
{
for (int i = 0; i < 40000; ++i)
arr[i].part = nullptr;
for (Particle* particle : particles)
{
Vector2 pos = Vector2::roundVector(particle->m_pos, 4);
int posX = pos.x / 4;
int posY = pos.y / 4;
//arr[posY * 200 + posX].mtx.lock();
arr[posY * 200 + posX].part = particle;
//arr[posY * 200 + posX].mtx.unlock();
//std::cout << "Col pos:" << posX << " / " << posY << "\n";
}
} | 30.177305 | 161 | 0.587544 | Hukunaa |
5b22f4a342fc7c18b9516f246bc8caedd52438af | 636 | cpp | C++ | src/card/base/command/SetEidPinCommand.cpp | Governikus/AusweisApp2-Omapi | 0d563e61cb385492cef96c2542d50a467e003259 | [
"Apache-2.0"
] | 1 | 2019-06-06T11:58:51.000Z | 2019-06-06T11:58:51.000Z | src/card/base/command/SetEidPinCommand.cpp | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 1 | 2022-01-28T11:08:59.000Z | 2022-01-28T12:05:33.000Z | src/card/base/command/SetEidPinCommand.cpp | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 3 | 2019-06-06T11:58:14.000Z | 2021-11-15T23:32:04.000Z | /*!
* \copyright Copyright (c) 2015-2019 Governikus GmbH & Co. KG, Germany
*/
#include "SetEidPinCommand.h"
using namespace governikus;
SetEidPinCommand::SetEidPinCommand(QSharedPointer<CardConnectionWorker> pCardConnectionWorker,
const QString& pNewPin, quint8 pTimeoutSeconds)
: BaseCardCommand(pCardConnectionWorker)
, mNewPin(pNewPin)
, mTimeoutSeconds(pTimeoutSeconds)
, mResponseApdu()
{
}
void SetEidPinCommand::internalExecute()
{
mReturnCode = mCardConnectionWorker->setEidPin(mNewPin, mTimeoutSeconds, mResponseApdu);
}
const ResponseApdu& SetEidPinCommand::getResponseApdu() const
{
return mResponseApdu;
}
| 21.2 | 94 | 0.790881 | Governikus |
5b24150a2c107975ad4e4cd2b461958ba619c8ae | 15,843 | cc | C++ | content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
class BrowserSideSender
: blink::mojom::ServiceWorkerInstalledScriptsManagerHost {
public:
BrowserSideSender() : binding_(this) {}
~BrowserSideSender() override = default;
blink::mojom::ServiceWorkerInstalledScriptsInfoPtr CreateAndBind(
const std::vector<GURL>& installed_urls) {
EXPECT_FALSE(manager_.is_bound());
EXPECT_FALSE(body_handle_.is_valid());
EXPECT_FALSE(meta_data_handle_.is_valid());
auto scripts_info = blink::mojom::ServiceWorkerInstalledScriptsInfo::New();
scripts_info->installed_urls = installed_urls;
scripts_info->manager_request = mojo::MakeRequest(&manager_);
binding_.Bind(mojo::MakeRequest(&scripts_info->manager_host_ptr));
return scripts_info;
}
void TransferInstalledScript(const GURL& script_url,
int64_t body_size,
int64_t meta_data_size) {
EXPECT_FALSE(body_handle_.is_valid());
EXPECT_FALSE(meta_data_handle_.is_valid());
auto script_info = blink::mojom::ServiceWorkerScriptInfo::New();
script_info->script_url = script_url;
EXPECT_EQ(MOJO_RESULT_OK,
mojo::CreateDataPipe(nullptr, &body_handle_, &script_info->body));
EXPECT_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, &meta_data_handle_,
&script_info->meta_data));
script_info->body_size = body_size;
script_info->meta_data_size = meta_data_size;
manager_->TransferInstalledScript(std::move(script_info));
}
void PushBody(const std::string& data) {
PushDataPipe(data, body_handle_.get());
}
void PushMetaData(const std::string& data) {
PushDataPipe(data, meta_data_handle_.get());
}
void FinishTransferBody() { body_handle_.reset(); }
void FinishTransferMetaData() { meta_data_handle_.reset(); }
void ResetManager() { manager_.reset(); }
void WaitForRequestInstalledScript(const GURL& script_url) {
waiting_requested_url_ = script_url;
base::RunLoop loop;
requested_script_closure_ = loop.QuitClosure();
loop.Run();
}
private:
void RequestInstalledScript(const GURL& script_url) override {
EXPECT_EQ(waiting_requested_url_, script_url);
ASSERT_TRUE(requested_script_closure_);
std::move(requested_script_closure_).Run();
}
void PushDataPipe(const std::string& data,
const mojo::DataPipeProducerHandle& handle) {
// Send |data| with null terminator.
ASSERT_TRUE(handle.is_valid());
uint32_t written_bytes = data.size() + 1;
MojoResult rv = handle.WriteData(data.c_str(), &written_bytes,
MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, rv);
ASSERT_EQ(data.size() + 1, written_bytes);
}
base::OnceClosure requested_script_closure_;
GURL waiting_requested_url_;
blink::mojom::ServiceWorkerInstalledScriptsManagerPtr manager_;
mojo::Binding<blink::mojom::ServiceWorkerInstalledScriptsManagerHost>
binding_;
mojo::ScopedDataPipeProducerHandle body_handle_;
mojo::ScopedDataPipeProducerHandle meta_data_handle_;
DISALLOW_COPY_AND_ASSIGN(BrowserSideSender);
};
class WebServiceWorkerInstalledScriptsManagerImplTest : public testing::Test {
public:
WebServiceWorkerInstalledScriptsManagerImplTest()
: io_thread_("io thread"),
worker_thread_("worker thread"),
worker_waiter_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED) {}
protected:
using RawScriptData =
blink::WebServiceWorkerInstalledScriptsManager::RawScriptData;
void SetUp() override {
ASSERT_TRUE(io_thread_.Start());
ASSERT_TRUE(worker_thread_.Start());
io_task_runner_ = io_thread_.task_runner();
worker_task_runner_ = worker_thread_.task_runner();
}
void TearDown() override {
io_thread_.Stop();
worker_thread_.Stop();
}
void CreateInstalledScriptsManager(
blink::mojom::ServiceWorkerInstalledScriptsInfoPtr
installed_scripts_info) {
installed_scripts_manager_ =
WebServiceWorkerInstalledScriptsManagerImpl::Create(
std::move(installed_scripts_info), io_task_runner_);
}
base::WaitableEvent* IsScriptInstalledOnWorkerThread(const GURL& script_url,
bool* out_installed) {
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
[](blink::WebServiceWorkerInstalledScriptsManager*
installed_scripts_manager,
const blink::WebURL& script_url, bool* out_installed,
base::WaitableEvent* waiter) {
*out_installed =
installed_scripts_manager->IsScriptInstalled(script_url);
waiter->Signal();
},
installed_scripts_manager_.get(), script_url, out_installed,
&worker_waiter_));
return &worker_waiter_;
}
base::WaitableEvent* GetRawScriptDataOnWorkerThread(
const GURL& script_url,
std::unique_ptr<RawScriptData>* out_data) {
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
[](blink::WebServiceWorkerInstalledScriptsManager*
installed_scripts_manager,
const blink::WebURL& script_url,
std::unique_ptr<RawScriptData>* out_data,
base::WaitableEvent* waiter) {
*out_data =
installed_scripts_manager->GetRawScriptData(script_url);
waiter->Signal();
},
installed_scripts_manager_.get(), script_url, out_data,
&worker_waiter_));
return &worker_waiter_;
}
private:
// Provides SingleThreadTaskRunner for this test.
const base::MessageLoop message_loop_;
base::Thread io_thread_;
base::Thread worker_thread_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> worker_task_runner_;
base::WaitableEvent worker_waiter_;
std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManager>
installed_scripts_manager_;
DISALLOW_COPY_AND_ASSIGN(WebServiceWorkerInstalledScriptsManagerImplTest);
};
TEST_F(WebServiceWorkerInstalledScriptsManagerImplTest, GetRawScriptData) {
const GURL kScriptUrl = GURL("https://example.com/installed1.js");
const GURL kUnknownScriptUrl = GURL("https://example.com/not_installed.js");
BrowserSideSender sender;
CreateInstalledScriptsManager(sender.CreateAndBind({kScriptUrl}));
{
bool result = false;
IsScriptInstalledOnWorkerThread(kScriptUrl, &result)->Wait();
// IsScriptInstalled returns correct answer even before script transfer
// hasn't been started yet.
EXPECT_TRUE(result);
}
{
bool result = true;
IsScriptInstalledOnWorkerThread(kUnknownScriptUrl, &result)->Wait();
// IsScriptInstalled returns correct answer even before script transfer
// hasn't been started yet.
EXPECT_FALSE(result);
}
{
std::unique_ptr<RawScriptData> script_data;
const std::string kExpectedBody = "This is a script body.";
const std::string kExpectedMetaData = "This is a meta data.";
base::WaitableEvent* get_raw_script_data_waiter =
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data);
// Start transferring the script. +1 for null terminator.
sender.TransferInstalledScript(kScriptUrl, kExpectedBody.size() + 1,
kExpectedMetaData.size() + 1);
sender.PushBody(kExpectedBody);
sender.PushMetaData(kExpectedMetaData);
// GetRawScriptData should be blocked until body and meta data transfer are
// finished.
EXPECT_FALSE(get_raw_script_data_waiter->IsSignaled());
sender.FinishTransferBody();
sender.FinishTransferMetaData();
// Wait for the script's arrival.
get_raw_script_data_waiter->Wait();
ASSERT_TRUE(script_data);
EXPECT_TRUE(script_data->IsValid());
ASSERT_EQ(1u, script_data->ScriptTextChunks().size());
ASSERT_EQ(kExpectedBody.size() + 1,
script_data->ScriptTextChunks()[0].size());
EXPECT_STREQ(kExpectedBody.data(),
script_data->ScriptTextChunks()[0].Data());
ASSERT_EQ(1u, script_data->MetaDataChunks().size());
ASSERT_EQ(kExpectedMetaData.size() + 1,
script_data->MetaDataChunks()[0].size());
EXPECT_STREQ(kExpectedMetaData.data(),
script_data->MetaDataChunks()[0].Data());
}
{
std::unique_ptr<RawScriptData> script_data;
const std::string kExpectedBody = "This is another script body.";
const std::string kExpectedMetaData = "This is another meta data.";
// Request the same script again.
base::WaitableEvent* get_raw_script_data_waiter =
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data);
// It should call a Mojo IPC "RequestInstalledScript()" to the browser.
sender.WaitForRequestInstalledScript(kScriptUrl);
// Start transferring the script. +1 for null terminator.
sender.TransferInstalledScript(kScriptUrl, kExpectedBody.size() + 1,
kExpectedMetaData.size() + 1);
sender.PushBody(kExpectedBody);
sender.PushMetaData(kExpectedMetaData);
// GetRawScriptData should be blocked until body and meta data transfer are
// finished.
EXPECT_FALSE(get_raw_script_data_waiter->IsSignaled());
sender.FinishTransferBody();
sender.FinishTransferMetaData();
// Wait for the script's arrival.
get_raw_script_data_waiter->Wait();
ASSERT_TRUE(script_data);
EXPECT_TRUE(script_data->IsValid());
ASSERT_EQ(1u, script_data->ScriptTextChunks().size());
ASSERT_EQ(kExpectedBody.size() + 1,
script_data->ScriptTextChunks()[0].size());
EXPECT_STREQ(kExpectedBody.data(),
script_data->ScriptTextChunks()[0].Data());
ASSERT_EQ(1u, script_data->MetaDataChunks().size());
ASSERT_EQ(kExpectedMetaData.size() + 1,
script_data->MetaDataChunks()[0].size());
EXPECT_STREQ(kExpectedMetaData.data(),
script_data->MetaDataChunks()[0].Data());
}
}
TEST_F(WebServiceWorkerInstalledScriptsManagerImplTest,
EarlyDisconnectionBody) {
const GURL kScriptUrl = GURL("https://example.com/installed1.js");
const GURL kUnknownScriptUrl = GURL("https://example.com/not_installed.js");
BrowserSideSender sender;
CreateInstalledScriptsManager(sender.CreateAndBind({kScriptUrl}));
{
std::unique_ptr<RawScriptData> script_data;
const std::string kExpectedBody = "This is a script body.";
const std::string kExpectedMetaData = "This is a meta data.";
base::WaitableEvent* get_raw_script_data_waiter =
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data);
// Start transferring the script.
// Body is expected to be 100 bytes larger than kExpectedBody, but sender
// only sends kExpectedBody and a null byte (kExpectedBody.size() + 1 bytes
// in total).
sender.TransferInstalledScript(kScriptUrl, kExpectedBody.size() + 100,
kExpectedMetaData.size() + 1);
sender.PushBody(kExpectedBody);
sender.PushMetaData(kExpectedMetaData);
// GetRawScriptData should be blocked until body and meta data transfer are
// finished.
EXPECT_FALSE(get_raw_script_data_waiter->IsSignaled());
sender.FinishTransferBody();
sender.FinishTransferMetaData();
// Wait for the script's arrival.
get_raw_script_data_waiter->Wait();
// script_data->IsValid() should return false since the data pipe for body
// gets disconnected during sending.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
{
std::unique_ptr<RawScriptData> script_data;
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data)->Wait();
// |script_data| should be invalid since the data wasn't received on the
// renderer process.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
}
TEST_F(WebServiceWorkerInstalledScriptsManagerImplTest,
EarlyDisconnectionMetaData) {
const GURL kScriptUrl = GURL("https://example.com/installed1.js");
const GURL kUnknownScriptUrl = GURL("https://example.com/not_installed.js");
BrowserSideSender sender;
CreateInstalledScriptsManager(sender.CreateAndBind({kScriptUrl}));
{
std::unique_ptr<RawScriptData> script_data;
const std::string kExpectedBody = "This is a script body.";
const std::string kExpectedMetaData = "This is a meta data.";
base::WaitableEvent* get_raw_script_data_waiter =
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data);
// Start transferring the script.
// Meta data is expected to be 100 bytes larger than kExpectedMetaData, but
// sender only sends kExpectedMetaData and a null byte
// (kExpectedMetaData.size() + 1 bytes in total).
sender.TransferInstalledScript(kScriptUrl, kExpectedBody.size() + 1,
kExpectedMetaData.size() + 100);
sender.PushBody(kExpectedBody);
sender.PushMetaData(kExpectedMetaData);
// GetRawScriptData should be blocked until body and meta data transfer are
// finished.
EXPECT_FALSE(get_raw_script_data_waiter->IsSignaled());
sender.FinishTransferBody();
sender.FinishTransferMetaData();
// Wait for the script's arrival.
get_raw_script_data_waiter->Wait();
// script_data->IsValid() should return false since the data pipe for meta
// data gets disconnected during sending.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
{
std::unique_ptr<RawScriptData> script_data;
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data)->Wait();
// |script_data| should be invalid since the data wasn't received on the
// renderer process.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
}
TEST_F(WebServiceWorkerInstalledScriptsManagerImplTest,
EarlyDisconnectionManager) {
const GURL kScriptUrl = GURL("https://example.com/installed1.js");
const GURL kUnknownScriptUrl = GURL("https://example.com/not_installed.js");
BrowserSideSender sender;
CreateInstalledScriptsManager(sender.CreateAndBind({kScriptUrl}));
{
std::unique_ptr<RawScriptData> script_data;
base::WaitableEvent* get_raw_script_data_waiter =
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data);
// Reset the Mojo connection before sending the script.
EXPECT_FALSE(get_raw_script_data_waiter->IsSignaled());
sender.ResetManager();
// Wait for the script's arrival.
get_raw_script_data_waiter->Wait();
// |script_data| should be nullptr since no data will arrive.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
{
std::unique_ptr<RawScriptData> script_data;
// This should not be blocked because data will not arrive anymore.
GetRawScriptDataOnWorkerThread(kScriptUrl, &script_data)->Wait();
// |script_data| should be invalid since the data wasn't received on the
// renderer process.
ASSERT_TRUE(script_data);
EXPECT_FALSE(script_data->IsValid());
}
}
} // namespace content
| 37.901914 | 94 | 0.708452 | zipated |
5b350088139791ab79c3469873954b19e485c0d7 | 1,482 | hpp | C++ | pybind/handler.hpp | mnaza/Pangolin | 2ed3f08f9ccb82255d23c6db1dce426166ceb3bf | [
"MIT"
] | 1 | 2018-01-14T08:44:02.000Z | 2018-01-14T08:44:02.000Z | pybind/handler.hpp | mnaza/Pangolin | 2ed3f08f9ccb82255d23c6db1dce426166ceb3bf | [
"MIT"
] | null | null | null | pybind/handler.hpp | mnaza/Pangolin | 2ed3f08f9ccb82255d23c6db1dce426166ceb3bf | [
"MIT"
] | null | null | null | //
// Copyright (c) Andrey Mnatsakanov
//
#ifndef PY_PANGOLIN_HANDLER_HPP
#define PY_PANGOLIN_HANDLER_HPP
#include <pybind11/pybind11.h>
#include <pangolin/handler/handler.h>
#include <pangolin/display/view.h>
namespace py_pangolin {
class PyHandler : public pangolin::Handler {
public:
using pangolin::Handler::Handler;
void Keyboard(pangolin::View& v, unsigned char key, int x, int y, bool pressed) override {
PYBIND11_OVERLOAD(void, pangolin::Handler, Keyboard, v, key, x, y, pressed);
}
void Mouse(pangolin::View& v, pangolin::MouseButton button, int x, int y, bool pressed, int button_state) override {
PYBIND11_OVERLOAD(void, pangolin::Handler, Mouse, v, button, x, y, pressed, button_state);
}
void MouseMotion(pangolin::View& v, int x, int y, int button_state) override {
PYBIND11_OVERLOAD(void, pangolin::Handler, MouseMotion, v, x, y, button_state);
}
void PassiveMouseMotion(pangolin::View& v, int x, int y, int button_state) override {
PYBIND11_OVERLOAD(void, pangolin::Handler, PassiveMouseMotion, v, x, y, button_state);
}
void Special(pangolin::View& v, pangolin::InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state) override{
PYBIND11_OVERLOAD(void, pangolin::Handler, Special, v, inType, x, y, p1, p2, p3, p4, button_state);
}
};
void bind_handler(pybind11::module &m);
} // py_pangolin
#endif //PY_PANGOLIN_HANDLER_HPP
| 35.285714 | 152 | 0.706478 | mnaza |
5b364408a2f9976b8c221d2c8ce279c22c537ca5 | 36,000 | cc | C++ | chrome/browser/ash/login/lock/screen_locker.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ash/login/lock/screen_locker.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ash/login/lock/screen_locker.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2014 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 "chrome/browser/ash/login/lock/screen_locker.h"
#include <algorithm>
#include "ash/components/audio/sounds.h"
#include "ash/public/cpp/ash_switches.h"
#include "ash/public/cpp/login_screen.h"
#include "ash/public/cpp/login_screen_model.h"
#include "ash/public/cpp/login_types.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/current_thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/ash/accessibility/accessibility_manager.h"
#include "chrome/browser/ash/authpolicy/authpolicy_helper.h"
#include "chrome/browser/ash/certificate_provider/certificate_provider_service.h"
#include "chrome/browser/ash/certificate_provider/certificate_provider_service_factory.h"
#include "chrome/browser/ash/certificate_provider/pin_dialog_manager.h"
#include "chrome/browser/ash/login/easy_unlock/easy_unlock_service.h"
#include "chrome/browser/ash/login/helper.h"
#include "chrome/browser/ash/login/lock/views_screen_locker.h"
#include "chrome/browser/ash/login/login_auth_recorder.h"
#include "chrome/browser/ash/login/quick_unlock/fingerprint_storage.h"
#include "chrome/browser/ash/login/quick_unlock/pin_backend.h"
#include "chrome/browser/ash/login/quick_unlock/pin_storage_prefs.h"
#include "chrome/browser/ash/login/quick_unlock/quick_unlock_factory.h"
#include "chrome/browser/ash/login/quick_unlock/quick_unlock_storage.h"
#include "chrome/browser/ash/login/session/user_session_manager.h"
#include "chrome/browser/ash/login/ui/user_adding_screen.h"
#include "chrome/browser/ash/login/users/chrome_user_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/login_screen_client.h"
#include "chrome/browser/ui/ash/session_controller_client_impl.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/dbus/biod/constants.pb.h"
#include "chromeos/dbus/session_manager/session_manager_client.h"
#include "chromeos/login/auth/authenticator.h"
#include "chromeos/login/auth/extended_authenticator.h"
#include "chromeos/login/session/session_termination_manager.h"
#include "components/password_manager/core/browser/hash_password_manager.h"
#include "components/session_manager/core/session_manager.h"
#include "components/session_manager/core/session_manager_observer.h"
#include "components/user_manager/user_manager.h"
#include "components/user_manager/user_type.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "services/audio/public/cpp/sounds/sounds_manager.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
using base::UserMetricsAction;
namespace chromeos {
namespace {
// Returns true if fingerprint authentication is available for `user`.
bool IsFingerprintAvailableForUser(const user_manager::User* user) {
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForUser(user);
return quick_unlock_storage &&
quick_unlock_storage->IsFingerprintAuthenticationAvailable();
}
// Observer to start ScreenLocker when locking the screen is requested.
class ScreenLockObserver : public SessionManagerClient::StubDelegate,
public UserAddingScreen::Observer,
public session_manager::SessionManagerObserver {
public:
ScreenLockObserver() : session_started_(false) {
session_manager::SessionManager::Get()->AddObserver(this);
SessionManagerClient::Get()->SetStubDelegate(this);
}
~ScreenLockObserver() override {
session_manager::SessionManager::Get()->RemoveObserver(this);
if (SessionManagerClient::Get())
SessionManagerClient::Get()->SetStubDelegate(nullptr);
}
bool session_started() const { return session_started_; }
// SessionManagerClient::StubDelegate overrides:
void LockScreenForStub() override {
ScreenLocker::HandleShowLockScreenRequest();
}
// session_manager::SessionManagerObserver:
void OnSessionStateChanged() override {
// Only set MarkStrongAuth for the first time session becomes active, which
// is when user first sign-in.
// For unlocking case which state changes from active->lock->active, it
// should be handled in OnPasswordAuthSuccess.
if (session_started_ ||
session_manager::SessionManager::Get()->session_state() !=
session_manager::SessionState::ACTIVE) {
return;
}
session_started_ = true;
// The user session has just started, so the user has logged in. Mark a
// strong authentication to allow them to use PIN to unlock the device.
user_manager::User* user =
user_manager::UserManager::Get()->GetActiveUser();
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForUser(user);
if (quick_unlock_storage)
quick_unlock_storage->MarkStrongAuth();
}
// UserAddingScreen::Observer overrides:
void OnUserAddingFinished() override {
UserAddingScreen::Get()->RemoveObserver(this);
ScreenLocker::HandleShowLockScreenRequest();
}
private:
bool session_started_;
DISALLOW_COPY_AND_ASSIGN(ScreenLockObserver);
};
ScreenLockObserver* g_screen_lock_observer = nullptr;
CertificateProviderService* GetLoginScreenCertProviderService() {
DCHECK(ProfileHelper::IsSigninProfileInitialized());
return CertificateProviderServiceFactory::GetForBrowserContext(
ProfileHelper::GetSigninProfile());
}
} // namespace
// static
ScreenLocker* ScreenLocker::screen_locker_ = nullptr;
//////////////////////////////////////////////////////////////////////////////
// ScreenLocker::Delegate, public:
ScreenLocker::Delegate::Delegate() = default;
ScreenLocker::Delegate::~Delegate() = default;
//////////////////////////////////////////////////////////////////////////////
// ScreenLocker, public:
ScreenLocker::ScreenLocker(const user_manager::UserList& users)
: users_(users) {
DCHECK(!screen_locker_);
screen_locker_ = this;
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
audio::SoundsManager* manager = audio::SoundsManager::Get();
manager->Initialize(static_cast<int>(Sound::kLock),
bundle.GetRawDataResource(IDR_SOUND_LOCK_WAV));
manager->Initialize(static_cast<int>(Sound::kUnlock),
bundle.GetRawDataResource(IDR_SOUND_UNLOCK_WAV));
content::GetDeviceService().BindFingerprint(
fp_service_.BindNewPipeAndPassReceiver());
fp_service_->AddFingerprintObserver(
fingerprint_observer_receiver_.BindNewPipeAndPassRemote());
GetLoginScreenCertProviderService()->pin_dialog_manager()->AddPinDialogHost(
&security_token_pin_dialog_host_ash_impl_);
user_manager::UserManager::Get()->AddSessionStateObserver(this);
}
void ScreenLocker::Init() {
input_method::InputMethodManager* imm =
input_method::InputMethodManager::Get();
saved_ime_state_ = imm->GetActiveIMEState();
imm->SetState(saved_ime_state_->Clone());
input_method::InputMethodManager::Get()->GetActiveIMEState()->SetUIStyle(
input_method::InputMethodManager::UIStyle::kLock);
input_method::InputMethodManager::Get()
->GetActiveIMEState()
->EnableLockScreenLayouts();
authenticator_ = UserSessionManager::GetInstance()->CreateAuthenticator(this);
extended_authenticator_ = ExtendedAuthenticator::Create(this);
// Create delegate that calls into the views-based lock screen via mojo.
views_screen_locker_ = std::make_unique<ViewsScreenLocker>(this);
delegate_ = views_screen_locker_.get();
// Create and display lock screen.
CHECK(LoginScreenClient::HasInstance());
ash::LoginScreen::Get()->ShowLockScreen();
views_screen_locker_->Init();
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
content::NotificationService::AllSources(),
content::NotificationService::NoDetails());
// Start locking on ash side.
SessionControllerClientImpl::Get()->StartLock(base::BindOnce(
&ScreenLocker::OnStartLockCallback, weak_factory_.GetWeakPtr()));
}
void ScreenLocker::OnAuthFailure(const AuthFailure& error) {
base::RecordAction(UserMetricsAction("ScreenLocker_OnLoginFailure"));
if (authentication_start_time_.is_null()) {
LOG(ERROR) << "Start time is not set at authentication failure";
} else {
base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
VLOG(1) << "Authentication failure: " << delta.InSecondsF() << " second(s)";
UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationFailureTime", delta);
}
UMA_HISTOGRAM_ENUMERATION("ScreenLocker.AuthenticationFailure",
unlock_attempt_type_, UnlockType::AUTH_COUNT);
EnableInput();
// Don't enable signout button here as we're showing
// MessageBubble.
delegate_->ShowErrorMessage(incorrect_passwords_count_++
? IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME
: IDS_LOGIN_ERROR_AUTHENTICATING,
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
if (auth_status_consumer_)
auth_status_consumer_->OnAuthFailure(error);
if (pending_auth_state_) {
GetLoginScreenCertProviderService()
->AbortSignatureRequestsForAuthenticatingUser(
pending_auth_state_->account_id);
std::move(pending_auth_state_->callback).Run(false);
pending_auth_state_.reset();
}
}
void ScreenLocker::OnAuthSuccess(const UserContext& user_context) {
CHECK(!IsAuthTemporarilyDisabledForUser(user_context.GetAccountId()))
<< "Authentication is disabled for this user.";
incorrect_passwords_count_ = 0;
DCHECK(!unlock_started_);
unlock_started_ = true;
if (authentication_start_time_.is_null()) {
if (user_context.GetAccountId().is_valid())
LOG(ERROR) << "Start time is not set at authentication success";
} else {
base::TimeDelta delta = base::Time::Now() - authentication_start_time_;
VLOG(1) << "Authentication success: " << delta.InSecondsF() << " second(s)";
UMA_HISTOGRAM_TIMES("ScreenLocker.AuthenticationSuccessTime", delta);
}
UMA_HISTOGRAM_ENUMERATION("ScreenLocker.AuthenticationSuccess",
unlock_attempt_type_, UnlockType::AUTH_COUNT);
const user_manager::User* user =
user_manager::UserManager::Get()->FindUser(user_context.GetAccountId());
if (user) {
if (!user->is_active()) {
saved_ime_state_ = nullptr;
user_manager::UserManager::Get()->SwitchActiveUser(
user_context.GetAccountId());
}
// Reset the number of PIN attempts available to the user. We always do this
// because:
// 1. If the user signed in with a PIN, that means they should be able to
// continue signing in with a PIN.
// 2. If the user signed in with cryptohome keys, then the PIN timeout is
// going to be reset as well, so it is safe to reset the unlock attempt
// count.
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForUser(user);
if (quick_unlock_storage) {
quick_unlock_storage->pin_storage_prefs()->ResetUnlockAttemptCount();
quick_unlock_storage->fingerprint_storage()->ResetUnlockAttemptCount();
}
UserSessionManager::GetInstance()->UpdateEasyUnlockKeys(user_context);
} else {
NOTREACHED() << "Logged in user not found.";
}
if (pending_auth_state_) {
std::move(pending_auth_state_->callback).Run(true);
pending_auth_state_.reset();
}
if (auth_status_consumer_)
auth_status_consumer_->OnAuthSuccess(user_context);
weak_factory_.InvalidateWeakPtrs();
VLOG(1) << "Hiding the lock screen.";
chromeos::ScreenLocker::Hide();
}
void ScreenLocker::OnPasswordAuthSuccess(const UserContext& user_context) {
// The user has signed in using their password, so reset the PIN timeout.
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForAccountId(
user_context.GetAccountId());
if (quick_unlock_storage)
quick_unlock_storage->MarkStrongAuth();
SaveSyncPasswordHash(user_context);
}
void ScreenLocker::ReenableAuthForUser(const AccountId& account_id) {
if (!IsAuthTemporarilyDisabledForUser(account_id))
return;
const user_manager::User* user = FindUnlockUser(account_id);
CHECK(user) << "Invalid user - cannot enable authentication.";
users_with_temporarily_disabled_auth_.erase(account_id);
ash::LoginScreen::Get()->GetModel()->EnableAuthForUser(account_id);
}
void ScreenLocker::TemporarilyDisableAuthForUser(
const AccountId& account_id,
const ash::AuthDisabledData& auth_disabled_data) {
if (IsAuthTemporarilyDisabledForUser(account_id))
return;
const user_manager::User* user = FindUnlockUser(account_id);
CHECK(user) << "Invalid user - cannot disable authentication.";
users_with_temporarily_disabled_auth_.insert(account_id);
ash::LoginScreen::Get()->GetModel()->DisableAuthForUser(account_id,
auth_disabled_data);
}
void ScreenLocker::Authenticate(const UserContext& user_context,
AuthenticateCallback callback) {
LOG_ASSERT(IsUserLoggedIn(user_context.GetAccountId()))
<< "Invalid user trying to unlock.";
// Do not attempt authentication if it is disabled for the user.
if (IsAuthTemporarilyDisabledForUser(user_context.GetAccountId())) {
VLOG(1) << "Authentication disabled for user.";
if (auth_status_consumer_) {
auth_status_consumer_->OnAuthFailure(
AuthFailure(AuthFailure::AUTH_DISABLED));
}
if (callback)
std::move(callback).Run(false);
return;
}
DCHECK(!pending_auth_state_);
pending_auth_state_ = std::make_unique<AuthState>(user_context.GetAccountId(),
std::move(callback));
unlock_attempt_type_ = AUTH_PASSWORD;
authentication_start_time_ = base::Time::Now();
if (user_context.IsUsingPin())
unlock_attempt_type_ = AUTH_PIN;
const user_manager::User* user = FindUnlockUser(user_context.GetAccountId());
if (user) {
// Check to see if the user submitted a PIN and it is valid.
if (unlock_attempt_type_ == AUTH_PIN) {
quick_unlock::PinBackend::GetInstance()->TryAuthenticate(
user_context.GetAccountId(), *user_context.GetKey(),
base::BindOnce(&ScreenLocker::OnPinAttemptDone,
weak_factory_.GetWeakPtr(), user_context));
// OnPinAttemptDone will call ContinueAuthenticate.
return;
}
}
ContinueAuthenticate(user_context);
}
void ScreenLocker::AuthenticateWithChallengeResponse(
const AccountId& account_id,
AuthenticateCallback callback) {
LOG_ASSERT(IsUserLoggedIn(account_id)) << "Invalid user trying to unlock.";
// Do not attempt authentication if it is disabled for the user.
if (IsAuthTemporarilyDisabledForUser(account_id)) {
VLOG(1) << "Authentication disabled for user.";
if (auth_status_consumer_) {
auth_status_consumer_->OnAuthFailure(
AuthFailure(AuthFailure::AUTH_DISABLED));
}
std::move(callback).Run(false);
return;
}
if (!ChallengeResponseAuthKeysLoader::CanAuthenticateUser(account_id)) {
LOG(ERROR)
<< "Challenge-response authentication isn't supported for the user";
if (auth_status_consumer_) {
auth_status_consumer_->OnAuthFailure(
AuthFailure(AuthFailure::UNLOCK_FAILED));
}
std::move(callback).Run(false);
return;
}
DCHECK(!pending_auth_state_);
pending_auth_state_ =
std::make_unique<AuthState>(account_id, std::move(callback));
unlock_attempt_type_ = AUTH_CHALLENGE_RESPONSE;
challenge_response_auth_keys_loader_.LoadAvailableKeys(
account_id, base::BindOnce(&ScreenLocker::OnChallengeResponseKeysPrepared,
weak_factory_.GetWeakPtr(), account_id));
// OnChallengeResponseKeysPrepared will call ContinueAuthenticate.
}
void ScreenLocker::OnChallengeResponseKeysPrepared(
const AccountId& account_id,
std::vector<ChallengeResponseKey> challenge_response_keys) {
if (challenge_response_keys.empty()) {
// TODO(crbug.com/826417): Indicate the error in the UI.
if (pending_auth_state_) {
std::move(pending_auth_state_->callback).Run(/*auth_success=*/false);
pending_auth_state_.reset();
}
return;
}
const user_manager::User* const user =
user_manager::UserManager::Get()->FindUser(account_id);
DCHECK(user);
UserContext user_context(*user);
*user_context.GetMutableChallengeResponseKeys() =
std::move(challenge_response_keys);
ContinueAuthenticate(user_context);
}
void ScreenLocker::OnPinAttemptDone(const UserContext& user_context,
bool success) {
if (success) {
// Mark strong auth if this is cryptohome based pin.
if (quick_unlock::PinBackend::GetInstance()->ShouldUseCryptohome(
user_context.GetAccountId())) {
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForAccountId(
user_context.GetAccountId());
if (quick_unlock_storage)
quick_unlock_storage->MarkStrongAuth();
}
OnAuthSuccess(user_context);
} else {
// PIN authentication has failed; try submitting as a normal password.
ContinueAuthenticate(user_context);
}
}
void ScreenLocker::ContinueAuthenticate(
const chromeos::UserContext& user_context) {
if (user_context.GetAccountId().GetAccountType() ==
AccountType::ACTIVE_DIRECTORY &&
user_context.GetKey()->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN) {
// Try to get kerberos TGT while we have user's password typed on the lock
// screen. Failure to get TGT here is OK - that could mean e.g. Active
// Directory server is not reachable. AuthPolicyCredentialsManager regularly
// checks TGT status inside the user session.
AuthPolicyHelper::TryAuthenticateUser(
user_context.GetAccountId().GetUserEmail(),
user_context.GetAccountId().GetObjGuid(),
user_context.GetKey()->GetSecret());
}
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&ExtendedAuthenticator::AuthenticateToCheck,
extended_authenticator_.get(), user_context,
base::BindOnce(&ScreenLocker::OnPasswordAuthSuccess,
weak_factory_.GetWeakPtr(), user_context)));
}
const user_manager::User* ScreenLocker::FindUnlockUser(
const AccountId& account_id) {
for (const user_manager::User* user : users_) {
if (user->GetAccountId() == account_id)
return user;
}
return nullptr;
}
void ScreenLocker::OnStartLockCallback(bool locked) {
// Happens in tests that exit with a pending lock. In real lock failure,
// ash::LockStateController would cause the current user session to be
// terminated.
if (!locked)
return;
delegate_->OnAshLockAnimationFinished();
AccessibilityManager::Get()->PlayEarcon(
Sound::kLock, PlaySoundOption::kOnlyIfSpokenFeedbackEnabled);
}
void ScreenLocker::ClearErrors() {
delegate_->ClearErrors();
}
void ScreenLocker::Signout() {
delegate_->ClearErrors();
base::RecordAction(UserMetricsAction("ScreenLocker_Signout"));
// We expect that this call will not wait for any user input.
// If it changes at some point, we will need to force exit.
chrome::AttemptUserExit();
// Don't hide yet the locker because the chrome screen may become visible
// briefly.
}
void ScreenLocker::EnableInput() {
// TODO(crbug.com/927498): Remove this.
}
void ScreenLocker::ShowErrorMessage(int error_msg_id,
HelpAppLauncher::HelpTopic help_topic_id,
bool sign_out_only) {
delegate_->ShowErrorMessage(error_msg_id, help_topic_id);
}
user_manager::UserList ScreenLocker::GetUsersToShow() const {
user_manager::UserList users_to_show;
// Filter out Managed Guest Session users as they should not appear on the UI.
std::copy_if(users_.begin(), users_.end(), std::back_inserter(users_to_show),
[](const user_manager::User* user) -> bool {
return user->GetType() !=
user_manager::UserType::USER_TYPE_PUBLIC_ACCOUNT;
});
return users_to_show;
}
void ScreenLocker::SetLoginStatusConsumer(
chromeos::AuthStatusConsumer* consumer) {
auth_status_consumer_ = consumer;
}
// static
void ScreenLocker::InitClass() {
DCHECK(!g_screen_lock_observer);
g_screen_lock_observer = new ScreenLockObserver;
}
// static
void ScreenLocker::ShutDownClass() {
DCHECK(g_screen_lock_observer);
delete g_screen_lock_observer;
g_screen_lock_observer = nullptr;
// Delete `screen_locker_` if it is being shown.
ScheduleDeletion();
}
// static
void ScreenLocker::HandleShowLockScreenRequest() {
VLOG(1) << "Received ShowLockScreen request from session manager";
DCHECK(g_screen_lock_observer);
if (UserAddingScreen::Get()->IsRunning()) {
VLOG(1) << "Waiting for user adding screen to stop";
UserAddingScreen::Get()->AddObserver(g_screen_lock_observer);
UserAddingScreen::Get()->Cancel();
return;
}
if (g_screen_lock_observer->session_started() &&
user_manager::UserManager::Get()->CanCurrentUserLock()) {
ScreenLocker::Show();
} else {
// If the current user's session cannot be locked or the user has not
// completed all sign-in steps yet, log out instead. The latter is done to
// avoid complications with displaying the lock screen over the login
// screen while remaining secure in the case the user walks away during
// the sign-in steps. See crbug.com/112225 and crbug.com/110933.
VLOG(1) << "The user session cannot be locked, logging out";
SessionTerminationManager::Get()->StopSession(
login_manager::SessionStopReason::FAILED_TO_LOCK);
}
}
// static
void ScreenLocker::Show() {
base::RecordAction(UserMetricsAction("ScreenLocker_Show"));
DCHECK(base::CurrentUIThread::IsSet());
// Check whether the currently logged in user is a guest account and if so,
// refuse to lock the screen (crosbug.com/23764).
if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
VLOG(1) << "Refusing to lock screen for guest account";
return;
}
if (!screen_locker_) {
SessionControllerClientImpl::Get()->PrepareForLock(base::BindOnce([]() {
ScreenLocker* locker =
new ScreenLocker(user_manager::UserManager::Get()->GetUnlockUsers());
VLOG(1) << "Created ScreenLocker " << locker;
locker->Init();
}));
} else {
VLOG(1) << "ScreenLocker " << screen_locker_ << " already exists; "
<< " calling session manager's HandleLockScreenShown D-Bus method";
SessionManagerClient::Get()->NotifyLockScreenShown();
}
}
// static
void ScreenLocker::Hide() {
DCHECK(base::CurrentUIThread::IsSet());
// For a guest user, screen_locker_ would have never been initialized.
if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
VLOG(1) << "Refusing to hide lock screen for guest account";
return;
}
DCHECK(screen_locker_);
SessionControllerClientImpl::Get()->RunUnlockAnimation(base::BindOnce([]() {
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::ACTIVE);
ScreenLocker::ScheduleDeletion();
}));
}
void ScreenLocker::RefreshPinAndFingerprintTimeout() {
MaybeDisablePinAndFingerprintFromTimeout(
"RefreshPinAndFingerprintTimeout",
user_manager::UserManager::Get()->GetPrimaryUser()->GetAccountId());
}
// static
void ScreenLocker::ScheduleDeletion() {
// Avoid possible multiple calls.
if (screen_locker_ == nullptr)
return;
VLOG(1) << "Deleting ScreenLocker " << screen_locker_;
AccessibilityManager::Get()->PlayEarcon(
Sound::kUnlock, PlaySoundOption::kOnlyIfSpokenFeedbackEnabled);
delete screen_locker_;
screen_locker_ = nullptr;
}
void ScreenLocker::SaveSyncPasswordHash(const UserContext& user_context) {
if (!user_context.GetSyncPasswordData().has_value())
return;
const user_manager::User* user =
user_manager::UserManager::Get()->FindUser(user_context.GetAccountId());
if (!user || !user->is_active())
return;
Profile* profile = chromeos::ProfileHelper::Get()->GetProfileByUser(user);
if (profile)
login::SaveSyncPasswordDataToProfile(user_context, profile);
}
bool ScreenLocker::IsAuthTemporarilyDisabledForUser(
const AccountId& account_id) {
return base::Contains(users_with_temporarily_disabled_auth_, account_id);
}
void ScreenLocker::SetAuthenticatorsForTesting(
scoped_refptr<Authenticator> authenticator,
scoped_refptr<ExtendedAuthenticator> extended_authenticator) {
authenticator_ = std::move(authenticator);
extended_authenticator_ = std::move(extended_authenticator);
}
////////////////////////////////////////////////////////////////////////////////
// ScreenLocker, private:
ScreenLocker::AuthState::AuthState(AccountId account_id,
base::OnceCallback<void(bool)> callback)
: account_id(account_id), callback(std::move(callback)) {}
ScreenLocker::AuthState::~AuthState() = default;
ScreenLocker::~ScreenLocker() {
VLOG(1) << "Destroying ScreenLocker " << this;
DCHECK(base::CurrentUIThread::IsSet());
user_manager::UserManager::Get()->RemoveSessionStateObserver(this);
GetLoginScreenCertProviderService()
->pin_dialog_manager()
->RemovePinDialogHost(&security_token_pin_dialog_host_ash_impl_);
if (authenticator_)
authenticator_->SetConsumer(nullptr);
if (extended_authenticator_)
extended_authenticator_->SetConsumer(nullptr);
ClearErrors();
screen_locker_ = nullptr;
bool state = false;
VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
content::Source<ScreenLocker>(this), content::Details<bool>(&state));
VLOG(1) << "Calling session manager's HandleLockScreenDismissed D-Bus method";
SessionManagerClient::Get()->NotifyLockScreenDismissed();
if (saved_ime_state_.get()) {
input_method::InputMethodManager::Get()->SetState(saved_ime_state_);
}
}
void ScreenLocker::ScreenLockReady() {
locked_ = true;
base::TimeDelta delta = base::Time::Now() - start_time_;
VLOG(1) << "ScreenLocker " << this << " is ready after " << delta.InSecondsF()
<< " second(s)";
UMA_HISTOGRAM_TIMES("ScreenLocker.ScreenLockTime", delta);
bool state = true;
VLOG(1) << "Emitting SCREEN_LOCK_STATE_CHANGED with state=" << state;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED,
content::Source<ScreenLocker>(this), content::Details<bool>(&state));
VLOG(1) << "Calling session manager's HandleLockScreenShown D-Bus method";
SessionManagerClient::Get()->NotifyLockScreenShown();
session_manager::SessionManager::Get()->SetSessionState(
session_manager::SessionState::LOCKED);
// Start a fingerprint authentication session if fingerprint is available for
// the primary user. Only the primary user can use fingerprint.
if (IsFingerprintAvailableForUser(
user_manager::UserManager::Get()->GetPrimaryUser())) {
VLOG(1) << "Fingerprint is available on lock screen, start fingerprint "
<< "auth session now.";
fp_service_->StartAuthSession();
} else {
VLOG(1) << "Fingerprint is not available on lock screen";
}
MaybeDisablePinAndFingerprintFromTimeout(
"ScreenLockReady",
user_manager::UserManager::Get()->GetPrimaryUser()->GetAccountId());
}
bool ScreenLocker::IsUserLoggedIn(const AccountId& account_id) const {
for (user_manager::User* user : users_) {
if (user->GetAccountId() == account_id)
return true;
}
return false;
}
void ScreenLocker::OnRestarted() {}
void ScreenLocker::OnEnrollScanDone(device::mojom::ScanResult scan_result,
bool enroll_session_complete,
int percent_complete) {}
void ScreenLocker::OnAuthScanDone(
device::mojom::ScanResult scan_result,
const base::flat_map<std::string, std::vector<std::string>>& matches) {
RefreshPinAndFingerprintTimeout();
VLOG(1) << "Receive fingerprint auth scan result. scan_result="
<< scan_result;
unlock_attempt_type_ = AUTH_FINGERPRINT;
const user_manager::User* primary_user =
user_manager::UserManager::Get()->GetPrimaryUser();
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForUser(primary_user);
if (!quick_unlock_storage ||
!quick_unlock_storage->IsFingerprintAuthenticationAvailable()) {
// In theory this should be very rare. The auth session should be ended when
// fingerprint becomes unavaliable.
LoginScreenClient::Get()->auth_recorder()->RecordFingerprintUnlockResult(
LoginAuthRecorder::FingerprintUnlockResult::kFingerprintUnavailable,
base::nullopt);
return;
}
if (IsAuthTemporarilyDisabledForUser(primary_user->GetAccountId())) {
LoginScreenClient::Get()->auth_recorder()->RecordFingerprintUnlockResult(
LoginAuthRecorder::FingerprintUnlockResult::kAuthTemporarilyDisabled,
base::nullopt);
return;
}
LoginScreenClient::Get()->auth_recorder()->RecordAuthMethod(
LoginAuthRecorder::AuthMethod::kFingerprint);
if (scan_result != device::mojom::ScanResult::SUCCESS) {
LOG(ERROR) << "Fingerprint unlock failed because scan_result="
<< scan_result;
OnFingerprintAuthFailure(*primary_user);
LoginScreenClient::Get()->auth_recorder()->RecordFingerprintUnlockResult(
LoginAuthRecorder::FingerprintUnlockResult::kMatchFailed,
base::nullopt);
return;
}
UserContext user_context(*primary_user);
if (!base::Contains(matches, primary_user->username_hash())) {
LOG(ERROR) << "Fingerprint unlock failed because it does not match primary"
<< " user's record";
OnFingerprintAuthFailure(*primary_user);
LoginScreenClient::Get()->auth_recorder()->RecordFingerprintUnlockResult(
LoginAuthRecorder::FingerprintUnlockResult::kMatchNotForPrimaryUser,
base::nullopt);
return;
}
LoginScreenClient::Get()->auth_recorder()->RecordFingerprintUnlockResult(
LoginAuthRecorder::FingerprintUnlockResult::kSuccess,
quick_unlock_storage->fingerprint_storage()->unlock_attempt_count());
ash::LoginScreen::Get()->GetModel()->NotifyFingerprintAuthResult(
primary_user->GetAccountId(), true /*success*/);
VLOG(1) << "Fingerprint unlock is successful.";
OnAuthSuccess(user_context);
}
void ScreenLocker::OnSessionFailed() {
LOG(ERROR) << "Fingerprint session failed.";
}
void ScreenLocker::ActiveUserChanged(user_manager::User* active_user) {
// During ScreenLocker lifetime active user could only change when unlock has
// started. See https://crbug.com/1022667 for more details.
CHECK(unlock_started_);
}
void ScreenLocker::OnFingerprintAuthFailure(const user_manager::User& user) {
UMA_HISTOGRAM_ENUMERATION("ScreenLocker.AuthenticationFailure",
unlock_attempt_type_, UnlockType::AUTH_COUNT);
ash::LoginScreen::Get()->GetModel()->NotifyFingerprintAuthResult(
user.GetAccountId(), false /*success*/);
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForUser(&user);
if (quick_unlock_storage &&
quick_unlock_storage->IsFingerprintAuthenticationAvailable()) {
quick_unlock_storage->fingerprint_storage()->AddUnlockAttempt();
if (quick_unlock_storage->fingerprint_storage()->ExceededUnlockAttempts()) {
VLOG(1) << "Fingerprint unlock is disabled because it reached maximum"
<< " unlock attempt.";
ash::LoginScreen::Get()->GetModel()->SetFingerprintState(
user.GetAccountId(), ash::FingerprintState::DISABLED_FROM_ATTEMPTS);
delegate_->ShowErrorMessage(IDS_LOGIN_ERROR_FINGERPRINT_MAX_ATTEMPT,
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
}
}
if (auth_status_consumer_) {
AuthFailure failure(AuthFailure::UNLOCK_FAILED);
auth_status_consumer_->OnAuthFailure(failure);
}
}
void ScreenLocker::MaybeDisablePinAndFingerprintFromTimeout(
const std::string& source,
const AccountId& account_id) {
VLOG(1) << "MaybeDisablePinAndFingerprintFromTimeout source=" << source;
update_fingerprint_state_timer_.Stop();
// Update PIN state.
quick_unlock::PinBackend::GetInstance()->CanAuthenticate(
account_id, base::BindOnce(&ScreenLocker::OnPinCanAuthenticate,
weak_factory_.GetWeakPtr(), account_id));
quick_unlock::QuickUnlockStorage* quick_unlock_storage =
quick_unlock::QuickUnlockFactory::GetForAccountId(account_id);
if (quick_unlock_storage) {
if (quick_unlock_storage->HasStrongAuth()) {
// Call this function again when strong authentication expires. PIN may
// also depend on strong authentication if it is prefs-based. Fingerprint
// always requires strong authentication.
const base::TimeDelta next_strong_auth =
quick_unlock_storage->TimeUntilNextStrongAuth();
VLOG(1) << "Scheduling next pin and fingerprint timeout check in "
<< next_strong_auth;
update_fingerprint_state_timer_.Start(
FROM_HERE, next_strong_auth,
base::BindOnce(
&ScreenLocker::MaybeDisablePinAndFingerprintFromTimeout,
base::Unretained(this), "update_fingerprint_state_timer_",
account_id));
} else {
// Strong auth is unavailable; disable fingerprint if it was enabled.
if (quick_unlock_storage->fingerprint_storage()
->IsFingerprintAvailable()) {
VLOG(1) << "Require strong auth to make fingerprint unlock available.";
ash::LoginScreen::Get()->GetModel()->SetFingerprintState(
account_id, ash::FingerprintState::DISABLED_FROM_TIMEOUT);
fp_service_->EndCurrentAuthSession(base::BindOnce([](bool success) {
if (success)
return;
DLOG(ERROR) << "Failed to end fingerprint auth session";
}));
}
}
}
}
void ScreenLocker::OnPinCanAuthenticate(const AccountId& account_id,
bool can_authenticate) {
ash::LoginScreen::Get()->GetModel()->SetPinEnabledForUser(account_id,
can_authenticate);
}
} // namespace chromeos
| 38.668099 | 89 | 0.718528 | Ron423c |
5b3c34d57c02a7795a68aa4ace858f6ea5921b25 | 697 | cpp | C++ | GeeksForGeeks/number_of_unique_paths.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/number_of_unique_paths.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | GeeksForGeeks/number_of_unique_paths.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <iomanip>
using namespace std;
// dynamic programming
int main(){
int t, m, n;
cin >> t;
while(t--){
cin >> m >> n;
vector<vector<int>> ve(m, vector<int> (n, 1));
for(int i = 1; i < m; i++){
ve[i][0] = 1;
}
for(int i = 1; i < n; i++){
ve[0][i] = 1;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
ve[i][j] = ve[i][j - 1] + ve[i - 1][j];
}
}
cout << ve[m-1][n-1] << endl;
}
return 0;
} | 22.483871 | 55 | 0.426112 | tanishq1g |
5b3dc38e0fd3189a12e0dd0761c6f19f6df170e9 | 320 | hpp | C++ | domain/params/inc/i_hit_params.hpp | PKizin/game_design | 6223466ea46c091616f8d832659306fe7140b316 | [
"MIT"
] | null | null | null | domain/params/inc/i_hit_params.hpp | PKizin/game_design | 6223466ea46c091616f8d832659306fe7140b316 | [
"MIT"
] | null | null | null | domain/params/inc/i_hit_params.hpp | PKizin/game_design | 6223466ea46c091616f8d832659306fe7140b316 | [
"MIT"
] | null | null | null | #ifndef I_HIT_PARAMS_HPP
#define I_HIT_PARAMS_HPP
#include "e_params_categories.hpp"
class IHitParams {
public:
virtual float get_hit_param(EHitParams) const = 0;
virtual void set_hit_param(EHitParams, float) = 0;
protected:
IHitParams() { }
virtual ~IHitParams() { }
};
#endif // I_HIT_PARAMS_HPP
| 16.842105 | 54 | 0.725 | PKizin |
5b3f2bc436fcaf9a49307a565a1bbe07f5440df3 | 2,740 | cpp | C++ | numeric.cpp | SimplyCpp/exemplos | 139cd3c7af6885d0f4be45b0049e0f714bce3468 | [
"MIT"
] | 6 | 2015-05-19T06:30:06.000Z | 2018-07-24T08:15:45.000Z | numeric.cpp | SimplyCpp/exemplos | 139cd3c7af6885d0f4be45b0049e0f714bce3468 | [
"MIT"
] | 1 | 2015-05-19T06:42:38.000Z | 2015-05-19T14:45:49.000Z | numeric.cpp | SimplyCpp/exemplos | 139cd3c7af6885d0f4be45b0049e0f714bce3468 | [
"MIT"
] | 3 | 2015-10-09T05:54:58.000Z | 2018-07-25T13:52:32.000Z | //Sample provided by Thiago Massari Guedes
//December 2015
//http://www.simplycpp.com/
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
namespace concrete {
//C++98 version ----------------------------
struct numerical_appender {
numerical_appender(std::string &buf) : _buf(buf) { }
void operator()(const char c) {
if( c >= '0' && c <= '9' ) _buf.push_back(c);
}
private:
std::string &_buf;
};
void get_numeric(const std::string &input, std::string &output)
{
numerical_appender appender(output);
std::for_each(input.begin(), input.end(), appender);
}
//C++14 version ----------------------------
std::string get_numeric(const std::string &input)
{
std::string output;
std::for_each(begin(input), end(input), [&output](const char c) {
if( c >= '0' && c <= '9' ) output.push_back(c);
});
return output;
}
}
namespace generic {
//Generic version - C++98 ------------------
template<class OutputIterator, class ValueType>
struct numerical_appender {
numerical_appender(OutputIterator it) : _it(it) { }
void operator()(const ValueType c) {
if( c >= '0' && c <= '9' ) {
*_it = c;
_it++;
}
}
private:
OutputIterator _it;
};
template<class T>
void get_numeric(const T &input, T &output)
{
typedef std::back_insert_iterator<T> it_type;
it_type it = std::back_inserter(output);
numerical_appender<it_type, typename T::value_type> appender(it);
std::for_each(input.begin(), input.end(), appender);
}
//Generic version - C++14 ------------------
template<typename T>
T get_numeric(const T &input)
{
T output;
std::for_each(begin(input), end(input), [&output](auto c) {
if( c >= '0' && c <= '9' ) output.push_back(c);
});
return output;
}
}
namespace with_stl {
template<typename T>
T get_numeric(const T &input)
{
T output;
std::copy_if(begin(input), end(input), std::back_inserter(output), [](auto c) {
if( c >= '0' && c <= '9' ) return true;
return false;
});
return output;
}
}
int main() {
//C++98 version
std::string value = "12asew3d45ddf678ee9 0";
std::string num;
concrete::get_numeric(value, num);
std::cout << value << " - " << num << std::endl;
num.clear();
generic::get_numeric(value, num);
std::cout << value << " - " << num << std::endl;
//C++14 version
std::cout << value << " - " << concrete::get_numeric(value) << std::endl;
std::cout << value << " - " << generic::get_numeric(value) << std::endl;
std::cout << value << " - " << with_stl::get_numeric(value) << std::endl;
std::vector<char> v_in {'1', 'a', '2', 'b', 'c', '3'};
decltype(v_in) v_out = generic::get_numeric(v_in);
for(auto &i : v_out) {
std::cout << i << " ";
}
std::cout << std::endl;
}
| 24.464286 | 81 | 0.599635 | SimplyCpp |
5b44ad8774a4a352a2fcbc42422aa966a945acd3 | 967 | hpp | C++ | SDK/ARKSurvivalEvolved_LeftClimbing_ImpactEffect_Metal_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_LeftClimbing_ImpactEffect_Metal_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_LeftClimbing_ImpactEffect_Metal_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_LeftClimbing_ImpactEffect_Metal_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function LeftClimbing_ImpactEffect_Metal.LeftClimbing_ImpactEffect_Metal_C.UserConstructionScript
struct ALeftClimbing_ImpactEffect_Metal_C_UserConstructionScript_Params
{
};
// Function LeftClimbing_ImpactEffect_Metal.LeftClimbing_ImpactEffect_Metal_C.ExecuteUbergraph_LeftClimbing_ImpactEffect_Metal
struct ALeftClimbing_ImpactEffect_Metal_C_ExecuteUbergraph_LeftClimbing_ImpactEffect_Metal_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 29.30303 | 152 | 0.638056 | 2bite |
5b460f288b981de7fde05ad02c8dee3c9f2ec179 | 1,090 | cpp | C++ | examples/toml_to_json_transcoder.cpp | GiulioRomualdi/tomlplusplus | 3f04e12b53f6fca1c12f230d285da167a656c899 | [
"MIT"
] | null | null | null | examples/toml_to_json_transcoder.cpp | GiulioRomualdi/tomlplusplus | 3f04e12b53f6fca1c12f230d285da167a656c899 | [
"MIT"
] | null | null | null | examples/toml_to_json_transcoder.cpp | GiulioRomualdi/tomlplusplus | 3f04e12b53f6fca1c12f230d285da167a656c899 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <toml++/toml.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
using namespace std::string_view_literals;
int main(int argc, char** argv)
{
#ifdef _WIN32
SetConsoleOutputCP(65001); //UTF-8 console output
#endif
//read from a file
if (argc > 1)
{
auto path = std::string{ argv[1] };
auto file = std::ifstream{ path };
if (!file)
{
std::cerr << "The file '"sv << path << "' could not be opened for reading."sv << std::endl;
return -1;
}
try
{
const auto table = toml::parse(file, std::move(path));
std::cout << toml::json_formatter{ table } << std::endl;
}
catch (const toml::parse_error& err)
{
std::cerr << "Error parsing file:\n"sv << err << std::endl;
return 1;
}
}
//read directly from stdin
else
{
try
{
const auto table = toml::parse(std::cin);
std::cout << toml::json_formatter{ table } << std::endl;
}
catch (const toml::parse_error& err)
{
std::cerr << "Error parsing stdin:\n"sv << err << std::endl;
return 1;
}
}
return 0;
}
| 18.793103 | 94 | 0.615596 | GiulioRomualdi |
5b4778588cf91e7a561ea17e1f690d1383179466 | 19,994 | cpp | C++ | time_util.cpp | r3dl3g/util | 385fd89d2d453d8827e3b92187b4087744b3d8c4 | [
"MIT"
] | null | null | null | time_util.cpp | r3dl3g/util | 385fd89d2d453d8827e3b92187b4087744b3d8c4 | [
"MIT"
] | null | null | null | time_util.cpp | r3dl3g/util | 385fd89d2d453d8827e3b92187b4087744b3d8c4 | [
"MIT"
] | null | null | null | /**
* @copyright (c) 2015-2021 Ing. Buero Rothfuss
* Riedlinger Str. 8
* 70327 Stuttgart
* Germany
* http://www.rothfuss-web.de
*
* @author <a href="mailto:armin@rothfuss-web.de">Armin Rothfuss</a>
*
* Project utility lib
*
* @brief C++ API: time utilities
*
* @license MIT license. See accompanying file LICENSE.
*/
// --------------------------------------------------------------------------
//
// Common includes
//
#include <iomanip>
// --------------------------------------------------------------------------
//
// Library includes
//
#include "time_util.h"
#include "string_util.h"
#include "ostream_resetter.h"
/**
* Provides an API to stream into OutputDebugString.
*/
namespace util {
namespace time {
// --------------------------------------------------------------------------
std::tm mktm (int year, int month, int day, int hour, int minute, int second, int isdst) {
return std::tm{ second, minute, hour, day, tm_mon(month), tm_year(year), 0, 0, isdst };
}
// --------------------------------------------------------------------------
std::tm time_t2tm (const std::time_t now) {
std::tm t{};
#ifdef WIN32
localtime_s(&t, &now);
#else
localtime_r(&now, &t);
#endif
return t;
}
// --------------------------------------------------------------------------
std::tm time_t2utc (const std::time_t now) {
std::tm t{};
#ifdef WIN32
gmtime_s(&t, &now);
#else
gmtime_r(&now, &t);
#endif
return t;
}
// --------------------------------------------------------------------------
time_point time_t2time_point (std::time_t t) {
return std::chrono::system_clock::from_time_t(t);
}
std::time_t time_point2time_t (time_point tp) {
return std::chrono::system_clock::to_time_t(tp);
}
// --------------------------------------------------------------------------
std::time_t get_local_time_offset () {
static std::time_t offset = [] () {
std::tm t_ = mktm(2000, 1, 1, 0, 0, 0, 0);
const auto t = std::mktime(&t_);
std::tm tl_ = time_t2tm(t);
const auto tl = std::mktime(&tl_);
std::tm tu_ = time_t2utc(t);
const auto tu = std::mktime(&tu_);
return (tl - tu);
} ();
return offset;
}
// --------------------------------------------------------------------------
std::time_t tm2time_t (const std::tm& t_) {
std::tm t = t_;
return std::mktime(&t);
}
std::time_t tm2time_t (std::tm&& t) {
return std::mktime(&t);
}
time_point mktime_point (int year, int month, int day, int hour, int minute, int second, int millis, int isdst) {
return std::chrono::system_clock::from_time_t(tm2time_t(mktm(year, month, day, hour, minute, second, isdst))) +
std::chrono::milliseconds(millis);
}
// --------------------------------------------------------------------------
std::tm local_time (time_point const& tp) {
return time_t2tm(std::chrono::system_clock::to_time_t(tp));
}
std::tm local_time_now () {
return local_time(std::chrono::system_clock::now());
}
// --------------------------------------------------------------------------
std::time_t utc2time_t (const std::tm& t) {
return tm2time_t(t) + get_local_time_offset();
}
std::time_t utc2time_t (std::tm&& t) {
return tm2time_t(std::move(t)) + get_local_time_offset();
}
time_point mktime_point_from_utc (int year, int month, int day, int hour, int minute, int second, int millis) {
return std::chrono::system_clock::from_time_t(utc2time_t(mktm(year, month, day, hour, minute, second, 0))) +
std::chrono::milliseconds(millis);
}
std::tm utc_time (time_point const& tp) {
return time_t2utc(std::chrono::system_clock::to_time_t(tp));
}
std::tm utc_time_now () {
return utc_time(std::chrono::system_clock::now());
}
// --------------------------------------------------------------------------
UTIL_EXPORT int week_of_year (const std::tm& t) {
return ((t.tm_yday + 7 - weekday_of(t)) / 7);
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::time_t first_day_of_week (int year, int w) {
const int yday = w * 7;
const auto t = tm2time_t(mktm(year, 1, yday));
const auto tm = time_t2tm(t);
const auto wd = weekday_of(tm);
if (wd == 0) { // already monday
return t;
}
return tm2time_t(mktm(year_of(tm), 1, tm.tm_yday - wd + 1));
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::ostream& format_datetime (std::ostream& out,
const std::tm& t,
const char* date_delem,
const char* separator,
const char* time_delem) {
format_date(out, t, date_delem);
out << separator;
format_time(out, t, time_delem);
return out;
}
std::string format_datetime (const std::tm& t,
const char* date_delem,
const char* separator,
const char* time_delem) {
std::ostringstream os;
format_datetime(os, t, date_delem, separator, time_delem);
return os.str();
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::ostream& format_datetime (std::ostream& out,
const std::time_t& tp,
const char* date_delem,
const char* separator,
const char* time_delem) {
return format_datetime(out, time_t2tm(tp), date_delem, separator, time_delem);
}
std::string format_datetime (const std::time_t& tp,
const char* date_delem,
const char* separator,
const char* time_delem) {
std::ostringstream os;
format_datetime(os, tp, date_delem, separator, time_delem);
return os.str();
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::ostream& format_datetime (std::ostream& out,
time_point const& tp,
const char* date_delem,
const char* separator,
const char* time_delem,
bool add_micros) {
format_datetime(out, time_t2tm(std::chrono::system_clock::to_time_t(tp)), date_delem, separator, time_delem);
if (add_micros) {
auto t0 = std::chrono::time_point_cast<std::chrono::seconds>(tp);
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(tp - t0);
ostream_resetter r(out);
out << '.' << std::setfill('0') << std::setw(6) << micros.count();
}
return out;
}
std::string format_datetime (time_point const& tp,
const char* date_delem,
const char* separator,
const char* time_delem,
bool add_micros) {
std::ostringstream os;
format_datetime(os, tp, date_delem, separator, time_delem, add_micros);
return os.str();
}
// --------------------------------------------------------------------------
#if (USE_FILE_TIME_POINT)
std::string format_datetime (file_time_point const& ftp,
const char* date_delem,
const char* separator,
const char* time_delem,
bool add_micros) {
#if WIN32
# if defined USE_MINGW
using namespace std::chrono;
auto sctp = time_point_cast<system_clock::duration>(ftp - file_time_point::clock::now()
+ system_clock::now());
const auto tse = system_clock::to_time_t(sctp);
const time_point tp = time_point(time_point::duration(tse));
# elif _MSC_VER < 1917
const auto tse = ftp.time_since_epoch().count() - __std_fs_file_time_epoch_adjustment;
const time_point tp = time_point(time_point::duration(tse));
# else
const auto tse = ftp.time_since_epoch().count() - std::filesystem::__std_fs_file_time_epoch_adjustment;
const time_point tp = time_point(time_point::duration(tse));
# endif
#elif __cplusplus > 201703L // C++20
const auto systemTime = std::chrono::clock_cast<std::chrono::system_clock>(ftp);
const time_point tp = std::chrono::system_clock::to_time_t(systemTime);
#elif __cplusplus < 201401L
// this is gcc 5.1 or pior
std::time_t tt = file_time_point::clock::to_time_t(ftp);
const auto tp = std::chrono::system_clock::from_time_t(tt);
#else
using namespace std::chrono;
const time_point tp = time_point_cast<system_clock::duration>(ftp - file_time_point::clock::now()
+ system_clock::now());
#endif
return format_datetime(tp, date_delem, separator, time_delem, add_micros);
}
#endif
bool skip_delemiter (std::istream& is) {
char ch = is.peek();
while (is.good() && (('.' == ch) || (':' == ch) || ('-' == ch) || (' ' == ch) || ('\\' == ch) || ('T' == ch))) {
is.ignore();
ch = is.peek();
}
return is.good() && ('\n' != ch) && ('\r' != ch);
}
time_point parse_datetime (const std::string& s) {
std::istringstream is(s);
return parse_datetime(is);
}
time_point parse_datetime (std::istream& is) {
int year = 0, month = 1, day = 1, hour = 0, minute = 0, second = 0, millis = 0;
if (skip_delemiter(is)) {
is >> year;
if (skip_delemiter(is)) {
is >> month;
if (skip_delemiter(is)) {
is >> day;
if (skip_delemiter(is)) {
is >> hour;
if (skip_delemiter(is)) {
is >> minute;
if (skip_delemiter(is)) {
is >> second;
if (is.good() && (is.peek() == '.')) {
if (skip_delemiter(is)) {
is >> millis;
}
}
}
}
}
}
}
}
return mktime_point(year, month, day, hour, minute, second, millis);
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::ostream& format_time (std::ostream& out,
const std::tm& t,
const char* delem) {
ostream_resetter r(out);
out << std::setfill('0')
<< std::setw(2) << t.tm_hour << delem
<< std::setw(2) << t.tm_min << delem
<< std::setw(2) << t.tm_sec;
return out;
}
UTIL_EXPORT std::string format_time (const std::tm& t,
const char* delem) {
std::ostringstream is;
format_time(is, t, delem);
return is.str();
}
// --------------------------------------------------------------------------
UTIL_EXPORT std::ostream& format_date (std::ostream& out,
const std::tm& t,
const char* delem) {
ostream_resetter r(out);
out << std::setfill('0') << year_of(t) << delem
<< std::setw(2) << month_of(t) << delem
<< std::setw(2) << day_of(t);
return out;
}
UTIL_EXPORT std::ostream& format_date (std::ostream& out,
const std::time_t& tp,
const char* delem) {
return format_date(out, time_t2tm(tp), delem);
}
UTIL_EXPORT std::ostream& format_date (std::ostream& out,
time_point const& tp,
const char* delem) {
return format_date(out, std::chrono::system_clock::to_time_t(tp), delem);
}
// --------------------------------------------------------------------------
UTIL_EXPORT time_point parse_date (std::istream& is) {
int year = 0, month = 1, day = 1;
if (skip_delemiter(is)) {
is >> year;
if (skip_delemiter(is)) {
is >> month;
if (skip_delemiter(is)) {
is >> day;
}
}
}
return mktime_point(year, month, day);
}
UTIL_EXPORT time_point parse_date (const std::string& s) {
std::istringstream is(s);
return parse_date(is);
}
// --------------------------------------------------------------------------
duration mkduration (int hours, int mins, int secs, int mcrsecs) {
return std::chrono::hours(hours) + std::chrono::minutes(mins) + std::chrono::seconds(secs) + std::chrono::microseconds(mcrsecs);
}
// --------------------------------------------------------------------------
duration_parts duration2parts (duration const& d) {
using namespace std::chrono;
const auto hrs = duration_cast<hours>(d);
const auto mins = duration_cast<minutes>(d - hrs);
const auto secs = duration_cast<seconds>(d - hrs - mins);
const auto ms = duration_cast<microseconds>(d - hrs - mins - secs);
return {
static_cast<int>(hrs.count()),
static_cast<int>(mins.count()),
static_cast<int>(secs.count()),
static_cast<int>(ms.count())
};
}
duration parts2duration (const duration_parts& p) {
using namespace std::chrono;
return hours(p.hours) + minutes(p.mins) + seconds(p.secs) + microseconds(p.micros);
}
// --------------------------------------------------------------------------
std::ostream& format_duration_mt (std::ostream& out,
duration const& d,
int hours_per_mt,
const char* separator,
const char* time_delem,
bool add_micros,
bool minimize) {
ostream_resetter r(out);
duration_parts p = duration2parts(d);
auto days = p.hours / hours_per_mt;
p.hours %= hours_per_mt;
bool has_prefix = !minimize;
if (days || has_prefix) {
out << days << separator;
has_prefix = true;
}
out << std::setfill('0');
if (p.hours || has_prefix) {
out << std::setw(2) << p.hours << time_delem;
has_prefix = true;
}
if (p.mins || has_prefix) {
out << std::setw(2) << p.mins << time_delem;
has_prefix = true;
}
if (has_prefix) {
out << std::setw(2);
}
out << p.secs;
if (add_micros) {
out << '.' << std::setfill('0') << std::setw(6) << p.micros;
}
return out;
}
// --------------------------------------------------------------------------
std::ostream& format_duration_only_h (std::ostream& out,
duration const& d,
const char* time_delem,
bool add_micros,
bool minimize) {
ostream_resetter r(out);
duration_parts p = duration2parts(d);
out << std::setfill('0');
bool has_prefix = !minimize;
if (p.hours || has_prefix) {
out << std::setw(2) << p.hours << time_delem;
has_prefix = true;
}
if (p.mins || has_prefix) {
out << std::setw(2) << p.mins << time_delem;
has_prefix = true;
}
if (has_prefix) {
out << std::setw(2);
}
out << p.secs;
if (add_micros) {
out << '.' << std::setfill('0') << std::setw(6) << p.micros;
}
return out;
}
// --------------------------------------------------------------------------
std::ostream& format_duration (std::ostream& out,
duration const& d,
const char* separator,
const char* time_delem,
bool add_micros,
bool minimize) {
return format_duration_mt(out, d, 24, separator, time_delem, add_micros, minimize);
}
// --------------------------------------------------------------------------
std::string format_duration (duration const& d,
const char* separator,
const char* time_delem,
bool add_micros,
bool minimize) {
std::ostringstream os;
format_duration(os, d, separator, time_delem, add_micros, minimize);
return os.str();
}
// --------------------------------------------------------------------------
std::string format_duration_mt (duration const& d,
int hours_per_mt,
const char* separator,
const char* time_delem,
bool add_micros,
bool minimize) {
std::ostringstream os;
format_duration_mt(os, d, hours_per_mt, separator, time_delem, add_micros, minimize);
return os.str();
}
// --------------------------------------------------------------------------
std::string format_duration_only_h (duration const& d,
const char* time_delem,
bool add_micros,
bool minimize) {
std::ostringstream os;
format_duration_only_h(os, d, time_delem, add_micros, minimize);
return os.str();
}
// --------------------------------------------------------------------------
duration parse_duration (const std::string& s) {
std::istringstream is(s);
return parse_duration(is);
}
duration parse_duration (std::istream& is) {
int day = 0, hour = 0, minute = 0, second = 0, millis = 0;
if (skip_delemiter(is)) {
is >> day;
if (skip_delemiter(is)) {
is >> hour;
if (skip_delemiter(is)) {
is >> minute;
if (skip_delemiter(is)) {
is >> second;
if (is.good() && (is.peek() == '.')) {
if (skip_delemiter(is)) {
is >> millis;
}
}
}
}
}
}
return std::chrono::milliseconds(((((((day * 24) + hour) * 60) + minute) * 60) + second) * 1000 + millis);
}
} // namespace time
} // namespace util
namespace std {
ostream& operator<< (ostream& out, util::time::time_point const& tp) {
return util::time::format_datetime(out, tp);
}
istream& operator>> (istream& in, util::time::time_point& tp) {
tp = util::time::parse_datetime(in);
return in;
}
ostream& operator<< (ostream& out, util::time::duration const& d) {
return util::time::format_duration(out, d, " ", ":", true);
}
istream& operator>> (istream& in, util::time::duration& d) {
d = util::time::parse_duration(in);
return in;
}
} // namespace std
| 36.025225 | 134 | 0.449485 | r3dl3g |
5b4981befd71c99fe04ba5e3c15d7dbce7632867 | 813 | cpp | C++ | tutorial/classes/Person.cpp | epg-apg/cpptutorial | 028e5039314ccd98146d6f394981f137c5b85b19 | [
"Unlicense"
] | null | null | null | tutorial/classes/Person.cpp | epg-apg/cpptutorial | 028e5039314ccd98146d6f394981f137c5b85b19 | [
"Unlicense"
] | null | null | null | tutorial/classes/Person.cpp | epg-apg/cpptutorial | 028e5039314ccd98146d6f394981f137c5b85b19 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <sstream>
#include "Person.h"
Person::Person()
{
std::cout << "Person created..." << std::endl;
name = "George";
age = 0;
}
Person::Person(std::string newName)
{
name = newName;
age = 0;
}
Person::Person(std::string newName, int newAge)
{
name = newName;
age = newAge;
}
Person::Person(int age)
{
this->age = age;
}
Person::~Person()
{
std::cout << "Person destroyed..." << std::endl;
}
void Person::outputMemoryAddress()
{
std::cout << "Memory: " << this << std::endl;
}
std::string Person::toString()
{
std::stringstream temp;
temp << "My name is " << name << ". Age: " << age;
return temp.str();
}
void Person::setName(std::string newName)
{
name = newName;
}
std::string Person::getName()
{
return name;
} | 14.517857 | 54 | 0.579336 | epg-apg |
5b49b5a5e1d7e5ce8c957f6cf2440b3acbdbd91d | 6,924 | cpp | C++ | leetcode/30_days_challenge/2021_3_March/20.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/30_days_challenge/2021_3_March/20.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/30_days_challenge/2021_3_March/20.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: March 20th
link: https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/590/week-3-march-15th-march-21st/3673/
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
using namespace std;
/*
Q Design Underground System
Implement the UndergroundSystem class:
+ void checkIn(int id, string stationName, int t)
- A customer with a card id equal to id, gets in the station stationName at time t.
- A customer can only be checked into one place at a time.
+ void checkOut(int id, string stationName, int t)
- A customer with a card id equal to id, gets out from the station stationName at time t.
- double getAverageTime(string startStation, string endStation)
+ Returns the average time to travel between the startStation and the endStation.
- The average time is computed from all the previous traveling from startStation to endStation that happened directly.
- Call to getAverageTime is always valid.
You can assume all calls to checkIn and checkOut methods are consistent.
If a customer gets in at time t1 at some station, they get out at time t2 with t2 > t1. All events happen in chronological order.
Example 1:
Input
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
Output
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15);
undergroundSystem.checkOut(27, "Waterloo", 20);
undergroundSystem.checkOut(32, "Cambridge", 22);
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. There was only one travel from "Paradise" (at time 8) to "Cambridge" (at time 22)
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. There were two travels from "Leyton" to "Waterloo", a customer with id=45 from time=3 to time=15 and a customer with id=27 from time=10 to time=20. So the average time is ( (15-3) + (20-10) ) / 2 = 11.00000
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000
Example 2:
Input
["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]
Output
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]
Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(10, "Leyton", 3);
undergroundSystem.checkOut(10, "Paradise", 8);
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000
undergroundSystem.checkIn(5, "Leyton", 10);
undergroundSystem.checkOut(5, "Paradise", 16);
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000
undergroundSystem.checkIn(2, "Leyton", 21);
undergroundSystem.checkOut(2, "Paradise", 30);
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667
Constraints:
There will be at most 20000 operations.
1 <= id, t <= 106
All strings consist of uppercase and lowercase English letters, and digits.
1 <= stationName.length <= 10
Answers within 10-5 of the actual value will be accepted as correct.
Hide Hint #1
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
*/
//Faster solution!! always use reference!!
class UndergroundSystem
{
private:
unordered_map<int, std::pair<string, int> > idStationMap;
unordered_map<string, unordered_map<string, vector<double> > > data;
public:
UndergroundSystem()
{
}
void checkIn(int id, string stationName, int t)
{
idStationMap[id] = std::make_pair(stationName, t);
}
void checkOut(int id, string stationName, int t)
{
std::pair<string, int>& startData = idStationMap[id];
if(data[startData.first][stationName].empty())
{
data[startData.first][stationName] = {(t - startData.second) * 1.0, 1.0};
}
else
{
vector<double>& timeData = data[startData.first][stationName];
timeData[0] += (t - startData.second) * 1.0;
timeData[1]++;
}
}
double getAverageTime(string startStation, string endStation)
{
vector<double>& timeData = data[startStation][endStation];
double ans = ((timeData[0] / timeData[1]) * 100000 ) / 100000;
return ans;
}
};
// class UndergroundSystem
// {
// private:
// unordered_map<int, std::pair<string, int> > idStationMap;
// map<string, map<string, vector<int> > > data;
// public:
// UndergroundSystem()
// {
// }
// void checkIn(int id, string stationName, int t)
// {
// idStationMap[id] = std::make_pair(stationName, t);
// }
// void checkOut(int id, string stationName, int t)
// {
// std::pair<string, int> startData = idStationMap[id];
// data[startData.first][stationName].push_back(t - startData.second);
// }
// double getAverageTime(string startStation, string endStation)
// {
// map<string, vector<int> > data_ = data[startStation];
// vector<int>& time = data_[endStation];
// double sum = 0.0;
// for(int t : time)
// {
// sum += (t * 1.0);
// }
// double ans = ((sum / time.size()) * 100000 ) / 100000;
// return ans;
// }
// };
/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem* obj = new UndergroundSystem();
* obj->checkIn(id,stationName,t);
* obj->checkOut(id,stationName,t);
* double param_3 = obj->getAverageTime(startStation,endStation);
*/ | 38.043956 | 297 | 0.659301 | bvbasavaraju |
5b4b25e02378196ea5acb2abc84e6090787d1267 | 389 | cpp | C++ | 4th semester/lab_6/src/Sofa.cpp | kmalski/cpp_labs | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | 1 | 2020-05-19T17:14:55.000Z | 2020-05-19T17:14:55.000Z | 4th semester/lab_6/src/Sofa.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | 4th semester/lab_6/src/Sofa.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | #include "Sofa.h"
#include <iostream>
Sofa::Sofa(const int width, const int height, const int length, const int seat) : Mebel(width, height, length), _seat(seat) {}
Sofa::Sofa(const int seat) : _seat(seat) {}
Sofa::~Sofa() {
std::cout << "~Sofa" << std::endl;
}
void Sofa::print() const {
std::cout << "Sofa: ";
Mebel::print();
std::cout << " siedzisko: " << _seat;
}
| 22.882353 | 126 | 0.601542 | kmalski |
5b5600292d5f0d3a1d12f48353f0a1ffa28a0baa | 14,199 | cpp | C++ | lib/SmartSign/Display.cpp | in-tech/SmartSign | 476a07ea2606ca80d2193f2957e7b62fb114d05e | [
"MIT"
] | 4 | 2022-01-07T12:38:08.000Z | 2022-01-07T14:58:25.000Z | lib/SmartSign/Display.cpp | in-tech/SmartSign | 476a07ea2606ca80d2193f2957e7b62fb114d05e | [
"MIT"
] | null | null | null | lib/SmartSign/Display.cpp | in-tech/SmartSign | 476a07ea2606ca80d2193f2957e7b62fb114d05e | [
"MIT"
] | 2 | 2022-01-07T12:39:29.000Z | 2022-01-07T12:42:25.000Z | #include "Display.h"
#include "IAppContext.h"
#include <images.h>
#include <fonts.h>
#include "TimeUtils.h"
#include "CryptoUtils.h"
#include <qrcode.h>
#include "Log.h"
extern sIMAGE IMG_background;
extern sIMAGE IMG_booked;
extern sIMAGE IMG_free;
extern sIMAGE IMG_cwa;
// Hash of the last content that was presented.
// The hash is stored in RTC memory to survive deep-sleep.
#define MAX_HASH_SIZE 65
RTC_DATA_ATTR char rtc_lastHash[MAX_HASH_SIZE] = "";
Display::Display(IAppContext& ctx) :
_ctx(ctx),
_frameBuffer(EPD_WIDTH * EPD_HEIGHT / 4),
_paint(_frameBuffer.data(), EPD_WIDTH, EPD_HEIGHT, TWO_BITS),
_active(false)
{
}
Display::~Display()
{
}
void Display::Init()
{
SPI.begin();
pinMode(EPD_CS_PIN, OUTPUT);
digitalWrite(EPD_CS_PIN, HIGH);
}
void Display::DeInit()
{
if (_active)
{
_epd.WaitUntilIdle();
_epd.Sleep();
}
}
void Display::ShowScheduleScreen(const time_t localNow, const std::vector<ScheduleItem>& items)
{
const String date = TimeUtils::ToDateString(localNow);
const String name = _ctx.Settings().DisplayName;
const bool lowBattery = _ctx.GetPowerMgr().BatteryIsLow();
String itemsCacheStr;
bool booked = false;
time_t until = 0;
std::vector<ScheduleItem> upcomingItems;
for (auto& item : items)
{
itemsCacheStr += item.Subject;
itemsCacheStr += item.LocalStartTime;
itemsCacheStr += item.LocalEndTime;
itemsCacheStr += (localNow >= item.LocalStartTime) ? "[" : "";
itemsCacheStr += (localNow < item.LocalEndTime) ? "]" : "";
if (booked)
{
if (until >= item.LocalStartTime)
{
until = item.LocalEndTime;
}
}
else
{
if (until == 0 && localNow < item.LocalStartTime)
{
until = item.LocalStartTime;
}
}
if (localNow < item.LocalEndTime)
{
upcomingItems.push_back(item);
if (localNow >= item.LocalStartTime)
{
booked = true;
until = item.LocalEndTime;
}
}
}
if (PrepareHash("ShowScheduleScreen: " + date + name + itemsCacheStr + booked + until + String(lowBattery)))
{
// fonts
sFONT* font = &Overpass_mono28;
auto drawText = [&](const int x, const int y, const String& txt, const int color, const TextAlignment alignment = TextAlignment::LEFT)
{
_paint.DrawUtf8StringAt(x, y - 7, txt.c_str(), font, color, alignment);
};
// background
_paint.DrawImage(0, 0, &IMG_background);
// header
drawText(20, 26, date, WHITE);
drawText(IMG_background.Width - 20, 26, name, WHITE, TextAlignment::RIGHT);
// label
sIMAGE* labelImg = &IMG_free;
int labelColor = BLACK;
if (booked)
{
labelImg = &IMG_booked;
labelColor = RED;
}
_paint.DrawImage(428 - labelImg->Width / 2, 97, labelImg, labelColor, WHITE);
// until
if (until > 0)
{
const String untilStr = String("until ") + TimeUtils::ToShortTimeString(until);
drawText(428, 170, untilStr, (booked ? RED : BLACK), TextAlignment::CENTER);
}
// upcoming
for (int i = 0; i < std::min<int>(2, upcomingItems.size()); i++)
{
const int yOffset = i * 84;
const ScheduleItem& item = upcomingItems[i];
int color = BLACK;
if (localNow >= item.LocalStartTime && localNow < item.LocalEndTime)
{
// white font
color = WHITE;
// red background
_paint.DrawFilledRectangle(225, 207 + yOffset, IMG_background.Width - 9, 289 + yOffset, RED);
}
drawText(240, 226 + yOffset, TimeUtils::ToShortTimeString(item.LocalStartTime), color);
drawText(240, 255 + yOffset, TimeUtils::ToShortTimeString(item.LocalEndTime), color);
drawText(320, 233 + yOffset, item.Subject.substring(0, 25), color);
}
// CWA QR-Code
if (booked && !upcomingItems.empty() && _ctx.Settings().CwaEventQRCodes)
{
_paint.DrawFilledRectangle(0, 69, 213, EPD_HEIGHT, WHITE);
RenderCwaEventQRCode(*upcomingItems.begin());
}
else
{
// timebars
auto drawTimebars = [&](const int x, const time_t tmin, const time_t tmax)
{
const int yOffset = 69;
const time_t timeRange = tmax - tmin;
const int pixRange = IMG_background.Height - yOffset;
for (auto& item : items)
{
if (item.LocalStartTime < tmax && item.LocalEndTime > tmin)
{
const time_t start = max(item.LocalStartTime, tmin);
const time_t end = min(item.LocalEndTime, tmax);
const int barStart = yOffset + pixRange * (start - tmin) / timeRange;
const int barHeight = pixRange * (end - start) / timeRange;
_paint.DrawFilledRectangle(x, barStart, x + 40, barStart + barHeight, RED);
}
}
};
time_t midnight = previousMidnight(localNow);
drawTimebars(53, midnight + SECS_PER_HOUR * 5 + SECS_PER_MIN * 30, midnight + SECS_PER_HOUR * 12 + SECS_PER_MIN * 30);
drawTimebars(163, midnight + SECS_PER_HOUR * 12 + SECS_PER_MIN * 30, midnight + SECS_PER_HOUR * 19 + SECS_PER_MIN * 30);
}
if (lowBattery)
{
_paint.DrawImage(IMG_background.Width - 48, IMG_background.Height - 25, &IMG_bat_0);
}
Present(false);
}
}
void Display::ShowAdminMenuScreen(const String& btnInfoA, const String& btnInfoB)
{
std::vector<String> lines;
lines.push_back(String("Battery : ") + String(_ctx.GetPowerMgr().GetBatteryVoltage(), 1) + "V");
String wifi = _ctx.Settings().WifiSSID;
if (wifi.isEmpty())
{
wifi += "not configured";
}
else if (_ctx.GetNetworkMgr().IsPending())
{
wifi += " connecting...";
}
else if (!_ctx.GetNetworkMgr().WifiIsConnected())
{
wifi += " disconnected";
}
lines.push_back(String("WiFi : ") + wifi);
time_t utcNow;
if (_ctx.GetNetworkMgr().TryGetUtcTime(utcNow))
{
time_t localNow = TimeUtils::ToLocalTime(utcNow);
lines.push_back(String("DateTime : ") + TimeUtils::ToDateString(localNow) + " " + TimeUtils::ToShortTimeString(localNow));
}
else
{
lines.push_back("DateTime : N/A");
}
int maxWidth = 0;
String content;
for (auto& line : lines)
{
content += line;
content += "$";
maxWidth = std::max<int>(maxWidth, line.length());
}
if (PrepareHash("ShowAdminMenuScreen: " + content + btnInfoA + btnInfoB))
{
_paint.Clear(WHITE);
const int yPos = EPD_HEIGHT / 2 - lines.size() * 11;
for (int i = 0; i < lines.size(); i++)
{
_paint.DrawUtf8StringAt(200, yPos + i * 22, lines[i].c_str(), &Font16, BLACK);
}
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
RenderFirmwareVersion();
Present(true);
}
}
void Display::ShowSettingsScreen(const String& wifiSsid, const String& wifiKey, const String& btnInfoA, const String& btnInfoB)
{
const String content = wifiSsid + wifiKey + btnInfoA + btnInfoB;
if (PrepareHash("ShowSettingsScreen: " + content))
{
_paint.Clear(WHITE);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, 50, "Connect to this WiFi to access the settings screen.", &Font16, BLACK, TextAlignment::CENTER, 31);
const String code = String("WIFI:T:WPA;S:") + wifiSsid + ";P:" + wifiKey + ";;";;
RenderQRCode(code, EPD_WIDTH / 2 - 87, EPD_HEIGHT / 2 - 87, 174);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT - 80, (String("SSID: ") + wifiSsid).c_str(), &Font16, BLACK, TextAlignment::CENTER);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT - 70 + Font16.Height, (String("Key: ") + wifiKey).c_str(), &Font16, BLACK, TextAlignment::CENTER);
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
Present(true);
}
}
void Display::ShowAuthorizationScreen(const String& message, const String& uri, const String& code, const String& btnInfoA, const String& btnInfoB)
{
const String content = message + uri + code + btnInfoA + btnInfoB;
if (PrepareHash("ShowAuthorizationScreen: " + content))
{
_paint.Clear(WHITE);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, 30, message.c_str(), &Font16, BLACK, TextAlignment::CENTER, 47);
RenderQRCode(uri, EPD_WIDTH / 2 - 87, EPD_HEIGHT / 2 - 87, 174);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT - 74, code.c_str(), &Font16, BLACK, TextAlignment::CENTER);
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
Present(true);
}
}
void Display::ShowUnknownCardScreen(const String& header, const String& code, const String& btnInfoA, const String& btnInfoB)
{
const String content = header + code + btnInfoA + btnInfoB;
if (PrepareHash("ShowUnknownCardScreen: " + content))
{
_paint.Clear(WHITE);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT / 3, header.c_str(), &Font16, BLACK, TextAlignment::CENTER);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT / 2, code.c_str(), &Font16, BLACK, TextAlignment::CENTER);
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
Present(true);
}
}
void Display::ShowInfoScreen(const String& info, const String& btnInfoA, const String& btnInfoB)
{
if (PrepareHash("ShowInfoScreen: " + info))
{
_paint.Clear(WHITE);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT / 3, info.c_str(), &Font16, BLACK, TextAlignment::CENTER, 50);
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
Present(true);
}
}
void Display::ShowErrorScreen(const String& error, const String& btnInfoA, const String& btnInfoB)
{
Log::Error(error);
if (PrepareHash("ShowErrorScreen: " + error))
{
_paint.Clear(WHITE);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT / 6, "ERROR", &Font16, BLACK, TextAlignment::CENTER);
_paint.DrawUtf8StringAt(EPD_WIDTH / 2, EPD_HEIGHT / 3, error.c_str(), &Font16, BLACK, TextAlignment::CENTER, 50);
RenderButtonInfos(btnInfoA, btnInfoB, BLACK);
Present(true);
}
}
void Display::ShowFontTestScreen()
{
sFONT* fnt = &Overpass_mono28;
auto drawText = [&](const int yOffset, const int height, const int backColor, const int frontColor)
{
_paint.DrawFilledRectangle(0, yOffset, EPD_WIDTH, yOffset + height, backColor);
char c = '0';
for (int y = yOffset + 5; y < yOffset + height - fnt->Height - 5; y += fnt->Height)
{
for (int x = 5; x < EPD_WIDTH - fnt->Width - 5; x += fnt->Width)
{
_paint.DrawCharAt(x, y, c, fnt, frontColor);
c++;
}
}
};
drawText(0, EPD_HEIGHT / 2, WHITE, BLACK);
drawText(EPD_HEIGHT / 2, EPD_HEIGHT / 2, RED, WHITE);
Present(false);
}
void Display::RenderFirmwareVersion()
{
_paint.DrawUtf8StringAt(EPD_WIDTH - 10, EPD_HEIGHT - 20, SMART_SIGN_FW_VERSION, &Font16, BLACK, TextAlignment::RIGHT);
}
void Display::RenderQRCode(const String& message, const int x, const int y, const int size, const int version)
{
QRCode qrcode;
std::vector<uint8_t> qrcodeData(qrcode_getBufferSize(version));
qrcode_initText(&qrcode, qrcodeData.data(), version, ECC_LOW, message.c_str());
const int boxSize = size / qrcode.size;
for (uint8_t qy = 0; qy < qrcode.size; qy++)
{
for (uint8_t qx = 0; qx < qrcode.size; qx++)
{
const int color = qrcode_getModule(&qrcode, qx, qy) ? BLACK : WHITE;
const int xPos = x + qx * boxSize;
const int yPos = y + qy * boxSize;
_paint.DrawFilledRectangle(xPos, yPos, xPos + boxSize - 1, yPos + boxSize - 1, color);
}
}
}
void Display::RenderCwaEventQRCode(const ScheduleItem& item)
{
const int size = 61 * 3;
const int xCenter = 214 / 2;
const int yTop = 69 + (214 - size) / 2 + 2;
const String data = CryptoUtils::CreateCwaEventCode(item, _ctx.Settings().DisplayName);
RenderQRCode(data.c_str(), xCenter - size / 2, yTop, size, 11);
_paint.DrawImage(xCenter - IMG_cwa.Width / 2, yTop + size + 25, &IMG_cwa, BLACK, RED);
}
void Display::RenderButtonInfos(const String& btnInfoA, const String& btnInfoB, const int color)
{
auto renderBtnInfo = [&](const int y, const String& info)
{
if (!info.isEmpty())
{
_paint.DrawUtf8StringAt(20, y + 14, info.c_str(), &Font16, color);
_paint.DrawFilledRectangle(0, y, 8, y + 40, color);
}
};
renderBtnInfo(55, btnInfoA);
renderBtnInfo(EPD_HEIGHT - 86, btnInfoB);
}
bool Display::PrepareHash(const String& content)
{
// make sure that old hash is null terminated
rtc_lastHash[MAX_HASH_SIZE - 1] = '\0';
const String oldHash(rtc_lastHash);
const String newHash = CryptoUtils::Sha256(content).substring(0, MAX_HASH_SIZE);
if (newHash != oldHash)
{
Log::Debug(content);
// copy new hash to RTC memory
newHash.toCharArray(rtc_lastHash, MAX_HASH_SIZE);
return true;
}
return false;
}
void Display::Present(const bool fastMode)
{
if (!_active || (fastMode && _epd.IsBusy()))
{
_active = true;
_epd.Init();
}
Log::Info("e-paper refresh");
_epd.DisplayFrame(
_paint,
fastMode ? fastInvertedColorPalette : defaultColorPalette,
false);
if (fastMode)
{
delay(4000);
_epd.Init();
}
}
bool Display::IsBusy()
{
return _active && _epd.IsBusy();
}
| 32.051919 | 156 | 0.595605 | in-tech |
5b56fa3d1c9cafa19beb9caa57145323de9df6fc | 5,979 | cpp | C++ | Plugin~/Src/MeshSync/Utils/msMaterialExt.cpp | Mu-L/MeshSync | 6290618f6cc60802394bda8e2aa177648fcf5cfd | [
"Apache-2.0"
] | 1,047 | 2017-02-01T01:56:55.000Z | 2022-03-30T10:27:07.000Z | Plugin~/Src/MeshSync/Utils/msMaterialExt.cpp | Mu-L/MeshSync | 6290618f6cc60802394bda8e2aa177648fcf5cfd | [
"Apache-2.0"
] | 112 | 2017-03-03T09:10:01.000Z | 2022-03-24T16:25:20.000Z | Plugin~/Src/MeshSync/Utils/msMaterialExt.cpp | Mu-L/MeshSync | 6290618f6cc60802394bda8e2aa177648fcf5cfd | [
"Apache-2.0"
] | 120 | 2017-07-26T22:25:59.000Z | 2022-02-22T06:15:42.000Z | #include "pch.h"
#include "MeshSync/Utility/msMaterialExt.h"
namespace ms {
// shader keywords
static const char _Color[] = "_Color";
static const char _EmissionColor[] = "_EmissionColor";
static const char _Metallic[] = "_Metallic";
static const char _Glossiness[] = "_Glossiness";
static const char _MainTex[] = "_MainTex";
static const char _EmissionMap[] = "_EmissionMap";
static const char _MetallicGlossMap[] = "_MetallicGlossMap";
static const char _BumpScale[] = "_BumpScale";
static const char _BumpMap[] = "_BumpMap";
static const char DETAIL_ALBEDO_MAP_SHADER_VAR[] = "_DetailAlbedoMap";
static const char UV_SEC_SHADER_VAR[] = "_UVSec";
using TextureRecord = MaterialProperty::TextureRecord;
void StandardMaterial::setColor(mu::float4 v)
{
addProperty( MaterialProperty( _Color, v ));
}
mu::float4 StandardMaterial::getColor() const
{
const MaterialProperty* p = findProperty(_Color);
return p ? p->get<mu::float4>() : mu::float4::zero();
}
void StandardMaterial::setColorMap(const TextureRecord& v)
{
addProperty( MaterialProperty(_MainTex,v));
}
void StandardMaterial::setColorMap(const TexturePtr v)
{
if (v)
addProperty(MaterialProperty(_MainTex, v ));
}
Material::TextureRecord* StandardMaterial::getColorMap() const {
const MaterialProperty* p = findProperty(_MainTex);
return p ? &p->get<TextureRecord>() : nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
void StandardMaterial::SetDetailAlbedoMap(const TextureRecord& v) {
addProperty( MaterialProperty(DETAIL_ALBEDO_MAP_SHADER_VAR,v));
}
void StandardMaterial::SetDetailAlbedoMap(TexturePtr v) {
assert(v);
addProperty( MaterialProperty(DETAIL_ALBEDO_MAP_SHADER_VAR,v));
}
TextureRecord* StandardMaterial::GetDetailAlbedoMap() const {
const MaterialProperty* p = findProperty(DETAIL_ALBEDO_MAP_SHADER_VAR);
return p ? &p->get<TextureRecord>() : nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
void StandardMaterial::SetUVForSecondaryMap(float v) {
addProperty(MaterialProperty( UV_SEC_SHADER_VAR, v ));
}
float StandardMaterial::GetUVForSecondaryMap() const {
const MaterialProperty* p = findProperty(UV_SEC_SHADER_VAR);
return p ? p->get<float>() : 0.0f;
}
//----------------------------------------------------------------------------------------------------------------------
void StandardMaterial::setEmissionColor(mu::float4 v)
{
addProperty(MaterialProperty( _EmissionColor, v ));
}
mu::float4 StandardMaterial::getEmissionColor() const
{
const MaterialProperty* p = findProperty(_EmissionColor);
return p ? p->get<mu::float4>() : mu::float4::zero();
}
void StandardMaterial::setEmissionMap(const TextureRecord& v){
addProperty(MaterialProperty(_EmissionMap, v ));
}
void StandardMaterial::setEmissionMap(TexturePtr v) {
if (v)
addProperty(MaterialProperty( _EmissionMap, v ));
}
Material::TextureRecord* StandardMaterial::getEmissionMap() const
{
const MaterialProperty* p = findProperty(_EmissionMap);
return p ? &p->get<TextureRecord>() : nullptr;
}
void StandardMaterial::setMetallic(float v) {
addProperty( MaterialProperty( _Metallic, v ));
}
float StandardMaterial::getMetallic() const
{
const MaterialProperty* p = findProperty(_Metallic);
return p ? p->get<float>() : 0.0f;
}
void StandardMaterial::setMetallicMap(const TextureRecord& v) {
addProperty( MaterialProperty( _MetallicGlossMap, v ));
}
void StandardMaterial::setMetallicMap(TexturePtr v) {
if (v)
addProperty(MaterialProperty( _MetallicGlossMap, v ));
}
Material::TextureRecord* StandardMaterial::getMetallicMap() const
{
const MaterialProperty* p = findProperty(_MetallicGlossMap);
return p ? &p->get<TextureRecord>() : nullptr;
}
void StandardMaterial::setSmoothness(float v)
{
addProperty(MaterialProperty( _Glossiness, v ));
}
float StandardMaterial::getSmoothness() const
{
const MaterialProperty* p = findProperty(_Glossiness);
return p ? p->get<float>() : 0.0f;
}
void StandardMaterial::setBumpScale(float v)
{
addProperty(MaterialProperty( _BumpScale, v ));
}
float StandardMaterial::getBumpScale() const
{
const MaterialProperty* p = findProperty(_BumpScale);
return p ? p->get<float>() : 0.0f;
}
void StandardMaterial::setBumpMap(const TextureRecord& v) {
addProperty(MaterialProperty( _BumpMap, v ));
}
void StandardMaterial::setBumpMap(const TexturePtr v) {
if (v)
addProperty(MaterialProperty( _BumpMap, v ));
}
Material::TextureRecord* StandardMaterial::getBumpMap() const
{
const MaterialProperty* p = findProperty(_BumpMap);
return p ? &p->get<TextureRecord>() : nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
// StandardSpecMaterial
static const char _SpecColor[] = "_SpecColor";
static const char _SpecGlossMap[] = "_SpecGlossMap";
void StandardSpecMaterial::setupShader() {
if (shader.empty())
shader = "Standard (Specular setup)";
}
void StandardSpecMaterial::setSpecularColor(mu::float4 v) {
setupShader();
addProperty(MaterialProperty( _SpecColor, v ));
}
mu::float4 StandardSpecMaterial::getSpecularColor() {
MaterialProperty* p = findProperty(_SpecColor);
return p ? p->get<mu::float4>() : mu::float4::zero();
}
void StandardSpecMaterial::setSpecularGlossMap(const TextureRecord& v) {
setupShader();
addProperty(MaterialProperty( _SpecGlossMap, v ));
}
void StandardSpecMaterial::setSpecularGlossMap(TexturePtr v) {
setupShader();
if (v)
addProperty(MaterialProperty( _SpecGlossMap, v ));
}
Material::TextureRecord* StandardSpecMaterial::getSpecularGlossMap()
{
MaterialProperty* p = findProperty(_SpecGlossMap);
return p ? &p->get<TextureRecord>() : nullptr;
}
} // namespace ms
| 31.803191 | 120 | 0.673189 | Mu-L |
5b5f1ecb136405854385b4aa313db509d54ff208 | 17,787 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Bold_otf_27_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Bold_otf_27_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Bold_otf_27_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | #include <touchgfx/hal/Types.hpp>
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const uint8_t unicodes_Asap_Bold_otf_27_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = {
// Unicode: [0x0020, space]
// (Has no glyph data)
// Unicode: [0x0030, zero]
0x00,0x00,0xB4,0xFE,0x8D,0x00,0x00,0x00,0x90,0xFF,0xFF,0xFF,0x2D,0x00,0x00,0xF7,
0xFF,0xFF,0xFF,0xDF,0x00,0x10,0xFF,0xFF,0x36,0xFC,0xFF,0x06,0x60,0xFF,0x9F,0x00,
0xF3,0xFF,0x0D,0xB0,0xFF,0x4F,0x00,0xE0,0xFF,0x2F,0xE0,0xFF,0x1F,0x00,0xA0,0xFF,
0x5F,0xF1,0xFF,0x0F,0x00,0x80,0xFF,0x7F,0xF2,0xFF,0x0E,0x00,0x80,0xFF,0x8F,0xF2,
0xFF,0x0E,0x00,0x70,0xFF,0x9F,0xF2,0xFF,0x0E,0x00,0x70,0xFF,0x8F,0xF1,0xFF,0x0F,
0x00,0x80,0xFF,0x7F,0xE0,0xFF,0x1F,0x00,0xA0,0xFF,0x5F,0xB0,0xFF,0x4F,0x00,0xD0,
0xFF,0x2F,0x60,0xFF,0x9F,0x00,0xF3,0xFF,0x0D,0x10,0xFF,0xFF,0x36,0xFC,0xFF,0x07,
0x00,0xF7,0xFF,0xFF,0xFF,0xDF,0x00,0x00,0x90,0xFF,0xFF,0xFF,0x2D,0x00,0x00,0x00,
0xB4,0xFE,0x8D,0x00,0x00,
// Unicode: [0x0032, two]
0x00,0x60,0xDA,0xEF,0x8C,0x01,0x00,0x10,0xFD,0xFF,0xFF,0xFF,0x5F,0x00,0x40,0xFF,
0xFF,0xFF,0xFF,0xFF,0x01,0x00,0xFE,0x39,0x52,0xFE,0xFF,0x08,0x00,0x11,0x00,0x00,
0xF5,0xFF,0x0B,0x00,0x00,0x00,0x00,0xF3,0xFF,0x0D,0x00,0x00,0x00,0x00,0xF7,0xFF,
0x0B,0x00,0x00,0x00,0x10,0xFE,0xFF,0x07,0x00,0x00,0x00,0xB0,0xFF,0xEF,0x00,0x00,
0x00,0x00,0xF8,0xFF,0x5F,0x00,0x00,0x00,0x50,0xFF,0xFF,0x08,0x00,0x00,0x00,0xF3,
0xFF,0xBF,0x00,0x00,0x00,0x10,0xFE,0xFF,0x1D,0x00,0x00,0x00,0xC0,0xFF,0xFF,0x02,
0x00,0x00,0x00,0xFA,0xFF,0x5F,0x00,0x00,0x00,0x70,0xFF,0xFF,0x19,0x11,0x11,0x00,
0xF1,0xFF,0xFF,0xFF,0xFF,0xFF,0x1F,0xF0,0xFF,0xFF,0xFF,0xFF,0xFF,0x3F,0xB0,0xFF,
0xFF,0xFF,0xFF,0xFF,0x0E,
// Unicode: [0x0034, four]
0x00,0x00,0x00,0x00,0xF8,0xDF,0x02,0x00,0x00,0x00,0x00,0x40,0xFF,0xFF,0x05,0x00,
0x00,0x00,0x00,0xE1,0xFF,0xFF,0x05,0x00,0x00,0x00,0x00,0xFA,0xFF,0xFF,0x05,0x00,
0x00,0x00,0x50,0xFF,0xFF,0xFF,0x05,0x00,0x00,0x00,0xE1,0xFF,0xFF,0xFF,0x05,0x00,
0x00,0x00,0xFB,0xCF,0xFA,0xFF,0x05,0x00,0x00,0x60,0xFF,0x2F,0xFA,0xFF,0x05,0x00,
0x00,0xF2,0xFF,0x08,0xFA,0xFF,0x05,0x00,0x00,0xFC,0xDF,0x00,0xFA,0xFF,0x05,0x00,
0x70,0xFF,0x4F,0x00,0xFA,0xFF,0x05,0x00,0xF2,0xFF,0x0A,0x00,0xFA,0xFF,0x05,0x00,
0xFA,0xFF,0xFF,0xFF,0xFF,0xFF,0xEF,0x00,0xF8,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x03,
0xF3,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x01,0x10,0x11,0x11,0x11,0xFA,0xFF,0x06,0x00,
0x00,0x00,0x00,0x00,0xFA,0xFF,0x05,0x00,0x00,0x00,0x00,0x00,0xFA,0xFF,0x05,0x00,
0x00,0x00,0x00,0x00,0xE5,0xDF,0x02,0x00,
// Unicode: [0x0038, eight]
0x00,0x00,0xB6,0xFD,0xAD,0x03,0x00,0x00,0xC1,0xFF,0xFF,0xFF,0x9F,0x00,0x00,0xFB,
0xFF,0xFF,0xFF,0xFF,0x06,0x30,0xFF,0xEF,0x24,0xF8,0xFF,0x0C,0x60,0xFF,0x8F,0x00,
0xE0,0xFF,0x0F,0x60,0xFF,0x9F,0x00,0xF0,0xFF,0x0F,0x40,0xFF,0xFF,0x05,0xF8,0xFF,
0x0A,0x00,0xFC,0xFF,0xDF,0xFF,0xEF,0x02,0x00,0xD1,0xFF,0xFF,0xFF,0x2F,0x00,0x00,
0xF8,0xFF,0xFF,0xFF,0xEF,0x02,0x60,0xFF,0xEF,0xA4,0xFF,0xFF,0x0D,0xE0,0xFF,0x3F,
0x00,0xF4,0xFF,0x4F,0xF1,0xFF,0x0F,0x00,0x90,0xFF,0x8F,0xF2,0xFF,0x0D,0x00,0x70,
0xFF,0x9F,0xF0,0xFF,0x1F,0x00,0xA0,0xFF,0x8F,0xD0,0xFF,0xCF,0x23,0xF7,0xFF,0x4F,
0x30,0xFF,0xFF,0xFF,0xFF,0xFF,0x0B,0x00,0xF7,0xFF,0xFF,0xFF,0xCF,0x01,0x00,0x20,
0xD9,0xFF,0xBE,0x06,0x00,
// Unicode: [0x0041, A]
0x00,0x00,0x00,0xFC,0xFF,0x06,0x00,0x00,0x00,0x00,0x00,0x40,0xFF,0xFF,0x0D,0x00,
0x00,0x00,0x00,0x00,0x90,0xFF,0xFF,0x3F,0x00,0x00,0x00,0x00,0x00,0xF0,0xFF,0xFF,
0x8F,0x00,0x00,0x00,0x00,0x00,0xF4,0xFF,0xFF,0xEF,0x00,0x00,0x00,0x00,0x00,0xFA,
0xFF,0xFC,0xFF,0x03,0x00,0x00,0x00,0x00,0xFF,0xEF,0xF6,0xFF,0x09,0x00,0x00,0x00,
0x50,0xFF,0xAF,0xF2,0xFF,0x0E,0x00,0x00,0x00,0xA0,0xFF,0x5F,0xD0,0xFF,0x3F,0x00,
0x00,0x00,0xF0,0xFF,0x0F,0x80,0xFF,0x9F,0x00,0x00,0x00,0xF5,0xFF,0x0A,0x30,0xFF,
0xEF,0x00,0x00,0x00,0xFB,0xFF,0x05,0x00,0xFE,0xFF,0x04,0x00,0x10,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0x09,0x00,0x60,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x0E,0x00,0xB0,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0x4F,0x00,0xF1,0xFF,0x7F,0x77,0x77,0xB7,0xFF,0xAF,0x00,
0xF6,0xFF,0x0A,0x00,0x00,0x30,0xFF,0xFF,0x00,0xFC,0xFF,0x05,0x00,0x00,0x00,0xFD,
0xFF,0x05,0xFC,0xCF,0x00,0x00,0x00,0x00,0xF6,0xFF,0x06,
// Unicode: [0x0042, B]
0xD0,0xFF,0xFF,0xFF,0xBD,0x17,0x00,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x05,0x00,
0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x2F,0x00,0xF2,0xFF,0x7F,0x87,0xFD,0xFF,0x6F,0x00,
0xF2,0xFF,0x0F,0x00,0xE0,0xFF,0x9F,0x00,0xF2,0xFF,0x0F,0x00,0xA0,0xFF,0x8F,0x00,
0xF2,0xFF,0x0F,0x00,0xC0,0xFF,0x3F,0x00,0xF2,0xFF,0x0F,0x10,0xF8,0xFF,0x09,0x00,
0xF2,0xFF,0xFF,0xFF,0xFF,0x7F,0x00,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xAF,0x02,0x00,
0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x4F,0x00,0xF2,0xFF,0x7F,0x77,0xFA,0xFF,0xDF,0x00,
0xF2,0xFF,0x0F,0x00,0x20,0xFF,0xFF,0x03,0xF2,0xFF,0x0F,0x00,0x00,0xFE,0xFF,0x06,
0xF2,0xFF,0x0F,0x00,0x20,0xFF,0xFF,0x03,0xF2,0xFF,0x7F,0x77,0xE9,0xFF,0xFF,0x01,
0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0xAF,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x0B,0x00,
0xD0,0xFF,0xFF,0xFF,0xCE,0x4A,0x00,0x00,
// Unicode: [0x0043, C]
0x00,0x00,0x71,0xEB,0xFF,0xCE,0x49,0x00,0x00,0x70,0xFF,0xFF,0xFF,0xFF,0xFF,0x0A,
0x00,0xF9,0xFF,0xFF,0xFF,0xFF,0xFF,0x09,0x50,0xFF,0xFF,0xCF,0x89,0xC9,0xFF,0x02,
0xD0,0xFF,0xEF,0x03,0x00,0x00,0x21,0x00,0xF4,0xFF,0x6F,0x00,0x00,0x00,0x00,0x00,
0xF7,0xFF,0x0E,0x00,0x00,0x00,0x00,0x00,0xFA,0xFF,0x0B,0x00,0x00,0x00,0x00,0x00,
0xFB,0xFF,0x09,0x00,0x00,0x00,0x00,0x00,0xFC,0xFF,0x08,0x00,0x00,0x00,0x00,0x00,
0xFB,0xFF,0x09,0x00,0x00,0x00,0x00,0x00,0xFA,0xFF,0x0B,0x00,0x00,0x00,0x00,0x00,
0xF8,0xFF,0x0E,0x00,0x00,0x00,0x00,0x00,0xF4,0xFF,0x6F,0x00,0x00,0x00,0x00,0x00,
0xE0,0xFF,0xEF,0x03,0x00,0x00,0x62,0x00,0x70,0xFF,0xFF,0xBF,0x78,0xC9,0xFF,0x09,
0x00,0xFB,0xFF,0xFF,0xFF,0xFF,0xFF,0x0F,0x00,0x90,0xFF,0xFF,0xFF,0xFF,0xFF,0x0B,
0x00,0x00,0x82,0xEC,0xFF,0xCE,0x39,0x00,
// Unicode: [0x0045, E]
0xD0,0xFF,0xFF,0xFF,0xFF,0xFF,0x06,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x0A,0xF2,0xFF,
0xFF,0xFF,0xFF,0xFF,0x09,0xF2,0xFF,0x7F,0x77,0x77,0x77,0x01,0xF2,0xFF,0x0F,0x00,
0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,
0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xAF,0x00,0xF2,
0xFF,0xFF,0xFF,0xFF,0xEF,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xDF,0x00,0xF2,0xFF,0x7F,
0x77,0x77,0x37,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,
0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0xF2,0xFF,0x7F,0x77,0x77,0x77,0x02,
0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x09,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x0A,0xD0,0xFF,
0xFF,0xFF,0xFF,0xFF,0x06,
// Unicode: [0x0048, H]
0xE7,0xDF,0x03,0x00,0x00,0x10,0xFD,0xAF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xEF,0xFB,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xEF,
0xFB,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xEF,0xFB,0xFF,0x7B,0x77,0x77,0x97,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,0xFB,0xFF,0x07,0x00,0x00,0x40,0xFF,0xEF,
0xF7,0xEF,0x03,0x00,0x00,0x10,0xFD,0xAF,
// Unicode: [0x0050, P]
0xD0,0xFF,0xFF,0xFF,0xCE,0x17,0x00,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x05,0x00,
0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x2F,0x00,0xF2,0xFF,0x7F,0x77,0xFB,0xFF,0x9F,0x00,
0xF2,0xFF,0x0F,0x00,0xA0,0xFF,0xDF,0x00,0xF2,0xFF,0x0F,0x00,0x50,0xFF,0xFF,0x00,
0xF2,0xFF,0x0F,0x00,0x50,0xFF,0xFF,0x00,0xF2,0xFF,0x0F,0x00,0xA0,0xFF,0xDF,0x00,
0xF2,0xFF,0x7F,0x87,0xFB,0xFF,0x8F,0x00,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x1E,0x00,
0xF2,0xFF,0xFF,0xFF,0xFF,0xEF,0x03,0x00,0xF2,0xFF,0xFF,0xFF,0xCE,0x06,0x00,0x00,
0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,
0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,
0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,0xF2,0xFF,0x0F,0x00,0x00,0x00,0x00,0x00,
0xC0,0xFF,0x0B,0x00,0x00,0x00,0x00,0x00,
// Unicode: [0x0054, T]
0xF8,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x05,0xFC,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x09,
0xFB,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x08,0x72,0x77,0xD7,0xFF,0xBF,0x77,0x77,0x01,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,0x00,0x00,0xB0,0xFF,0x8F,0x00,0x00,0x00,
0x00,0x00,0x60,0xFE,0x4E,0x00,0x00,0x00,
// Unicode: [0x0056, V]
0xFA,0xDF,0x01,0x00,0x00,0x00,0xE5,0xEF,0x04,0xF9,0xFF,0x07,0x00,0x00,0x00,0xFD,
0xFF,0x03,0xF4,0xFF,0x0C,0x00,0x00,0x20,0xFF,0xDF,0x00,0xE0,0xFF,0x1F,0x00,0x00,
0x80,0xFF,0x8F,0x00,0x90,0xFF,0x6F,0x00,0x00,0xD0,0xFF,0x2F,0x00,0x40,0xFF,0xBF,
0x00,0x00,0xF2,0xFF,0x0D,0x00,0x00,0xFE,0xFF,0x00,0x00,0xF7,0xFF,0x08,0x00,0x00,
0xF9,0xFF,0x05,0x00,0xFC,0xFF,0x02,0x00,0x00,0xF4,0xFF,0x0A,0x10,0xFF,0xDF,0x00,
0x00,0x00,0xE0,0xFF,0x0E,0x60,0xFF,0x8F,0x00,0x00,0x00,0x90,0xFF,0x4F,0xB0,0xFF,
0x2F,0x00,0x00,0x00,0x40,0xFF,0x9F,0xF1,0xFF,0x0D,0x00,0x00,0x00,0x00,0xFE,0xEF,
0xF5,0xFF,0x07,0x00,0x00,0x00,0x00,0xF9,0xFF,0xFD,0xFF,0x02,0x00,0x00,0x00,0x00,
0xF3,0xFF,0xFF,0xDF,0x00,0x00,0x00,0x00,0x00,0xE0,0xFF,0xFF,0x7F,0x00,0x00,0x00,
0x00,0x00,0x90,0xFF,0xFF,0x2F,0x00,0x00,0x00,0x00,0x00,0x30,0xFF,0xFF,0x0D,0x00,
0x00,0x00,0x00,0x00,0x00,0xFB,0xFF,0x05,0x00,0x00,0x00,
// Unicode: [0x0061, a]
0x00,0xB7,0xFE,0xDF,0x4B,0x00,0x00,0xD0,0xFF,0xFF,0xFF,0xFF,0x0B,0x00,0xD0,0xFF,
0xFF,0xFF,0xFF,0x7F,0x00,0x40,0x8D,0x23,0xA2,0xFF,0xBF,0x00,0x00,0x00,0x00,0x20,
0xFF,0xDF,0x00,0x00,0x00,0x63,0x97,0xFF,0xEF,0x00,0x10,0xF9,0xFF,0xFF,0xFF,0xEF,
0x00,0xD1,0xFF,0xFF,0xFF,0xFF,0xEF,0x00,0xF8,0xFF,0x5D,0x21,0xFF,0xEF,0x00,0xFC,
0xFF,0x03,0x40,0xFF,0xEF,0x00,0xFD,0xFF,0x28,0xF6,0xFF,0xFF,0x00,0xFA,0xFF,0xFF,
0xFF,0xFF,0xFF,0x00,0xF3,0xFF,0xFF,0x9F,0xFC,0xFF,0x01,0x30,0xEB,0xCF,0x05,0xF7,
0xAD,0x00,
// Unicode: [0x0064, d]
0x00,0x00,0x00,0x00,0xE3,0xEF,0x05,0x00,0x00,0x00,0x00,0xF6,0xFF,0x09,0x00,0x00,
0x00,0x00,0xF6,0xFF,0x09,0x00,0x00,0x00,0x00,0xF6,0xFF,0x09,0x00,0x00,0x00,0x00,
0xF6,0xFF,0x09,0x00,0x00,0x00,0x00,0xF6,0xFF,0x09,0x00,0x80,0xFD,0xBE,0xF9,0xFF,
0x09,0x10,0xFD,0xFF,0xFF,0xFF,0xFF,0x09,0xA0,0xFF,0xFF,0xFF,0xFF,0xFF,0x09,0xF3,
0xFF,0x7F,0x32,0xFB,0xFF,0x09,0xF8,0xFF,0x0A,0x00,0xF6,0xFF,0x09,0xFA,0xFF,0x05,
0x00,0xF6,0xFF,0x09,0xFC,0xFF,0x03,0x00,0xF6,0xFF,0x09,0xFC,0xFF,0x03,0x00,0xF6,
0xFF,0x09,0xFA,0xFF,0x05,0x00,0xF6,0xFF,0x09,0xF8,0xFF,0x09,0x00,0xFA,0xFF,0x09,
0xF3,0xFF,0x7F,0x93,0xFF,0xFF,0x0A,0xC0,0xFF,0xFF,0xFF,0xFF,0xFF,0x0B,0x30,0xFF,
0xFF,0xFF,0xF8,0xFF,0x0D,0x00,0x92,0xFD,0x5C,0xC0,0xDF,0x07,
// Unicode: [0x0065, e]
0x00,0x50,0xDA,0xEF,0x6C,0x00,0x00,0x10,0xFC,0xFF,0xFF,0xFF,0x0B,0x00,0xB0,0xFF,
0xFF,0xFF,0xFF,0x7F,0x00,0xF3,0xFF,0x6F,0x52,0xFE,0xEF,0x00,0xF8,0xFF,0x09,0x00,
0xF8,0xFF,0x04,0xFB,0xFF,0x9B,0x99,0xFC,0xFF,0x06,0xFD,0xFF,0xFF,0xFF,0xFF,0xFF,
0x07,0xFC,0xFF,0xFF,0xFF,0xFF,0xBF,0x00,0xFA,0xFF,0x06,0x00,0x00,0x00,0x00,0xF8,
0xFF,0x0B,0x00,0x00,0x00,0x00,0xF3,0xFF,0x9F,0x13,0x83,0x4D,0x00,0xA0,0xFF,0xFF,
0xFF,0xFF,0xDF,0x00,0x00,0xFA,0xFF,0xFF,0xFF,0xDF,0x00,0x00,0x40,0xDA,0xFF,0xAC,
0x06,0x00,
// Unicode: [0x0069, i]
0xE3,0xEF,0x05,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xB2,0xBD,0x03,0x00,0x00,0x00,0x00,
0x00,0x00,0xE3,0xEF,0x05,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,
0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,
0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xF6,0xFF,0x09,0xE3,0xEF,0x05,
// Unicode: [0x006C, l]
0xD1,0xEF,0x07,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,
0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,
0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,
0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,0xF4,0xFF,0x0B,0x00,
0xF3,0xFF,0x4E,0x01,0xF0,0xFF,0xFF,0x0E,0x80,0xFF,0xFF,0x2F,0x00,0xD7,0xEF,0x0B,
// Unicode: [0x006D, m]
0xC4,0xEE,0x11,0xD9,0xEF,0x19,0x30,0xEB,0xCF,0x06,0x00,0xF9,0xFF,0xD8,0xFF,0xFF,
0xCF,0xF7,0xFF,0xFF,0x6F,0x00,0xF7,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xDF,
0x00,0xF6,0xFF,0xBF,0x64,0xFF,0xFF,0x9F,0x84,0xFF,0xFF,0x00,0xF5,0xFF,0x0D,0x00,
0xFB,0xFF,0x09,0x00,0xFF,0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,0x00,0xFE,
0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,0x00,0xFE,0xFF,0x01,0xF5,0xFF,0x0A,
0x00,0xF9,0xFF,0x06,0x00,0xFE,0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,0x00,
0xFE,0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,0x00,0xFE,0xFF,0x01,0xF5,0xFF,
0x0A,0x00,0xF9,0xFF,0x06,0x00,0xFE,0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,
0x00,0xFE,0xFF,0x01,0xF5,0xFF,0x0A,0x00,0xF9,0xFF,0x06,0x00,0xFE,0xFF,0x01,0xD2,
0xEF,0x06,0x00,0xE5,0xEF,0x03,0x00,0xF9,0xCF,0x00,
// Unicode: [0x006E, n]
0xC4,0xEE,0x11,0xD8,0xDF,0x09,0x00,0xF9,0xFF,0xD8,0xFF,0xFF,0xBF,0x00,0xF7,0xFF,
0xFF,0xFF,0xFF,0xFF,0x03,0xF6,0xFF,0xCF,0x54,0xFF,0xFF,0x05,0xF5,0xFF,0x0D,0x00,
0xF9,0xFF,0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,
0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xF5,
0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xF5,0xFF,0x0A,
0x00,0xF8,0xFF,0x07,0xF5,0xFF,0x0A,0x00,0xF8,0xFF,0x07,0xD2,0xEF,0x06,0x00,0xE5,
0xEF,0x03,
// Unicode: [0x006F, o]
0x00,0x50,0xEB,0xEF,0x8C,0x01,0x00,0x10,0xFC,0xFF,0xFF,0xFF,0x4F,0x00,0xB0,0xFF,
0xFF,0xFF,0xFF,0xFF,0x02,0xF3,0xFF,0x7F,0x42,0xFE,0xFF,0x09,0xF8,0xFF,0x0A,0x00,
0xF4,0xFF,0x0E,0xFA,0xFF,0x05,0x00,0xF0,0xFF,0x0F,0xFC,0xFF,0x03,0x00,0xD0,0xFF,
0x2F,0xFC,0xFF,0x03,0x00,0xD0,0xFF,0x2F,0xFA,0xFF,0x05,0x00,0xF0,0xFF,0x0F,0xF8,
0xFF,0x0A,0x00,0xF4,0xFF,0x0E,0xF3,0xFF,0x7F,0x42,0xFE,0xFF,0x09,0xB0,0xFF,0xFF,
0xFF,0xFF,0xFF,0x02,0x10,0xFC,0xFF,0xFF,0xFF,0x4F,0x00,0x00,0x50,0xEB,0xFF,0x8D,
0x01,0x00,
// Unicode: [0x0072, r]
0xC4,0xEE,0x51,0xFD,0x08,0xF9,0xFF,0xF9,0xFF,0x0E,0xF7,0xFF,0xFF,0xFF,0x0B,0xF6,
0xFF,0xDF,0x78,0x02,0xF5,0xFF,0x1D,0x00,0x00,0xF5,0xFF,0x0A,0x00,0x00,0xF5,0xFF,
0x0A,0x00,0x00,0xF5,0xFF,0x0A,0x00,0x00,0xF5,0xFF,0x0A,0x00,0x00,0xF5,0xFF,0x0A,
0x00,0x00,0xF5,0xFF,0x0A,0x00,0x00,0xF5,0xFF,0x0A,0x00,0x00,0xF5,0xFF,0x0A,0x00,
0x00,0xD2,0xEF,0x06,0x00,0x00,
// Unicode: [0x0074, t]
0x00,0x61,0x47,0x00,0x00,0x00,0xF8,0xFF,0x00,0x00,0x00,0xFB,0xFF,0x01,0x00,0x00,
0xFD,0xFF,0x01,0x00,0xE0,0xFF,0xFF,0xEF,0x00,0xF2,0xFF,0xFF,0xFF,0x03,0xF0,0xFF,
0xFF,0xFF,0x01,0x00,0xFE,0xFF,0x02,0x00,0x00,0xFE,0xFF,0x01,0x00,0x00,0xFE,0xFF,
0x01,0x00,0x00,0xFE,0xFF,0x01,0x00,0x00,0xFE,0xFF,0x01,0x00,0x00,0xFE,0xFF,0x01,
0x00,0x00,0xFE,0xFF,0x01,0x00,0x00,0xFD,0xFF,0x27,0x00,0x00,0xFA,0xFF,0xFF,0x04,
0x00,0xF2,0xFF,0xFF,0x08,0x00,0x30,0xEB,0xDF,0x03,
// Unicode: [0x0075, u]
0xE3,0xEF,0x05,0x00,0xE6,0xDF,0x02,0xF6,0xFF,0x09,0x00,0xFA,0xFF,0x05,0xF6,0xFF,
0x09,0x00,0xFA,0xFF,0x05,0xF6,0xFF,0x09,0x00,0xFA,0xFF,0x05,0xF6,0xFF,0x09,0x00,
0xFA,0xFF,0x05,0xF6,0xFF,0x09,0x00,0xFA,0xFF,0x05,0xF6,0xFF,0x09,0x00,0xFA,0xFF,
0x05,0xF6,0xFF,0x09,0x00,0xFA,0xFF,0x05,0xF6,0xFF,0x09,0x00,0xFA,0xFF,0x05,0xF6,
0xFF,0x0A,0x00,0xFD,0xFF,0x06,0xF5,0xFF,0x5F,0xB4,0xFF,0xFF,0x06,0xF2,0xFF,0xFF,
0xFF,0xFF,0xFF,0x07,0xB0,0xFF,0xFF,0xDF,0xF7,0xFF,0x09,0x00,0xD8,0xDF,0x18,0xE1,
0xCE,0x05,
// Unicode: [0x0077, w]
0xE5,0xEF,0x03,0x00,0xF6,0xDF,0x01,0x00,0xF9,0x5E,0xF5,0xFF,0x08,0x00,0xFC,0xFF,
0x05,0x00,0xFF,0x6F,0xF1,0xFF,0x0C,0x00,0xFF,0xFF,0x09,0x30,0xFF,0x2F,0xC0,0xFF,
0x1F,0x40,0xFF,0xFF,0x0D,0x80,0xFF,0x0E,0x80,0xFF,0x5F,0x80,0xFF,0xFF,0x1F,0xC0,
0xFF,0x09,0x30,0xFF,0x9F,0xC0,0xFF,0xFF,0x4F,0xF0,0xFF,0x05,0x00,0xFF,0xDF,0xF0,
0xFF,0xFC,0x8F,0xF5,0xFF,0x01,0x00,0xFB,0xFF,0xF5,0xBF,0xF8,0xCF,0xF9,0xDF,0x00,
0x00,0xF6,0xFF,0xFD,0x7F,0xF4,0xFF,0xFE,0x9F,0x00,0x00,0xF2,0xFF,0xFF,0x3F,0xF0,
0xFF,0xFF,0x5F,0x00,0x00,0xE0,0xFF,0xFF,0x0F,0xC0,0xFF,0xFF,0x1F,0x00,0x00,0x90,
0xFF,0xFF,0x0B,0x70,0xFF,0xFF,0x0D,0x00,0x00,0x50,0xFF,0xFF,0x07,0x30,0xFF,0xFF,
0x08,0x00,0x00,0x00,0xFD,0xEF,0x02,0x00,0xFC,0xEF,0x03,0x00,
// Unicode: [0x0078, x]
0xF6,0xFF,0x08,0x00,0xE3,0xFF,0x0A,0xF2,0xFF,0x3F,0x00,0xFD,0xFF,0x05,0x70,0xFF,
0xDF,0x80,0xFF,0xAF,0x00,0x00,0xFC,0xFF,0xFA,0xFF,0x1E,0x00,0x00,0xF2,0xFF,0xFF,
0xFF,0x04,0x00,0x00,0x60,0xFF,0xFF,0x9F,0x00,0x00,0x00,0x00,0xFC,0xFF,0x0E,0x00,
0x00,0x00,0x00,0xFD,0xFF,0x2F,0x00,0x00,0x00,0x90,0xFF,0xFF,0xCF,0x00,0x00,0x00,
0xF4,0xFF,0xFF,0xFF,0x06,0x00,0x10,0xFE,0xFF,0xF6,0xFF,0x2F,0x00,0xA0,0xFF,0x9F,
0x80,0xFF,0xCF,0x00,0xF5,0xFF,0x0E,0x00,0xFD,0xFF,0x06,0xFA,0xEF,0x04,0x00,0xE3,
0xFF,0x0B,
// Unicode: [0x0079, y]
0xF8,0xEF,0x03,0x00,0xB0,0xFF,0x0A,0xF7,0xFF,0x09,0x00,0xF3,0xFF,0x0A,0xF1,0xFF,
0x0E,0x00,0xF8,0xFF,0x04,0xC0,0xFF,0x4F,0x00,0xFE,0xEF,0x00,0x60,0xFF,0x9F,0x30,
0xFF,0x9F,0x00,0x10,0xFF,0xEF,0x80,0xFF,0x3F,0x00,0x00,0xFB,0xFF,0xC2,0xFF,0x0D,
0x00,0x00,0xF5,0xFF,0xF7,0xFF,0x08,0x00,0x00,0xF0,0xFF,0xFE,0xFF,0x02,0x00,0x00,
0xA0,0xFF,0xFF,0xCF,0x00,0x00,0x00,0x40,0xFF,0xFF,0x6F,0x00,0x00,0x00,0x00,0xFE,
0xFF,0x1F,0x00,0x00,0x00,0x00,0xF9,0xFF,0x0B,0x00,0x00,0x00,0x00,0xF4,0xFF,0x05,
0x00,0x00,0x00,0x00,0xF8,0xFF,0x00,0x00,0x00,0x00,0x00,0xFE,0xAF,0x00,0x00,0x00,
0x00,0x40,0xFF,0x4F,0x00,0x00,0x00,0x00,0xA0,0xFF,0x0E,0x00,0x00,0x00,0x00,0xC0,
0xFF,0x07,0x00,0x00,0x00,
// Unicode: [0x007A, z]
0x90,0xFF,0xFF,0xFF,0xFF,0xDF,0x00,0xD0,0xFF,0xFF,0xFF,0xFF,0xFF,0x03,0xA0,0xFF,
0xFF,0xFF,0xFF,0xFF,0x02,0x00,0x11,0x11,0xF6,0xFF,0x7F,0x00,0x00,0x00,0x10,0xFE,
0xFF,0x0B,0x00,0x00,0x00,0xC0,0xFF,0xEF,0x01,0x00,0x00,0x00,0xF7,0xFF,0x4F,0x00,
0x00,0x00,0x30,0xFF,0xFF,0x09,0x00,0x00,0x00,0xE1,0xFF,0xDF,0x00,0x00,0x00,0x00,
0xFA,0xFF,0x2F,0x00,0x00,0x00,0x60,0xFF,0xFF,0x17,0x11,0x01,0x00,0xF2,0xFF,0xFF,
0xFF,0xFF,0xFF,0x03,0xF2,0xFF,0xFF,0xFF,0xFF,0xFF,0x06,0xD0,0xFF,0xFF,0xFF,0xFF,
0xFF,0x03
};
| 68.675676 | 92 | 0.782088 | ramkumarkoppu |
5b67aa36666531f43d801b94529ba4a600971cd2 | 11,136 | cpp | C++ | DriverOptions.cpp | ARM-software/android-nn-driver | 249c1253c6019a380ee2e283b7d3f412d5ecbfd1 | [
"MIT"
] | 130 | 2018-03-09T20:44:20.000Z | 2022-03-06T16:34:51.000Z | DriverOptions.cpp | ARM-software/android-nn-driver | 249c1253c6019a380ee2e283b7d3f412d5ecbfd1 | [
"MIT"
] | 18 | 2018-05-02T09:43:59.000Z | 2021-11-08T10:41:55.000Z | DriverOptions.cpp | ARM-software/android-nn-driver | 249c1253c6019a380ee2e283b7d3f412d5ecbfd1 | [
"MIT"
] | 53 | 2018-03-12T18:25:48.000Z | 2022-02-01T13:52:52.000Z | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#define LOG_TAG "ArmnnDriver"
#include "DriverOptions.hpp"
#include "Utils.hpp"
#include <armnn/Version.hpp>
#include <log/log.h>
#include "SystemPropertiesUtils.hpp"
#include <OperationsUtils.h>
#include <cxxopts/cxxopts.hpp>
#include <algorithm>
#include <cassert>
#include <functional>
#include <string>
#include <sstream>
using namespace android;
using namespace std;
namespace armnn_driver
{
DriverOptions::DriverOptions(armnn::Compute computeDevice, bool fp16Enabled)
: m_Backends({computeDevice})
, m_VerboseLogging(false)
, m_ClTunedParametersMode(armnn::IGpuAccTunedParameters::Mode::UseTunedParameters)
, m_ClTuningLevel(armnn::IGpuAccTunedParameters::TuningLevel::Rapid)
, m_EnableGpuProfiling(false)
, m_fp16Enabled(fp16Enabled)
, m_FastMathEnabled(false)
, m_ShouldExit(false)
, m_SaveCachedNetwork(false)
, m_NumberOfThreads(0)
, m_EnableAsyncModelExecution(false)
, m_ArmnnNumberOfThreads(1)
{
}
DriverOptions::DriverOptions(const std::vector<armnn::BackendId>& backends, bool fp16Enabled)
: m_Backends(backends)
, m_VerboseLogging(false)
, m_ClTunedParametersMode(armnn::IGpuAccTunedParameters::Mode::UseTunedParameters)
, m_ClTuningLevel(armnn::IGpuAccTunedParameters::TuningLevel::Rapid)
, m_EnableGpuProfiling(false)
, m_fp16Enabled(fp16Enabled)
, m_FastMathEnabled(false)
, m_ShouldExit(false)
, m_SaveCachedNetwork(false)
, m_NumberOfThreads(0)
, m_EnableAsyncModelExecution(false)
, m_ArmnnNumberOfThreads(1)
{
}
DriverOptions::DriverOptions(int argc, char** argv)
: m_VerboseLogging(false)
, m_ClTunedParametersMode(armnn::IGpuAccTunedParameters::Mode::UseTunedParameters)
, m_ClTuningLevel(armnn::IGpuAccTunedParameters::TuningLevel::Rapid)
, m_EnableGpuProfiling(false)
, m_fp16Enabled(false)
, m_FastMathEnabled(false)
, m_ShouldExit(false)
, m_SaveCachedNetwork(false)
, m_NumberOfThreads(0)
, m_EnableAsyncModelExecution(false)
, m_ArmnnNumberOfThreads(1)
{
std::string unsupportedOperationsAsString;
std::string clTunedParametersModeAsString;
std::string clTuningLevelAsString;
std::vector<std::string> backends;
bool showHelp;
bool showVersion;
cxxopts::Options optionsDesc(argv[0], "ArmNN Android NN driver for the Android Neural Networks API. The Android NN "
"driver will convert Android NNAPI requests and delegate them to available "
"ArmNN backends.");
try
{
optionsDesc.add_options()
("a,enable-fast-math", "Enables fast_math options in backends that support it. Using the fast_math flag can "
"lead to performance improvements but may result in reduced or different precision.",
cxxopts::value<bool>(m_FastMathEnabled)->default_value("false"))
("c,compute",
"Comma separated list of backends to run layers on. Examples of possible values are: CpuRef, CpuAcc, GpuAcc",
cxxopts::value<std::vector<std::string>>(backends))
("d,request-inputs-and-outputs-dump-dir",
"If non-empty, the directory where request inputs and outputs should be dumped",
cxxopts::value<std::string>(m_RequestInputsAndOutputsDumpDir)->default_value(""))
("f,fp16-enabled", "Enables support for relaxed computation from Float32 to Float16",
cxxopts::value<bool>(m_fp16Enabled)->default_value("false"))
("h,help", "Show this help",
cxxopts::value<bool>(showHelp)->default_value("false"))
("m,cl-tuned-parameters-mode",
"If 'UseTunedParameters' (the default), will read CL tuned parameters from the file specified by "
"--cl-tuned-parameters-file. "
"If 'UpdateTunedParameters', will also find the optimum parameters when preparing new networks and update "
"the file accordingly.",
cxxopts::value<std::string>(clTunedParametersModeAsString)->default_value("UseTunedParameters"))
("g,mlgo-cl-tuned-parameters-file",
"If non-empty, the given file will be used to load/save MLGO CL tuned parameters. ",
cxxopts::value<std::string>(m_ClMLGOTunedParametersFile)->default_value(""))
("n,service-name",
"If non-empty, the driver service name to be registered",
cxxopts::value<std::string>(m_ServiceName)->default_value("armnn"))
("o,cl-tuning-level",
"exhaustive: all lws values are tested "
"normal: reduced number of lws values but enough to still have the performance really close to the "
"exhaustive approach "
"rapid: only 3 lws values should be tested for each kernel ",
cxxopts::value<std::string>(clTuningLevelAsString)->default_value("rapid"))
("p,gpu-profiling", "Turns GPU profiling on",
cxxopts::value<bool>(m_EnableGpuProfiling)->default_value("false"))
("q,cached-network-file", "If non-empty, the given file will be used to load/save cached network. "
"If save-cached-network option is given will save the cached network to given file."
"If save-cached-network option is not given will load the cached network from given "
"file.",
cxxopts::value<std::string>(m_CachedNetworkFilePath)->default_value(""))
("s,save-cached-network", "Enables saving the cached network to the file given with cached-network-file option."
" See also --cached-network-file",
cxxopts::value<bool>(m_SaveCachedNetwork)->default_value("false"))
("number-of-threads",
"Assign the number of threads used by the CpuAcc backend. "
"Input value must be between 1 and 64. "
"Default is set to 0 (Backend will decide number of threads to use).",
cxxopts::value<unsigned int>(m_NumberOfThreads)->default_value("0"))
("t,cl-tuned-parameters-file",
"If non-empty, the given file will be used to load/save CL tuned parameters. "
"See also --cl-tuned-parameters-mode",
cxxopts::value<std::string>(m_ClTunedParametersFile)->default_value(""))
("u,unsupported-operations",
"If non-empty, a comma-separated list of operation indices which the driver will forcibly "
"consider unsupported",
cxxopts::value<std::string>(unsupportedOperationsAsString)->default_value(""))
("v,verbose-logging", "Turns verbose logging on",
cxxopts::value<bool>(m_VerboseLogging)->default_value("false"))
("V,version", "Show version information",
cxxopts::value<bool>(showVersion)->default_value("false"))
("A,asyncModelExecution", "Enable AsynModel Execution",
cxxopts::value<bool>(m_EnableAsyncModelExecution)->default_value("false"))
("T,armnn-threads",
"Assign the number of threads used by ArmNN. "
"Input value must be at least 1. "
"Default is set to 1.",
cxxopts::value<unsigned int>(m_ArmnnNumberOfThreads)->default_value("1"));
}
catch (const std::exception& e)
{
ALOGE("An error occurred attempting to construct options: %s", e.what());
std::cout << "An error occurred attempting to construct options: %s" << std::endl;
m_ExitCode = EXIT_FAILURE;
return;
}
try
{
cxxopts::ParseResult result = optionsDesc.parse(argc, argv);
}
catch (const cxxopts::OptionException& e)
{
ALOGW("An exception occurred attempting to parse program options: %s", e.what());
std::cout << optionsDesc.help() << std::endl
<< "An exception occurred while parsing program options: " << std::endl
<< e.what() << std::endl;
m_ShouldExit = true;
m_ExitCode = EXIT_FAILURE;
return;
}
if (showHelp)
{
ALOGW("Showing help and exiting");
std::cout << optionsDesc.help() << std::endl;
m_ShouldExit = true;
m_ExitCode = EXIT_SUCCESS;
return;
}
if (showVersion)
{
ALOGW("Showing version and exiting");
std::cout << "ArmNN Android NN driver for the Android Neural Networks API.\n"
"ArmNN v" << ARMNN_VERSION << std::endl;
m_ShouldExit = true;
m_ExitCode = EXIT_SUCCESS;
return;
}
// Convert the string backend names into backendId's.
m_Backends.reserve(backends.size());
for (auto&& backend : backends)
{
m_Backends.emplace_back(backend);
}
// If no backends have been specified then the default value is GpuAcc.
if (backends.empty())
{
ALOGE("No backends have been specified:");
std::cout << optionsDesc.help() << std::endl
<< "Unable to start:" << std::endl
<< "No backends have been specified" << std::endl;
m_ShouldExit = true;
m_ExitCode = EXIT_FAILURE;
return;
}
if (!unsupportedOperationsAsString.empty())
{
std::istringstream argStream(unsupportedOperationsAsString);
std::string s;
while (!argStream.eof())
{
std::getline(argStream, s, ',');
try
{
unsigned int operationIdx = std::stoi(s);
m_ForcedUnsupportedOperations.insert(operationIdx);
}
catch (const std::invalid_argument&)
{
ALOGW("Ignoring invalid integer argument in -u/--unsupported-operations value: %s", s.c_str());
}
}
}
if (!m_ClTunedParametersFile.empty())
{
// The mode is only relevant if the file path has been provided
if (clTunedParametersModeAsString == "UseTunedParameters")
{
m_ClTunedParametersMode = armnn::IGpuAccTunedParameters::Mode::UseTunedParameters;
}
else if (clTunedParametersModeAsString == "UpdateTunedParameters")
{
m_ClTunedParametersMode = armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters;
}
else
{
ALOGW("Requested unknown cl-tuned-parameters-mode '%s'. Defaulting to UseTunedParameters",
clTunedParametersModeAsString.c_str());
}
if (clTuningLevelAsString == "exhaustive")
{
m_ClTuningLevel = armnn::IGpuAccTunedParameters::TuningLevel::Exhaustive;
}
else if (clTuningLevelAsString == "normal")
{
m_ClTuningLevel = armnn::IGpuAccTunedParameters::TuningLevel::Normal;
}
else if (clTuningLevelAsString == "rapid")
{
m_ClTuningLevel = armnn::IGpuAccTunedParameters::TuningLevel::Rapid;
}
else
{
ALOGW("Requested unknown cl-tuner-mode '%s'. Defaulting to rapid",
clTuningLevelAsString.c_str());
}
}
}
} // namespace armnn_driver
| 38.268041 | 120 | 0.639368 | ARM-software |
5b6eb1a8f650508647ebb1d09defc4bcc8314938 | 451 | cpp | C++ | src/robotics/genetico.cpp | pcamarillor/Exploratory3D | 10705d201376b98bdf8f19fca398a3bf341807c9 | [
"MIT"
] | null | null | null | src/robotics/genetico.cpp | pcamarillor/Exploratory3D | 10705d201376b98bdf8f19fca398a3bf341807c9 | [
"MIT"
] | null | null | null | src/robotics/genetico.cpp | pcamarillor/Exploratory3D | 10705d201376b98bdf8f19fca398a3bf341807c9 | [
"MIT"
] | null | null | null | #include "genetico.h"
genetico::genetico()
{
this->numGeneraciones = 100;
this->tamPoblacion = 20;
this->pCruza = 0.8;
this->pMutacion = 0.2;
}
genetico::genetico(int _nGeneraciones, int _tPoblacion, float _pCruza, float _pMutacion)
{
this->numGeneraciones = _nGeneraciones;
this->tamPoblacion = _tPoblacion;
this->pCruza = _pCruza;
this->pMutacion = _pMutacion;
}
genetico::~genetico()
{
}
| 18.791667 | 89 | 0.640798 | pcamarillor |
5b71eb28bb592ba6fa72287450ece721c3d1a2f1 | 943 | cpp | C++ | Easy/345 - Reverse Vowels of a String.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 11 | 2015-08-06T15:43:48.000Z | 2022-02-16T01:30:24.000Z | Easy/345 - Reverse Vowels of a String.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 1 | 2015-08-17T13:33:55.000Z | 2015-08-27T03:43:47.000Z | Easy/345 - Reverse Vowels of a String.cpp | WangZixuan/Leetcode | 4593e8b48c4ce810567473a825735ffde3f7a0f0 | [
"WTFPL"
] | 2 | 2021-09-30T14:39:05.000Z | 2021-10-02T11:02:20.000Z | /*
Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
@author Zixuan
@date 2016/6/7
*/
#include <set>
using namespace std;
class Solution
{
public:
string reverseVowels(string s)
{
set<char> vowels{ 'a','e','i','o','u','A','E','I','O','U' };//Do not forget upper class.
auto first = 0;
auto last = static_cast<int>(s.length()) - 1;//Without static cast, last will be unsigned int,
//which means that if s.length=0, last would not be -1.
while (first < last)
{
while (vowels.end() == vowels.find(s[first]))
++first;
while (vowels.end() == vowels.find(s[last]))
--last;
if (first < last)
{
//Swap.
auto temp = s[first];
s[first] = s[last];
s[last] = temp;
++first;
--last;
}
}
return s;
}
};
| 17.792453 | 96 | 0.592789 | WangZixuan |
ac8ce1d1670b820a80857ab9a38727074296607d | 11,760 | hpp | C++ | openjdk11/src/hotspot/share/gc/g1/ptrQueue.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | openjdk11/src/hotspot/share/gc/g1/ptrQueue.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | openjdk11/src/hotspot/share/gc/g1/ptrQueue.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_G1_PTRQUEUE_HPP
#define SHARE_VM_GC_G1_PTRQUEUE_HPP
#include "utilities/align.hpp"
#include "utilities/sizes.hpp"
// There are various techniques that require threads to be able to log
// addresses. For example, a generational write barrier might log
// the addresses of modified old-generation objects. This type supports
// this operation.
class BufferNode;
class PtrQueueSet;
class PtrQueue {
friend class VMStructs;
// Noncopyable - not defined.
PtrQueue(const PtrQueue&);
PtrQueue& operator=(const PtrQueue&);
// The ptr queue set to which this queue belongs.
PtrQueueSet* const _qset;
// Whether updates should be logged.
bool _active;
// If true, the queue is permanent, and doesn't need to deallocate
// its buffer in the destructor (since that obtains a lock which may not
// be legally locked by then.
const bool _permanent;
// The (byte) index at which an object was last enqueued. Starts at
// capacity_in_bytes (indicating an empty buffer) and goes towards zero.
// Value is always pointer-size aligned.
size_t _index;
// Size of the current buffer, in bytes.
// Value is always pointer-size aligned.
size_t _capacity_in_bytes;
static const size_t _element_size = sizeof(void*);
// Get the capacity, in bytes. The capacity must have been set.
size_t capacity_in_bytes() const {
assert(_capacity_in_bytes > 0, "capacity not set");
return _capacity_in_bytes;
}
void set_capacity(size_t entries) {
size_t byte_capacity = index_to_byte_index(entries);
assert(_capacity_in_bytes == 0 || _capacity_in_bytes == byte_capacity,
"changing capacity " SIZE_FORMAT " -> " SIZE_FORMAT,
_capacity_in_bytes, byte_capacity);
_capacity_in_bytes = byte_capacity;
}
static size_t byte_index_to_index(size_t ind) {
assert(is_aligned(ind, _element_size), "precondition");
return ind / _element_size;
}
static size_t index_to_byte_index(size_t ind) {
return ind * _element_size;
}
protected:
// The buffer.
void** _buf;
size_t index() const {
return byte_index_to_index(_index);
}
void set_index(size_t new_index) {
size_t byte_index = index_to_byte_index(new_index);
assert(byte_index <= capacity_in_bytes(), "precondition");
_index = byte_index;
}
size_t capacity() const {
return byte_index_to_index(capacity_in_bytes());
}
// If there is a lock associated with this buffer, this is that lock.
Mutex* _lock;
PtrQueueSet* qset() { return _qset; }
bool is_permanent() const { return _permanent; }
// Process queue entries and release resources.
void flush_impl();
// Initialize this queue to contain a null buffer, and be part of the
// given PtrQueueSet.
PtrQueue(PtrQueueSet* qset, bool permanent = false, bool active = false);
// Requires queue flushed or permanent.
~PtrQueue();
public:
// Associate a lock with a ptr queue.
void set_lock(Mutex* lock) { _lock = lock; }
// Forcibly set empty.
void reset() {
if (_buf != NULL) {
_index = capacity_in_bytes();
}
}
void enqueue(volatile void* ptr) {
enqueue((void*)(ptr));
}
// Enqueues the given "obj".
void enqueue(void* ptr) {
if (!_active) return;
else enqueue_known_active(ptr);
}
// This method is called when we're doing the zero index handling
// and gives a chance to the queues to do any pre-enqueueing
// processing they might want to do on the buffer. It should return
// true if the buffer should be enqueued, or false if enough
// entries were cleared from it so that it can be re-used. It should
// not return false if the buffer is still full (otherwise we can
// get into an infinite loop).
virtual bool should_enqueue_buffer() { return true; }
void handle_zero_index();
void locking_enqueue_completed_buffer(BufferNode* node);
void enqueue_known_active(void* ptr);
// Return the size of the in-use region.
size_t size() const {
size_t result = 0;
if (_buf != NULL) {
assert(_index <= capacity_in_bytes(), "Invariant");
result = byte_index_to_index(capacity_in_bytes() - _index);
}
return result;
}
bool is_empty() const {
return _buf == NULL || capacity_in_bytes() == _index;
}
// Set the "active" property of the queue to "b". An enqueue to an
// inactive thread is a no-op. Setting a queue to inactive resets its
// log to the empty state.
void set_active(bool b) {
_active = b;
if (!b && _buf != NULL) {
reset();
} else if (b && _buf != NULL) {
assert(index() == capacity(),
"invariant: queues are empty when activated.");
}
}
bool is_active() const { return _active; }
// To support compiler.
protected:
template<typename Derived>
static ByteSize byte_offset_of_index() {
return byte_offset_of(Derived, _index);
}
static ByteSize byte_width_of_index() { return in_ByteSize(sizeof(size_t)); }
template<typename Derived>
static ByteSize byte_offset_of_buf() {
return byte_offset_of(Derived, _buf);
}
static ByteSize byte_width_of_buf() { return in_ByteSize(_element_size); }
template<typename Derived>
static ByteSize byte_offset_of_active() {
return byte_offset_of(Derived, _active);
}
static ByteSize byte_width_of_active() { return in_ByteSize(sizeof(bool)); }
};
class BufferNode {
size_t _index;
BufferNode* _next;
void* _buffer[1]; // Pseudo flexible array member.
BufferNode() : _index(0), _next(NULL) { }
~BufferNode() { }
static size_t buffer_offset() {
return offset_of(BufferNode, _buffer);
}
public:
BufferNode* next() const { return _next; }
void set_next(BufferNode* n) { _next = n; }
size_t index() const { return _index; }
void set_index(size_t i) { _index = i; }
// Allocate a new BufferNode with the "buffer" having size elements.
static BufferNode* allocate(size_t size);
// Free a BufferNode.
static void deallocate(BufferNode* node);
// Return the BufferNode containing the buffer, after setting its index.
static BufferNode* make_node_from_buffer(void** buffer, size_t index) {
BufferNode* node =
reinterpret_cast<BufferNode*>(
reinterpret_cast<char*>(buffer) - buffer_offset());
node->set_index(index);
return node;
}
// Return the buffer for node.
static void** make_buffer_from_node(BufferNode *node) {
// &_buffer[0] might lead to index out of bounds warnings.
return reinterpret_cast<void**>(
reinterpret_cast<char*>(node) + buffer_offset());
}
};
// A PtrQueueSet represents resources common to a set of pointer queues.
// In particular, the individual queues allocate buffers from this shared
// set, and return completed buffers to the set.
// All these variables are are protected by the TLOQ_CBL_mon. XXX ???
class PtrQueueSet {
private:
// The size of all buffers in the set.
size_t _buffer_size;
protected:
Monitor* _cbl_mon; // Protects the fields below.
BufferNode* _completed_buffers_head;
BufferNode* _completed_buffers_tail;
size_t _n_completed_buffers;
int _process_completed_threshold;
volatile bool _process_completed;
// This (and the interpretation of the first element as a "next"
// pointer) are protected by the TLOQ_FL_lock.
Mutex* _fl_lock;
BufferNode* _buf_free_list;
size_t _buf_free_list_sz;
// Queue set can share a freelist. The _fl_owner variable
// specifies the owner. It is set to "this" by default.
PtrQueueSet* _fl_owner;
bool _all_active;
// If true, notify_all on _cbl_mon when the threshold is reached.
bool _notify_when_complete;
// Maximum number of elements allowed on completed queue: after that,
// enqueuer does the work itself. Zero indicates no maximum.
int _max_completed_queue;
size_t _completed_queue_padding;
size_t completed_buffers_list_length();
void assert_completed_buffer_list_len_correct_locked();
void assert_completed_buffer_list_len_correct();
protected:
// A mutator thread does the the work of processing a buffer.
// Returns "true" iff the work is complete (and the buffer may be
// deallocated).
virtual bool mut_process_buffer(BufferNode* node) {
ShouldNotReachHere();
return false;
}
// Create an empty ptr queue set.
PtrQueueSet(bool notify_when_complete = false);
~PtrQueueSet();
// Because of init-order concerns, we can't pass these as constructor
// arguments.
void initialize(Monitor* cbl_mon,
Mutex* fl_lock,
int process_completed_threshold,
int max_completed_queue,
PtrQueueSet *fl_owner = NULL);
public:
// Return the buffer for a BufferNode of size buffer_size().
void** allocate_buffer();
// Return an empty buffer to the free list. The node is required
// to have been allocated with a size of buffer_size().
void deallocate_buffer(BufferNode* node);
// Declares that "buf" is a complete buffer.
void enqueue_complete_buffer(BufferNode* node);
// To be invoked by the mutator.
bool process_or_enqueue_complete_buffer(BufferNode* node);
bool completed_buffers_exist_dirty() {
return _n_completed_buffers > 0;
}
bool process_completed_buffers() { return _process_completed; }
void set_process_completed(bool x) { _process_completed = x; }
bool is_active() { return _all_active; }
// Set the buffer size. Should be called before any "enqueue" operation
// can be called. And should only be called once.
void set_buffer_size(size_t sz);
// Get the buffer size. Must have been set.
size_t buffer_size() const {
assert(_buffer_size > 0, "buffer size not set");
return _buffer_size;
}
// Get/Set the number of completed buffers that triggers log processing.
void set_process_completed_threshold(int sz) { _process_completed_threshold = sz; }
int process_completed_threshold() const { return _process_completed_threshold; }
// Must only be called at a safe point. Indicates that the buffer free
// list size may be reduced, if that is deemed desirable.
void reduce_free_list();
size_t completed_buffers_num() { return _n_completed_buffers; }
void merge_bufferlists(PtrQueueSet* src);
void set_max_completed_queue(int m) { _max_completed_queue = m; }
int max_completed_queue() { return _max_completed_queue; }
void set_completed_queue_padding(size_t padding) { _completed_queue_padding = padding; }
size_t completed_queue_padding() { return _completed_queue_padding; }
// Notify the consumer if the number of buffers crossed the threshold
void notify_if_necessary();
};
#endif // SHARE_VM_GC_G1_PTRQUEUE_HPP
| 31.52815 | 90 | 0.714966 | iootclab |
ac8e0fdaba7552f4373146f3be78ecf133f34d4b | 10,011 | cc | C++ | build/X86_MESI_Two_Level/python/m5/internal/param_TaggedPrefetcher.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | build/X86_MESI_Two_Level/python/m5/internal/param_TaggedPrefetcher.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/python/m5/internal/param_TaggedPrefetcher.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_param_TaggedPrefetcher[] = {
120,156,197,88,123,111,219,200,17,159,165,94,150,108,217,114,
252,202,195,62,51,137,221,168,143,216,109,15,110,175,189,52,
104,146,166,197,1,141,47,165,3,36,81,11,16,52,185,146,
105,75,164,74,174,226,40,144,255,104,29,180,247,97,250,95,
63,89,63,65,59,51,75,210,180,108,1,1,122,167,147,173,
213,114,57,251,152,249,253,102,118,118,93,72,62,183,240,251,
91,19,32,254,143,0,240,240,95,192,9,64,87,64,203,0,
33,13,240,150,224,184,4,225,45,16,94,9,62,2,180,10,
32,11,112,142,149,34,252,185,0,193,231,90,106,57,147,170,
92,39,85,199,23,56,246,12,156,20,185,201,128,97,13,100,
9,90,101,120,29,44,65,81,86,224,184,6,97,5,4,126,
2,156,249,205,176,1,73,143,25,104,85,81,106,19,165,106,
44,181,196,82,201,219,42,189,229,30,94,21,188,26,124,196,
149,207,130,55,203,171,152,3,111,142,43,117,240,234,92,153,
7,111,158,43,11,233,240,13,104,45,166,245,27,185,250,82,
174,190,156,171,175,228,234,171,185,250,90,174,126,51,87,191,
149,171,223,206,213,239,228,234,235,185,250,6,215,23,64,46,
130,255,25,248,155,224,155,208,22,224,53,104,217,104,209,183,
173,187,32,139,224,223,131,214,61,144,248,127,23,206,5,154,
119,49,215,227,62,247,184,145,245,216,226,30,219,208,218,6,
137,255,91,186,199,12,28,52,87,16,126,255,191,248,105,34,
252,160,230,176,120,39,163,216,15,3,219,15,218,161,111,208,
251,10,21,68,22,151,138,2,126,203,248,125,70,172,137,128,
41,131,107,71,214,156,225,8,2,176,143,103,208,12,94,1,
110,157,9,122,240,11,48,194,74,17,218,252,194,47,38,18,
103,200,131,69,24,225,232,37,24,113,203,193,235,96,3,138,
170,204,64,47,50,208,250,53,118,166,215,8,51,224,178,75,
56,237,62,175,91,209,186,119,120,117,106,13,11,187,239,68,
78,207,126,229,116,58,210,123,25,201,182,84,238,145,140,154,
164,131,170,146,34,189,126,24,169,174,127,168,102,72,220,14,
156,158,180,109,85,195,135,8,251,42,95,161,242,170,136,143,
199,161,31,40,210,180,27,171,200,239,171,122,214,219,238,133,
222,160,43,213,44,182,124,197,45,207,163,40,140,154,100,26,
139,10,69,69,255,164,163,104,161,61,154,162,73,43,228,34,
110,97,177,123,20,246,36,22,65,103,56,216,237,200,222,222,
195,246,112,247,112,224,119,189,221,55,95,252,194,126,241,252,
224,43,251,213,105,104,255,81,190,147,221,221,254,80,161,232,
110,111,111,23,87,36,163,192,193,166,107,213,220,65,201,27,
52,199,169,223,177,147,181,30,201,110,95,70,164,122,60,79,
243,139,57,177,36,62,19,5,177,40,230,133,95,78,97,37,
3,213,83,88,255,149,192,106,36,193,0,145,21,9,204,6,
156,113,133,176,107,18,172,132,102,129,64,68,101,17,162,142,
128,115,3,254,82,32,129,51,44,139,232,187,102,6,233,178,
246,93,61,84,5,206,16,247,18,161,250,97,157,135,154,225,
161,12,24,97,137,128,23,225,12,3,4,138,98,19,150,199,
85,8,231,65,224,131,95,37,98,139,0,105,252,102,84,70,
66,20,51,66,104,34,147,54,158,31,145,229,45,226,112,179,
150,182,134,241,78,223,81,71,86,61,133,9,205,196,112,239,
135,129,70,180,237,7,94,138,176,230,72,219,239,34,71,44,
178,33,143,198,98,221,208,201,196,8,102,183,27,198,146,121,
198,99,91,11,36,72,210,237,62,15,67,179,210,122,184,179,
39,99,151,56,133,92,211,35,210,10,104,180,169,241,196,34,
95,95,166,121,110,51,43,26,200,139,50,178,162,137,172,208,
181,117,163,46,22,196,190,79,6,117,75,137,215,23,83,138,
252,27,52,44,2,142,13,118,213,17,7,9,148,70,240,216,
85,71,28,8,232,237,79,64,40,35,105,199,88,128,24,83,
235,13,236,195,196,65,6,161,236,35,242,108,134,148,152,80,
2,164,166,134,29,233,164,121,194,224,151,168,7,13,101,208,
20,69,232,175,225,224,51,196,136,17,36,212,57,47,32,53,
112,69,232,212,24,54,176,121,21,231,253,59,115,46,9,29,
204,4,117,228,199,225,169,246,117,170,115,244,59,64,207,121,
57,252,250,240,88,186,42,222,196,134,183,225,192,116,157,32,
8,149,233,120,158,233,40,140,5,135,3,37,99,83,133,230,
118,220,36,52,173,219,41,153,178,241,134,125,105,113,69,51,
200,243,93,133,81,102,137,31,216,59,99,169,144,11,71,161,
23,99,59,117,237,72,101,53,168,7,153,57,228,5,48,85,
108,18,165,105,81,142,28,248,73,186,2,29,115,202,41,123,
98,217,109,115,24,115,187,78,28,219,180,2,110,103,206,145,
214,239,156,238,64,242,232,49,142,135,11,162,170,94,195,244,
162,211,77,210,40,53,0,107,21,132,129,55,196,69,250,238,
231,52,255,77,102,99,29,163,83,93,172,226,183,42,86,68,
5,57,89,17,107,134,91,76,24,152,237,63,171,164,61,48,
244,34,65,31,25,121,142,49,165,105,112,72,96,197,136,193,
214,143,168,70,157,173,45,42,182,169,248,1,21,15,82,221,
167,98,128,250,184,1,158,209,164,6,107,237,22,18,253,50,
47,179,47,121,217,124,206,203,206,201,91,70,188,221,250,133,
156,167,20,200,6,225,108,234,91,236,137,8,63,122,34,9,
179,79,225,46,156,247,8,154,116,223,162,68,48,190,139,197,
131,237,248,129,169,249,103,30,57,177,25,132,23,164,55,233,
165,142,113,68,121,107,157,204,159,35,117,39,71,106,203,36,
9,98,180,117,159,138,226,36,251,255,240,123,178,127,71,219,
255,15,52,233,92,194,186,121,102,219,172,112,137,50,4,74,
37,69,226,0,43,195,53,66,34,15,193,26,110,134,175,131,
117,220,223,24,6,218,226,234,122,139,227,125,82,39,166,105,
144,243,75,105,165,76,96,180,11,176,154,236,92,49,109,45,
253,40,124,63,52,195,182,169,32,93,210,163,237,120,103,59,
254,18,227,140,249,248,194,236,73,76,137,100,159,98,130,142,
17,100,28,229,7,248,76,67,61,127,239,74,222,92,248,201,
182,117,72,208,89,142,157,108,90,136,16,67,98,164,144,112,
80,196,84,135,98,225,244,240,168,101,120,144,62,47,105,198,
26,131,81,16,107,24,4,114,80,208,183,64,80,16,225,254,
9,156,227,10,248,7,144,161,209,156,137,199,179,15,165,126,
180,68,226,148,222,140,196,181,59,149,145,248,135,145,68,16,
116,160,126,157,55,160,100,231,194,124,229,155,92,120,201,118,
150,66,146,243,228,253,168,152,249,17,163,244,73,187,71,241,
178,43,17,2,232,115,36,198,78,163,51,202,173,203,161,138,
19,156,2,71,124,53,21,136,102,244,92,54,45,235,237,5,
64,20,163,55,196,178,161,185,194,52,250,37,21,95,100,254,
44,210,182,239,122,133,155,227,65,53,183,171,216,58,34,189,
161,101,20,121,225,11,21,69,97,105,124,32,78,131,233,67,
155,229,83,98,206,207,177,34,241,176,40,64,114,124,253,200,
89,49,149,6,225,127,110,8,60,232,98,138,241,145,15,186,
250,60,107,233,20,131,89,155,126,57,128,80,224,185,20,189,
115,118,203,24,160,193,165,226,253,244,92,144,240,125,212,117,
122,135,158,243,248,175,52,31,77,234,166,46,103,164,10,52,
242,10,144,179,136,9,58,240,227,151,169,34,239,166,151,210,
62,194,225,51,5,216,69,188,208,229,112,241,234,72,154,61,
217,59,196,179,237,145,223,55,219,93,167,195,8,21,18,5,
191,78,21,84,12,113,206,171,57,168,196,148,60,236,135,166,
27,6,24,32,7,174,10,35,211,147,120,80,144,158,249,208,
228,232,106,250,177,233,28,226,91,199,85,154,248,151,29,152,
115,49,39,234,196,156,118,157,156,82,117,186,16,219,120,164,
247,49,11,37,235,36,9,135,222,83,56,8,81,242,197,249,
165,246,35,220,140,240,212,168,134,58,158,61,161,98,143,138,
93,200,111,214,83,65,245,215,56,124,159,230,33,195,149,197,
29,163,106,168,213,107,252,247,37,141,16,95,245,226,195,79,
241,98,89,132,86,41,245,229,50,73,202,10,157,71,169,172,
210,190,208,194,195,132,190,1,155,229,198,57,190,85,42,39,
183,74,232,245,149,255,211,235,217,99,166,235,43,31,190,77,
103,183,126,243,253,173,223,122,12,73,94,48,201,209,69,94,
185,186,118,116,95,164,25,50,3,176,175,117,225,227,248,198,
68,126,217,110,36,29,37,53,100,91,211,84,153,3,135,158,
253,236,194,133,179,244,168,148,106,247,251,76,187,115,206,141,
134,203,140,100,122,13,71,119,127,124,157,170,56,35,165,148,
181,161,47,218,216,28,182,145,100,173,144,153,165,156,153,133,
96,15,228,233,149,213,105,211,232,228,148,164,157,126,95,6,
158,245,83,234,248,51,200,39,153,44,51,61,150,80,224,250,
27,100,41,203,28,102,149,203,152,182,92,245,83,138,129,57,
149,25,221,70,230,154,83,197,153,169,253,77,74,237,38,221,
35,93,132,104,235,41,21,28,148,179,120,108,61,207,0,186,
59,153,183,158,236,68,82,210,169,231,19,164,48,141,98,32,
245,35,155,145,125,194,147,93,169,228,4,252,57,171,74,78,
130,158,196,173,48,28,226,153,163,194,141,216,209,182,167,188,
113,208,201,122,8,201,189,39,110,28,162,140,91,199,138,81,
45,87,5,239,203,99,183,219,185,182,114,214,70,105,183,78,
182,135,177,69,45,138,108,159,236,145,188,24,59,127,97,206,
183,106,26,10,190,243,75,119,81,66,141,207,98,251,78,79,
95,220,240,251,228,212,22,107,79,225,251,69,202,52,172,31,
83,241,48,3,249,87,212,251,30,22,189,189,157,84,239,29,
173,247,159,6,114,144,215,155,111,28,123,123,202,188,86,250,
169,19,203,156,236,205,107,133,14,134,177,146,61,117,103,236,
165,12,6,61,251,133,236,133,209,240,69,232,73,181,62,246,
254,137,231,69,150,19,116,36,26,132,18,36,102,217,37,129,
36,59,210,99,164,82,215,47,244,178,236,149,181,104,33,124,
169,47,234,56,255,191,250,254,89,55,116,79,164,151,200,108,
76,150,249,93,216,115,176,253,250,89,14,252,116,150,197,177,
247,94,68,189,86,198,90,99,25,249,78,215,255,160,47,143,
211,102,206,88,38,64,70,110,51,222,200,89,207,181,219,16,
115,47,146,29,31,81,138,120,216,241,190,73,52,38,250,171,
251,147,93,61,63,206,116,61,83,159,56,244,53,196,99,190,
117,120,133,69,131,110,251,102,170,162,66,191,11,248,107,96,
184,54,10,162,38,230,69,9,127,27,248,187,104,204,53,170,
197,106,21,229,102,231,196,164,191,77,244,240,154,177,217,168,
138,255,1,71,9,152,120,
};
EmbeddedPython embedded_m5_internal_param_TaggedPrefetcher(
"m5/internal/param_TaggedPrefetcher.py",
"/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_TaggedPrefetcher.py",
"m5.internal.param_TaggedPrefetcher",
data_m5_internal_param_TaggedPrefetcher,
2455,
7400);
} // anonymous namespace
| 58.54386 | 97 | 0.668365 | hoho20000000 |
ac9720657a55c816255d46b6862b74fb60c8ae1a | 19,109 | cpp | C++ | project/c++/mri/src/PI-slim-napa/recdopt/packet/tunnelset.cpp | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/PI-slim-napa/recdopt/packet/tunnelset.cpp | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/PI-slim-napa/recdopt/packet/tunnelset.cpp | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
//
// File: tunnelset.cpp
//
// Description: see .h file
//
// Copyright (c) 2012 Agilent Technologies. All rights reserved.
// $Log: tunnelset.cpp $
// Revision 12 2012/10/05 03:28:07 +0800 hen55467 /MassTransit/MT1.10.100_Tip_SP1/Integration/IQ335326_Thomas
// Allow bearer ids to be 0x0 - 0xF
//
// Revision 11 2012/10/01 11:07:20 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Setting bearer to NO_BEARERS_FOUND should be silent.
//
// Revision 10 2012/10/01 10:52:04 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Insulate PI from bad bearer_id's in the packet.
//
// Revision 9 2012/09/14 10:57:16 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// IQ00335595: Need to be able to debug cp follower in the middle of large data sets
//
// Revision 8 2012/08/09 16:35:24 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Simplify the linked bearer calculations
//
// Revision 7 2012/08/02 17:08:12 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Support APN and bearerId columns in the Call view
//
// Revision 6 2012/07/30 11:11:03 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Fix tunnel Ends duplication bug, and fix db pool deadlock issues.
//
// Revision 5 2012/07/17 15:41:26 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Run astyler
//
// Revision 4 2012/07/17 14:19:06 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Ran with Astyler
//
// Revision 3 2012/07/13 11:51:01 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Optimize the classifier and move the UPStats call to the time order thread
//
// Revision 2 2012/07/12 10:23:58 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Reduce usage of container classes in the classifiedpacket
//
// Revision 1 2012/06/28 15:29:09 -0600 hen55467 /MassTransit/MT1.10.100_Tip/Integration/Thomas
// Needed for new tunnel interface logic
//
//
//
//////////////////////////////////////////////////////////////////////////////
#include <assert.h>
#include "logger.h"
#include "tunnelset.h"
eInterfaceType tunnelMappedT::translateInterfaceType(eInterfaceType to_trans)
{
switch(to_trans)
{
case INTERFACE_TYPE_S1U_ENODEB_GTPU: // 0: S1-U eNodeB GTP-U interface
case INTERFACE_TYPE_S1U_SGW_GTPU: // 1: S1-U SGW GTP-U interface
return INTERFACE_TYPE_S1S11;
case INTERFACE_TYPE_S5_S8_SGW_GTPU: // 4: S5/S8 SGW GTP-U interface
case INTERFACE_TYPE_S5_S8_PGW_GTPU: // 5: S5/S8 PGW GTP-U interface
case INTERFACE_TYPE_S5_S8_SGW_GTPC: // 6: S5/S8 SGW GTP-C interface
case INTERFACE_TYPE_S5_S8_PGW_GTPC: // 7: S5/S8 PGW GTP-C interface
case INTERFACE_TYPE_S5_S8_SGW_PMIPV6: // 8: S5/S8 SGW PMIPv6 interface (the 32 bit GRE key is encoded in 32 bit TEID field and since alternate CoA is not used the control plane and user plane addresses are the same for PMIPv6)
case INTERFACE_TYPE_S5_S8_PGW_PMIPV6: // 9: S5/S8 PGW PMIPv6 interface (the 32 bit GRE key is encoded in 32 bit TEID field and the control plane and user plane addresses are the same for PMIPv6)
return INTERFACE_TYPE_S5;
case INTERFACE_TYPE_S11_MME_GTPC: // 10: S11 MME GTP-C interface
case INTERFACE_TYPE_S11_S4_SGW_GTPC: // 11: S11/S4 SGW GTP-C interface
return INTERFACE_TYPE_S1S11;
case INTERFACE_TYPE_S12_RNC_GTPU: // 2: S12 RNC GTP-U interface
case INTERFACE_TYPE_S12_SGW_GTPU: // 3: S12 SGW GTP-U interface
case INTERFACE_TYPE_S10_MME_GTPC: // 12: S10 MME GTP-C interface
case INTERFACE_TYPE_S3_MME_GTPC: // 13: S3 MME GTP-C interface
case INTERFACE_TYPE_S3_SGSN_GTPC: // 14: S3 SGSN GTP-C interface
case INTERFACE_TYPE_S4_SGSN_GTPU: // 15: S4 SGSN GTP-U interface
case INTERFACE_TYPE_S4_SGW_GTPU: // 16: S4 SGW GTP-U interface
case INTERFACE_TYPE_S4_SGSN_GTPC: // 17: S4 SGSN GTP-C interface
case INTERFACE_TYPE_S16_SGSN_GTPC: // 18: S16 SGSN GTP-C interface
case INTERFACE_TYPE_ENODEB_GTPU_DL: // 19: eNodeB GTP-U interface for DL data forwarding
case INTERFACE_TYPE_ENODEB_GTPU_UL: // 20: eNodeB GTP-U interface for UL data forwarding
case INTERFACE_TYPE_RNC_GTPU: // 21: RNC GTP-U interface for data forwarding
case INTERFACE_TYPE_SGSN_GTPU: // 22: SGSN GTP-U interface for data forwarding
case INTERFACE_TYPE_SGW_GTPU_DL: // 23: SGW GTP-U interface for DL data forwarding
case INTERFACE_TYPE_SM_MBMS_GW_GTPC: // 24: Sm MBMS GW GTP-C interface
case INTERFACE_TYPE_SN_MBMS_GW_GTPC: // 25: Sn MBMS GW GTP-C interface
case INTERFACE_TYPE_SM_MME_GTPC: // 26: Sm MME GTP-C interface
case INTERFACE_TYPE_SN_SGSN_GTPC: // 27: Sn SGSN GTP-C interface
case INTERFACE_TYPE_SGW_GTPU_UL: // 28: SGW GTP-U interface for UL data forwarding
case INTERFACE_TYPE_SN_SGSN_GTPU: // 29: Sn SGSN GTP-U interface
default:
case INTERFACE_TYPE_UNKNOWN: // Code for interface type unknown or not read
return INTERFACE_TYPE_UNKNOWN;
case INTERFACE_TYPE_S1S11: // Code for ALL S1/S11 types
return INTERFACE_TYPE_S1S11;
case INTERFACE_TYPE_S5: // Code for ALL S5 types
return INTERFACE_TYPE_S5;
case INTERFACE_TYPE_GN: // Code for ALL GN types
case INTERFACE_TYPE_GN_GTPU: // This is not a true specification enum: but I needed something to represent Gn user plane: and nothing else works.
case INTERFACE_TYPE_GN_GTPC: // This is not a true specification enum: but I needed something to represent Gn control plane: and nothing else works.
return INTERFACE_TYPE_GN;
case INTERFACE_TYPE_SGIGX: // Code for ALL SGi/Gx typesThis is not a true specification enum: but I needed something to represent Gx control plane: and nothing else works.
case INTERFACE_TYPE_SGIGX_GTPU: // This is not a true specification enum: but I needed something to represent Gx user plane: and nothing else works.
case INTERFACE_TYPE_SGIGX_GTPC: // This is not a true specification enum: but I needed something to represent Gx control plane: and nothing else works.
return INTERFACE_TYPE_SGIGX;
}
return INTERFACE_TYPE_UNKNOWN;
}
eSimplifiedInterfaceType tunnelMappedT::getSimplifiedInterfaceType(eInterfaceType to_trans)
{
switch(to_trans)
{
case INTERFACE_TYPE_S1U_ENODEB_GTPU: // 0: S1-U eNodeB GTP-U interface
case INTERFACE_TYPE_S1U_SGW_GTPU: // 1: S1-U SGW GTP-U interface
return SINTTYPE_S1S11;
case INTERFACE_TYPE_S5_S8_SGW_GTPU: // 4: S5/S8 SGW GTP-U interface
case INTERFACE_TYPE_S5_S8_PGW_GTPU: // 5: S5/S8 PGW GTP-U interface
case INTERFACE_TYPE_S5_S8_SGW_GTPC: // 6: S5/S8 SGW GTP-C interface
case INTERFACE_TYPE_S5_S8_PGW_GTPC: // 7: S5/S8 PGW GTP-C interface
case INTERFACE_TYPE_S5_S8_SGW_PMIPV6: // 8: S5/S8 SGW PMIPv6 interface (the 32 bit GRE key is encoded in 32 bit TEID field and since alternate CoA is not used the control plane and user plane addresses are the same for PMIPv6)
case INTERFACE_TYPE_S5_S8_PGW_PMIPV6: // 9: S5/S8 PGW PMIPv6 interface (the 32 bit GRE key is encoded in 32 bit TEID field and the control plane and user plane addresses are the same for PMIPv6)
return SINTTYPE_S5;
case INTERFACE_TYPE_S11_MME_GTPC: // 10: S11 MME GTP-C interface
case INTERFACE_TYPE_S11_S4_SGW_GTPC: // 11: S11/S4 SGW GTP-C interface
return SINTTYPE_S1S11;
case INTERFACE_TYPE_S12_RNC_GTPU: // 2: S12 RNC GTP-U interface
case INTERFACE_TYPE_S12_SGW_GTPU: // 3: S12 SGW GTP-U interface
case INTERFACE_TYPE_S10_MME_GTPC: // 12: S10 MME GTP-C interface
case INTERFACE_TYPE_S3_MME_GTPC: // 13: S3 MME GTP-C interface
case INTERFACE_TYPE_S3_SGSN_GTPC: // 14: S3 SGSN GTP-C interface
case INTERFACE_TYPE_S4_SGSN_GTPU: // 15: S4 SGSN GTP-U interface
case INTERFACE_TYPE_S4_SGW_GTPU: // 16: S4 SGW GTP-U interface
case INTERFACE_TYPE_S4_SGSN_GTPC: // 17: S4 SGSN GTP-C interface
case INTERFACE_TYPE_S16_SGSN_GTPC: // 18: S16 SGSN GTP-C interface
case INTERFACE_TYPE_ENODEB_GTPU_DL: // 19: eNodeB GTP-U interface for DL data forwarding
case INTERFACE_TYPE_ENODEB_GTPU_UL: // 20: eNodeB GTP-U interface for UL data forwarding
case INTERFACE_TYPE_RNC_GTPU: // 21: RNC GTP-U interface for data forwarding
case INTERFACE_TYPE_SGSN_GTPU: // 22: SGSN GTP-U interface for data forwarding
case INTERFACE_TYPE_SGW_GTPU_DL: // 23: SGW GTP-U interface for DL data forwarding
case INTERFACE_TYPE_SM_MBMS_GW_GTPC: // 24: Sm MBMS GW GTP-C interface
case INTERFACE_TYPE_SN_MBMS_GW_GTPC: // 25: Sn MBMS GW GTP-C interface
case INTERFACE_TYPE_SM_MME_GTPC: // 26: Sm MME GTP-C interface
case INTERFACE_TYPE_SN_SGSN_GTPC: // 27: Sn SGSN GTP-C interface
case INTERFACE_TYPE_SGW_GTPU_UL: // 28: SGW GTP-U interface for UL data forwarding
case INTERFACE_TYPE_SN_SGSN_GTPU: // 29: Sn SGSN GTP-U interface
default:
case INTERFACE_TYPE_UNKNOWN: // Code for interface type unknown or not read
return SINTTYPE_UNKNOWN;
case INTERFACE_TYPE_S1S11: // Code for ALL S1/S11 types
return SINTTYPE_S1S11;
case INTERFACE_TYPE_S5: // Code for ALL S5 types
return SINTTYPE_S5;
case INTERFACE_TYPE_GN: // Code for ALL GN types
case INTERFACE_TYPE_GN_GTPU: // This is not a true specification enum: but I needed something to represent Gn user plane: and nothing else works.
case INTERFACE_TYPE_GN_GTPC: // This is not a true specification enum: but I needed something to represent Gn control plane: and nothing else works.
return SINTTYPE_GN;
case INTERFACE_TYPE_SGIGX: // Code for ALL SGi/Gx typesThis is not a true specification enum: but I needed something to represent Gx control plane: and nothing else works.
case INTERFACE_TYPE_SGIGX_GTPU: // This is not a true specification enum: but I needed something to represent Gx user plane: and nothing else works.
case INTERFACE_TYPE_SGIGX_GTPC: // This is not a true specification enum: but I needed something to represent Gx control plane: and nothing else works.
return SINTTYPE_GX;
}
return SINTTYPE_UNKNOWN;
}
eInterfaceType tunnelMappedT::getInterfaceType(eSimplifiedInterfaceType to_trans)
{
switch(to_trans)
{
default:
case SINTTYPE_UNKNOWN:
return INTERFACE_TYPE_UNKNOWN;
case SINTTYPE_GN:
return INTERFACE_TYPE_GN;
case SINTTYPE_S5:
return INTERFACE_TYPE_S5;
case SINTTYPE_S1S11:
return INTERFACE_TYPE_S1S11;
case SINTTYPE_GX:
return INTERFACE_TYPE_SGIGX;
}
return INTERFACE_TYPE_UNKNOWN;
}
tunnelMappedT::tunnelMappedT(uint16_t bearerId, eInterfaceType type)
{
setBearer(bearerId);
setType(type);
}
tunnelMappedT::tunnelMappedT(tunnelSimpleMappedT const & ts)
{
setBearer(ts.m_nBearerId);
setType(ts.m_eInterface);
}
tunnelMappedT::tunnelMappedT(tunnelMappedT const & ts)
: m_sBearerIds(ts.m_sBearerIds), m_sInterfaces(ts.m_sInterfaces), m_mAdded(ts.m_mAdded)
{
}
bool tunnelMappedT::operator==(tunnelMappedT const &rhs) const
{
if(m_sBearerIds == rhs.m_sBearerIds)
if(m_sInterfaces == rhs.m_sInterfaces)
if(m_mAdded == rhs.m_mAdded)
return true;
return false;
}
tunnelMappedT const &tunnelMappedT::operator=(tunnelMappedT const &rhs)
{
m_sBearerIds = rhs.m_sBearerIds;
m_sInterfaces = rhs.m_sInterfaces;
m_mAdded = rhs.m_mAdded;
return *this;
}
bool tunnelMappedT::isUnknown(void) const
{
return m_sInterfaces.none();
}
bool tunnelMappedT::hasType(eSimplifiedInterfaceType stype) const
{
if(stype == SINTTYPE_UNKNOWN)
return m_sInterfaces.none();
return m_sInterfaces.test(stype);
}
void tunnelMappedT::setType(eSimplifiedInterfaceType stype)
{
if(stype != SINTTYPE_UNKNOWN)
m_sInterfaces.set(stype);
}
void tunnelMappedT::setType(eInterfaceType eType)
{
setType(getSimplifiedInterfaceType(eType));
}
void tunnelMappedT::resetType(eSimplifiedInterfaceType stype)
{
m_sInterfaces.reset(stype);
}
void tunnelMappedT::resetType(eInterfaceType eType)
{
m_sInterfaces.reset(getSimplifiedInterfaceType(eType));
}
bool tunnelMappedT::noBearersFound(void) const
{
return m_sBearerIds.none();
}
bool tunnelMappedT::hasBearer(uint16_t nBearerId) const
{
return m_sBearerIds.test(nBearerId);
}
void tunnelMappedT::setBearer(uint16_t nBearerId)
{
if(nBearerId == NO_BEARERS_FOUND)
return;
if(nBearerId < NO_BEARERS_FOUND)
m_sBearerIds.set(nBearerId);
else
{
LOG_ERROR(LOG_ID("cpfollower"), "Trying to set bearerId in tunnelMappedT to %u", (uint32_t)nBearerId);
}
}
void tunnelMappedT::resetBearer(uint16_t nBearerId)
{
m_sBearerIds.reset(nBearerId);
}
void tunnelMappedT::merge(tunnelMappedT const &to_merge, eSimplifiedInterfaceType canonicalType)
{
// Merge does not touch the m_nAdded member
m_sBearerIds |= to_merge.m_sBearerIds;
m_sInterfaces |= to_merge.m_sInterfaces;
if(isUnknown())
setType(canonicalType);
}
void tunnelMappedT::merge(tunnelSimpleMappedT const &to_merge, eSimplifiedInterfaceType canonicalType)
{
// Merge does not touch the m_nAdded member
setBearer(to_merge.m_nBearerId);
m_sInterfaces.set(getSimplifiedInterfaceType(to_merge.m_eInterface));
if(isUnknown())
setType(canonicalType);
}
uint32_t tunnelMappedT::firstBearer(void) const
{
for(uint32_t bearer = 0; bearer < MAX_BEARERS_COUNT; ++bearer)
if(m_sBearerIds.test(bearer))
return bearer;
return NO_BEARERS_FOUND;
}
eSimplifiedInterfaceType tunnelMappedT::firstInterface(void) const
{
for(eSimplifiedInterfaceType type = SINTTYPE_UNKNOWN; type < SINTTYPE_COUNT;
type=(eSimplifiedInterfaceType)(((uint32_t)type)+1))
if(m_sInterfaces.test(type))
return type;
return SINTTYPE_UNKNOWN;
}
void tunnelMappedT::merge(eSimplifiedInterfaceType canonicalType)
{
// Merge does not touch the m_nAdded member
if(isUnknown())
setType(canonicalType);
}
eSimplifiedInterfaceType tunnelMappedT::packetInterfaceType(void) const
{
// The logic behind this function is as follows:
// 1) if the type is unknown, then that is the best thing to report to the caller.
// 2) If one of the types is S5, then that should take precedence, since it turns out that
// an S5 packet can have S5 only, or S5 and S1S11. An S1S11 packet on the other hand can have
// only S1S11 type in it.
// 3) So if S5 is not present, then we expect only a single type in the set, and that type is the
// type that the caller wants to know about.
if(isUnknown())
return SINTTYPE_UNKNOWN;
if(hasType(SINTTYPE_S5))
return SINTTYPE_S5;
return firstInterface();
}
bool tunnelMappedT::hasPendingAdds(void) const
{
if(m_mAdded.size() == m_sInterfaces.count())
return false;
return true;
}
void tunnelMappedT::buildPendingAdds(pendingAddedSetT &toadd) const
{
if(m_mAdded.size() == m_sInterfaces.count())
return;
for(eSimplifiedInterfaceType type = SINTTYPE_UNKNOWN; type < SINTTYPE_COUNT;
type=(eSimplifiedInterfaceType)(((uint32_t)type)+1))
{
if(m_sInterfaces.test(type))
{
if(m_mAdded.find(type) == m_mAdded.end())
toadd.set(type);
}
}
}
void tunnelMappedT::registerAdd(rowAddKeyT const &type, rowAddMappedT const &added)
{
addedMapT::value_type new_value(type, added);
m_mAdded.insert(new_value);
}
tunnelKeyT::tunnelKeyT(uint32_t teid, bool bIsIpv6, uint64_t nMSWIP, uint64_t nLSWIP)
: m_nTeid(teid), m_bIsIPV6(bIsIpv6), m_nMSWIP(nMSWIP), m_nLSWIP(nLSWIP)
{
}
tunnelKeyT::tunnelKeyT(uint32_t teid, ipv4_row_key_t ipv4)
: m_nTeid(teid), m_bIsIPV6(false), m_nMSWIP(0), m_nLSWIP(ipv4.ipv4)
{
}
tunnelKeyT::tunnelKeyT(uint32_t teid, ipv6_row_key_t ipv6)
: m_nTeid(teid), m_bIsIPV6(true), m_nMSWIP(ipv6.mipv6), m_nLSWIP(ipv6.lipv6)
{
}
tunnelKeyT::tunnelKeyT(tunnelKeyT const & ts)
: m_nTeid(ts.m_nTeid), m_bIsIPV6(ts.m_bIsIPV6), m_nMSWIP(ts.m_nMSWIP), m_nLSWIP(ts.m_nLSWIP)
{
}
tunnelKeyT::tunnelKeyT(tunnelSimpleKeyT const & ts)
: m_nTeid(ts.m_nTeid), m_bIsIPV6(ts.m_bIsIPV6), m_nMSWIP(ts.m_nMSWIP), m_nLSWIP(ts.m_nLSWIP)
{
}
ipv4_row_key_t tunnelKeyT::get_ipv4_key(void) const
{
return ipv4_row_key_t(m_nLSWIP);
}
void tunnelKeyT::set_ipv4_key(ipv4_row_key_t key)
{
m_bIsIPV6 = false;
m_nMSWIP = 0;
m_nLSWIP = key.ipv4;
}
ipv6_row_key_t tunnelKeyT::get_ipv6_key(void) const
{
return ipv6_row_key_t(m_nMSWIP, m_nLSWIP);
}
void tunnelKeyT::set_ipv6_key(ipv6_row_key_t key)
{
m_bIsIPV6 = true;
m_nMSWIP = key.mipv6;
m_nLSWIP = key.lipv6;
}
bool tunnelKeyT::operator<(tunnelKeyT const &rhs) const
{
if(m_nTeid == rhs.m_nTeid)
{
if(m_bIsIPV6 == rhs.m_bIsIPV6)
{
if(m_nMSWIP == rhs.m_nMSWIP)
{
return m_nLSWIP < rhs.m_nLSWIP;
}
else
{
return m_nMSWIP < rhs.m_nMSWIP;
}
}
else
{
if(!m_bIsIPV6)
return true;
}
}
else
{
return m_nTeid < rhs.m_nTeid;
}
return false;
}
bool tunnelKeyT::operator==(tunnelKeyT const &rhs) const
{
if(m_nTeid == rhs.m_nTeid)
{
if(m_bIsIPV6 == rhs.m_bIsIPV6)
{
if(m_nMSWIP == rhs.m_nMSWIP)
{
return m_nLSWIP == rhs.m_nLSWIP;
}
}
}
return false;
}
| 41.631808 | 240 | 0.661364 | jia57196 |
ac98cb3849583db62e6c84d96b3bbb447b64167f | 882 | cpp | C++ | common/lib/Vector/Vector.cpp | mc18g13/teensy-drone | 21a396c44a32b85d6455de2743e52ba2c95bb07d | [
"MIT"
] | null | null | null | common/lib/Vector/Vector.cpp | mc18g13/teensy-drone | 21a396c44a32b85d6455de2743e52ba2c95bb07d | [
"MIT"
] | null | null | null | common/lib/Vector/Vector.cpp | mc18g13/teensy-drone | 21a396c44a32b85d6455de2743e52ba2c95bb07d | [
"MIT"
] | null | null | null | #include "Vector.h"
#include "Quaternion.h"
Vector::Vector() : v0(0), v1(0), v2(0) {}
Vector::Vector(float32_t _v0, float32_t _v1, float32_t _v2) {
v0 = _v0;
v1 = _v1;
v2 = _v2;
}
Vector Vector::minus(Vector v) {
return Vector(v0 - v.v0, v1 - v.v1, v2 - v.v2);
}
Vector Vector::add(Vector v) {
return Vector(v0 + v.v0, v1 + v.v1, v2 + v.v2);
}
Vector Vector::divide(float32_t a) {
return Vector(v0 / a, v1 / a, v2 / a);
}
Vector Vector::multiply(float32_t a) {
return Vector(v0 * a, v1 * a, v2 * a);
}
float32_t Vector::magnitude() {
return sqrt(v0 * v0 + v1 * v1 + v2 * v2);
}
Vector Vector::asUnit() {
float32_t inverseMagnitude = Math::fastInverseSquareRoot(v0 * v0 + v1 * v1 + v2 * v2);
return Vector(v0 * inverseMagnitude, v1 * inverseMagnitude, v2 * inverseMagnitude);
}
Quaternion Vector::toQuaternion() {
return Quaternion(0, v0, v1, v2);
};
| 21.512195 | 88 | 0.633787 | mc18g13 |
ac9bbc6bf15e5d7b3d39e29918a0d63392279e2b | 601 | hpp | C++ | libs/renderer/include/sge/renderer/texture/capabilities_field_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/renderer/include/sge/renderer/texture/capabilities_field_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/renderer/include/sge/renderer/texture/capabilities_field_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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)
#ifndef SGE_RENDERER_TEXTURE_CAPABILITIES_FIELD_FWD_HPP_INCLUDED
#define SGE_RENDERER_TEXTURE_CAPABILITIES_FIELD_FWD_HPP_INCLUDED
#include <sge/renderer/texture/capabilities.hpp>
#include <fcppt/container/bitfield/object_fwd.hpp>
namespace sge::renderer::texture
{
using capabilities_field = fcppt::container::bitfield::object<sge::renderer::texture::capabilities>;
}
#endif
| 30.05 | 100 | 0.778702 | cpreh |
aca67d2392ee147493e0c311330e400de6ff9b5d | 637 | cpp | C++ | patbasic/test1051.cpp | neild47/PATBasic | 6215232750aa62cf406eb2a9f9c9a6d7c3850339 | [
"MIT"
] | null | null | null | patbasic/test1051.cpp | neild47/PATBasic | 6215232750aa62cf406eb2a9f9c9a6d7c3850339 | [
"MIT"
] | null | null | null | patbasic/test1051.cpp | neild47/PATBasic | 6215232750aa62cf406eb2a9f9c9a6d7c3850339 | [
"MIT"
] | null | null | null | //
// Created by neild47 on 18-4-28.
//
#include <iostream>
#include <cmath>
using namespace std;
int test1051() {
double r1, p1, r2, p2;
cin >> r1 >> p1 >> r2 >> p2;
double n1, n2, n3, n4;
n1 = r1 * cos(p1);
n2 = r1 * sin(p1);
n3 = r2 * cos(p2);
n4 = r2 * sin(p2);
double a, b;
a = n1 * n3 - n2 * n4;
b = n1 * n4 + n2 * n3;
if (a < 0 && a >= -0.005) {
printf("0.00");
} else {
printf("%.2f", a);
}
if (b >= 0) {
printf("+%.2fi\n", b);
} else if (b < 0 && b >= -0.005) {
printf("+0.00i\n");
} else {
printf("%.2fi\n", b);
}
}
| 18.735294 | 38 | 0.414443 | neild47 |
aca72d628281ab6382c8fc2b5c247bd99b0ba05f | 1,393 | cpp | C++ | Chapter5/12_image_thresholding.cpp | robotchaoX/Hands-On-GPU-Accelerated-Computer-Vision-with-OpenCV-and-CUDA | fa0c6c80e70d4dbbea8662b6f17d18927ca6d3fa | [
"MIT"
] | null | null | null | Chapter5/12_image_thresholding.cpp | robotchaoX/Hands-On-GPU-Accelerated-Computer-Vision-with-OpenCV-and-CUDA | fa0c6c80e70d4dbbea8662b6f17d18927ca6d3fa | [
"MIT"
] | null | null | null | Chapter5/12_image_thresholding.cpp | robotchaoX/Hands-On-GPU-Accelerated-Computer-Vision-with-OpenCV-and-CUDA | fa0c6c80e70d4dbbea8662b6f17d18927ca6d3fa | [
"MIT"
] | null | null | null | #include <iostream>
#include "opencv2/opencv.hpp"
int main(int argc, char* argv[])
{
//Read Image
cv::Mat h_img1 = cv::imread("images/cameraman.tif", 0);
//Define device variables
cv::cuda::GpuMat d_result1, d_result2, d_result3, d_result4, d_result5, d_img1;
//Upload image on device
d_img1.upload(h_img1);
//Perform different thresholding techniques on device
cv::cuda::threshold(d_img1, d_result1, 128.0, 255.0, cv::THRESH_BINARY);
cv::cuda::threshold(d_img1, d_result2, 128.0, 255.0, cv::THRESH_BINARY_INV);
cv::cuda::threshold(d_img1, d_result3, 128.0, 255.0, cv::THRESH_TRUNC);
cv::cuda::threshold(d_img1, d_result4, 128.0, 255.0, cv::THRESH_TOZERO);
cv::cuda::threshold(d_img1, d_result5, 128.0, 255.0, cv::THRESH_TOZERO_INV);
//Define host variables
cv::Mat h_result1, h_result2, h_result3, h_result4, h_result5;
//Copy results back to host
d_result1.download(h_result1);
d_result2.download(h_result2);
d_result3.download(h_result3);
d_result4.download(h_result4);
d_result5.download(h_result5);
cv::imshow("Result Threshhold binary ", h_result1);
cv::imshow("Result Threshhold binary inverse ", h_result2);
cv::imshow("Result Threshhold truncated ", h_result3);
cv::imshow("Result Threshhold truncated to zero ", h_result4);
cv::imshow("Result Threshhold truncated to zero inverse ", h_result5);
cv::waitKey();
return 0;
}
| 40.970588 | 81 | 0.72649 | robotchaoX |
aca7fb019c97d1ff67c829f5263eaa8a1ef3ac6d | 2,491 | hpp | C++ | Program Interface/src/interfaceDecl.hpp | Milosz08/Matrix_Calculator | 0534b3bb59962312e83273a744356dc598b08a43 | [
"MIT"
] | null | null | null | Program Interface/src/interfaceDecl.hpp | Milosz08/Matrix_Calculator | 0534b3bb59962312e83273a744356dc598b08a43 | [
"MIT"
] | null | null | null | Program Interface/src/interfaceDecl.hpp | Milosz08/Matrix_Calculator | 0534b3bb59962312e83273a744356dc598b08a43 | [
"MIT"
] | null | null | null | #ifndef PK_MATRIX_CALCULATOR_INTERFACEDECL_HPP
#define PK_MATRIX_CALCULATOR_INTERFACEDECL_HPP
#include "../../Matrix Classes/src/packages/abstractMatrixPackage/MatrixAbstract.hpp"
#include "../../Matrix Classes/src/packages/generalMatrixPackage/GeneralMatrix.hpp"
#include "../../Matrix Classes/src/packages/diagonalMatrixPackage/DiagonalMatrix.hpp"
#include <string>
#include <stdlib.h>
#include <windows.h>
#include <winnt.h>
using namespace matrixAbstractPackage; /** @skip package klasy wirtualnej (bazowej) macierzy */
using namespace generalMatrixPackage; /** @skip package klasy pochodnej (macierze standardowa) */
using namespace diagonalMatrixPackage; /** @skip package klasy pochodnej (macierze diagonalna) */
/** @skip Deklaracje funkcji zawartych w folderze ../ProgramInterface/src */
void startPrg();
void mainMenu(HANDLE& hOut);
void initMtrxObj(HANDLE& hOut);
/** @skip Deklaracje funkcji zawartych w folderze ../ProgramInterface/src/initObjects */
std::string saveMtrxInfo(unsigned short int& type, unsigned short int& val);
unsigned short int chooseTypeOfMatrix(HANDLE& hOut);
unsigned short int chooseTypeOfNumbers(HANDLE& hOut);
unsigned short int* setMtrxSize(HANDLE& hOut, unsigned short int& mtrxType, unsigned short int& mtrxValType);
/** @skip Deklaracje funkcji zawartych w folderze ../ProgramInterface/src/mathOperations/mathFirstMtrx */
template<typename T>
unsigned short int mathChooseMtrx(MatrixAbstract<T>* obj, HANDLE& hOut);
template<typename T>
void createMtrxObject(unsigned short int* sizeMtrx, HANDLE& hOut,
unsigned short int& mtrxType, unsigned short int& mtrxValType);
template<class M, class I, typename T>
void onlyOneMtrxMath(unsigned short int& choose, MatrixAbstract<T>* ptr, M& obj, HANDLE& hOut,
unsigned short int& mtrxType, unsigned short int& mtrxValType);
template<class M, typename T>
void onlyOneMtrxMathInfo(MatrixAbstract<T>* ptr, M& outObj, HANDLE& hOut, std::vector<std::string>infMess);
/** @skip Deklaracje funkcji zawartych w folderze ../ProgramInterface/src/mathOperations/mathSecondMtrx */
template<typename T>
unsigned short int mathSecondMatrix(MatrixAbstract<T>* objF, MatrixAbstract<T>* objS, HANDLE& hOut);
template<class M>
void secondMtrxMath(unsigned short int& choose, M& objF, M& objS, HANDLE& hOut);
template<class M>
void secondMtrxMathInfo(M& objF, M& objS, M& objFinal, HANDLE& hOut, std::vector<std::string>infMess);
#endif | 37.742424 | 109 | 0.76114 | Milosz08 |
aca9d77f06dc4bad08f9b5b0c6414387d62ff019 | 332 | cpp | C++ | test/ofp/unittest_unittest.cpp | byllyfish/libofp | 5368b65d17d57286412478adcea84371ef5e4fc4 | [
"MIT"
] | 3 | 2015-07-04T18:12:09.000Z | 2016-09-09T07:12:43.000Z | test/ofp/unittest_unittest.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 20 | 2017-02-20T04:49:10.000Z | 2019-07-09T05:32:54.000Z | test/ofp/unittest_unittest.cpp | byllyfish/libofp | 5368b65d17d57286412478adcea84371ef5e4fc4 | [
"MIT"
] | 1 | 2019-07-16T00:21:42.000Z | 2019-07-16T00:21:42.000Z | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/unittest.h"
using namespace std;
TEST(unittest, test) {
string a = hexclean("00 01 \n - 02 z$ 03");
EXPECT_EQ("00010203", a);
char d[] = {1, 2, 3, 4};
EXPECT_HEX("01020304", d, sizeof(d));
}
| 22.133333 | 63 | 0.644578 | byllyfish |
acaa8f2854ab19c4cb21c961c649058f418e4978 | 973 | hpp | C++ | include/experimental/fundamental/v3/contract/constexpr_assert.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 105 | 2015-01-24T13:26:41.000Z | 2022-02-18T15:36:53.000Z | include/experimental/fundamental/v3/contract/constexpr_assert.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 37 | 2015-09-04T06:57:10.000Z | 2021-09-09T18:01:44.000Z | include/experimental/fundamental/v3/contract/constexpr_assert.hpp | jwakely/std-make | f09d052983ace70cf371bb8ddf78d4f00330bccd | [
"BSL-1.0"
] | 23 | 2015-01-27T11:09:18.000Z | 2021-10-04T02:23:30.000Z | // 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)
// (C) Copyright 2013,2014,2017 Vicente J. Botet Escriba
#ifndef JASEL_EXPERIMENTAL_V3_CONTRACT_CONSTEXPR_ASSERT_HPP
#define JASEL_EXPERIMENTAL_V3_CONTRACT_CONSTEXPR_ASSERT_HPP
#include <cassert>
namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{
namespace detail
{
template<class Assertion>
inline void constexpr_assert_failed(Assertion a) noexcept
{
a();
//quick_exit(EXIT_FAILURE);
}
}
// When evaluated at compile time emits a compilation error if condition is not true.
// Invokes the standard assert at run time.
#define JASEL_CONSTEXPR_ASSERT(cond) \
((void)((cond) ? 0 : (std::experimental::detail::constexpr_assert_failed([](){ assert(false && #cond);}), 0)))
}
}
} // namespace
#endif // JASEL_EXPERIMENTAL_V3_EXPECTED_DETAIL_CONSTEXPR_UTILITY_HPP
| 25.605263 | 116 | 0.756423 | jwakely |
acb07b4c7f9f601d1e9dafbc93988ae6504cb612 | 247 | cpp | C++ | Leetcode1963.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | 1 | 2020-06-28T06:29:05.000Z | 2020-06-28T06:29:05.000Z | Leetcode1963.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | Leetcode1963.cpp | dezhonger/LeetCode | 70de054be5af3a0749dce0625fefd75e176e59f4 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int minSwaps(string s) {
int res = 0, mv = 0;
for (char c : s) {
if (c == '[') res++;
else res--;
mv = min(mv, res);
}
return (-mv + 1) / 2;
}
};
| 19 | 32 | 0.360324 | dezhonger |
acb3902469c3feac429193a97240974670541bd2 | 785 | cpp | C++ | B2G/gecko/content/base/src/nsAtomListUtils.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/content/base/src/nsAtomListUtils.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/content/base/src/nsAtomListUtils.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: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* 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/. */
/*
* Static helper class for implementing atom lists.
*/
#include "nsAtomListUtils.h"
#include "nsIAtom.h"
#include "nsStaticAtom.h"
/* static */ bool
nsAtomListUtils::IsMember(nsIAtom *aAtom,
const nsStaticAtom* aInfo,
uint32_t aInfoCount)
{
for (const nsStaticAtom *info = aInfo, *info_end = aInfo + aInfoCount;
info != info_end; ++info) {
if (aAtom == *(info->mAtom))
return true;
}
return false;
}
| 30.192308 | 79 | 0.608917 | wilebeast |
acbef3993a0af0776b250ae8871bd672afe5b2e4 | 259 | cpp | C++ | tournaments/longestString/longestString.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 5 | 2020-02-06T09:51:22.000Z | 2021-03-19T00:18:44.000Z | tournaments/longestString/longestString.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | null | null | null | tournaments/longestString/longestString.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 3 | 2019-09-27T13:06:21.000Z | 2021-04-20T23:13:17.000Z | std::string longestString(std::vector<std::string> inputArray) {
std::string answer = inputArray[0];
for (int i = 1; i < inputArray.size(); i++) {
if (inputArray[i].size() > answer.size()) {
answer = inputArray[i];
}
}
return answer;
}
| 23.545455 | 64 | 0.602317 | gurfinkel |
acbf9d5811f274b7e3faf017cf7135a8ad794ada | 6,554 | hpp | C++ | cpp2c/test_data/bitblock128.hpp | mendlin/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | 1 | 2021-01-07T03:18:27.000Z | 2021-01-07T03:18:27.000Z | cpp2c/test_data/bitblock128.hpp | Logicalmars/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | null | null | null | cpp2c/test_data/bitblock128.hpp | Logicalmars/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | 1 | 2021-11-29T07:28:13.000Z | 2021-11-29T07:28:13.000Z | #ifndef BITBLOCK128_HPP_
#define BITBLOCK128_HPP_
/*=============================================================================
bitblock128 - Specific 128 bit IDISA implementations.
Copyright (C) 2011, Robert D. Cameron, Kenneth S. Herdy, Hua Huang and Nigel Medforth.
Licensed to the public under the Open Software License 3.0.
Licensed to International Characters Inc.
under the Academic Free License version 3.0.
=============================================================================*/
#include "idisa128.hpp"
#include "builtins.hpp"
union ubitblock {
bitblock128_t _128;
uint64_t _64[sizeof(bitblock128_t)/sizeof(uint64_t)];
uint32_t _32[sizeof(bitblock128_t)/sizeof(uint32_t)];
uint16_t _16[sizeof(bitblock128_t)/sizeof(uint16_t)];
uint8_t _8[sizeof(bitblock128_t)/sizeof(uint8_t)];
};
static IDISA_ALWAYS_INLINE void add_ci_co(bitblock128_t x, bitblock128_t y, bitblock128_t carry_in, bitblock128_t & carry_out, bitblock128_t & sum);
static IDISA_ALWAYS_INLINE void sub_bi_bo(bitblock128_t x, bitblock128_t y, bitblock128_t borrow_in, bitblock128_t & borrow_out, bitblock128_t & difference);
static IDISA_ALWAYS_INLINE void adv_ci_co(bitblock128_t cursor, bitblock128_t carry_in, bitblock128_t & carry_out, bitblock128_t & rslt);
/* The type used to store a carry bit. */
typedef bitblock128_t carry_t;
static IDISA_ALWAYS_INLINE bitblock128_t carry2bitblock(carry_t carry);
static IDISA_ALWAYS_INLINE carry_t bitblock2carry(bitblock128_t carry);
static IDISA_ALWAYS_INLINE void adc(bitblock128_t x, bitblock128_t y, carry_t & carry, bitblock128_t & sum);
static IDISA_ALWAYS_INLINE void sbb(bitblock128_t x, bitblock128_t y, carry_t & borrow, bitblock128_t & difference);
static IDISA_ALWAYS_INLINE void advance_with_carry(bitblock128_t cursor, carry_t & carry, bitblock128_t & rslt);
static IDISA_ALWAYS_INLINE void adc(bitblock128_t x, bitblock128_t y, carry_t carry_in, carry_t & carry_out, bitblock128_t & sum);
static IDISA_ALWAYS_INLINE void sbb(bitblock128_t x, bitblock128_t y, carry_t borrow_in, carry_t & borrow_out, bitblock128_t & difference);
static IDISA_ALWAYS_INLINE void advance_with_carry(bitblock128_t cursor, carry_t carry_in, carry_t & carry_out, bitblock128_t & rslt);
static IDISA_ALWAYS_INLINE bitblock128_t convert (uint64_t s);
static IDISA_ALWAYS_INLINE uint64_t convert (bitblock128_t v);
static IDISA_ALWAYS_INLINE bitblock128_t carry2bitblock(carry_t carry) { return carry;}
static IDISA_ALWAYS_INLINE carry_t bitblock2carry(bitblock128_t carry) { return carry;}
static IDISA_ALWAYS_INLINE void add_ci_co(bitblock128_t x, bitblock128_t y, bitblock128_t carry_in, bitblock128_t & carry_out, bitblock128_t & sum) {
bitblock128_t gen = simd_and(x, y);
bitblock128_t prop = simd_or(x, y);
bitblock128_t partial = simd128<64>::add(simd128<64>::add(x, y), carry_in);
bitblock128_t c1 = simd128<128>::slli<64>(simd128<64>::srli<63>(simd_or(gen, simd_andc(prop, partial))));
sum = simd128<64>::add(c1, partial);
carry_out = simd_or(gen, simd_andc(prop, sum));
}
static IDISA_ALWAYS_INLINE void sub_bi_bo(bitblock128_t x, bitblock128_t y, bitblock128_t borrow_in, bitblock128_t & borrow_out, bitblock128_t & difference){
bitblock128_t gen = simd_andc(y, x);
bitblock128_t prop = simd_not(simd_xor(x, y));
bitblock128_t partial = simd128<64>::sub(simd128<64>::sub(x, y), borrow_in);
bitblock128_t b1 = simd128<128>::slli<64>(simd128<64>::srli<63>(simd_or(gen, simd_and(prop, partial))));
difference = simd128<64>::sub(partial, b1);
borrow_out = simd_or(gen, simd_and(prop, difference));
}
static IDISA_ALWAYS_INLINE void adv_ci_co(bitblock128_t cursor, bitblock128_t carry_in, bitblock128_t & carry_out, bitblock128_t & rslt){
bitblock128_t shift_out = simd128<64>::srli<63>(cursor);
bitblock128_t low_bits = esimd128<64>::mergel(shift_out, carry_in);
carry_out = cursor;
rslt = simd_or(simd128<64>::add(cursor, cursor), low_bits);
}
IDISA_ALWAYS_INLINE void adc(bitblock128_t x, bitblock128_t y, carry_t & carry, bitblock128_t & sum)
{
bitblock128_t gen = simd_and(x, y);
bitblock128_t prop = simd_or(x, y);
bitblock128_t partial = simd128<64>::add(simd128<64>::add(x, y), carry2bitblock(carry));
bitblock128_t c1 = simd128<128>::slli<64>(simd128<64>::srli<63>(simd_or(gen, simd_andc(prop, partial))));
sum = simd128<64>::add(c1, partial);
carry = bitblock2carry(simd128<128>::srli<127>(simd_or(gen, simd_andc(prop, sum))));
}
IDISA_ALWAYS_INLINE void adc(bitblock128_t x, bitblock128_t y, carry_t carry_in, carry_t & carry_out, bitblock128_t & sum)
{
bitblock128_t co;
add_ci_co(x, y, carry2bitblock(carry_in), co, sum);
carry_out = bitblock2carry(simd128<128>::srli<127>(co));
}
IDISA_ALWAYS_INLINE void sbb(bitblock128_t x, bitblock128_t y, carry_t & borrow, bitblock128_t & difference)
{
bitblock128_t gen = simd_andc(y, x);
bitblock128_t prop = simd_not(simd_xor(x, y));
bitblock128_t partial = simd128<64>::sub(simd128<64>::sub(x, y), carry2bitblock(borrow));
bitblock128_t b1 = simd128<128>::slli<64>(simd128<64>::srli<63>(simd_or(gen, simd_and(prop, partial))));
difference = simd128<64>::sub(partial, b1);
borrow = bitblock2carry(simd128<128>::srli<127>(simd_or(gen, simd_and(prop, difference))));
}
IDISA_ALWAYS_INLINE void sbb(bitblock128_t x, bitblock128_t y, carry_t borrow_in, carry_t & borrow_out, bitblock128_t & difference)
{
bitblock128_t bo;
sub_bi_bo(x, y, carry2bitblock(borrow_in), bo, difference);
borrow_out = bitblock2carry(simd128<128>::srli<127>(bo));
}
IDISA_ALWAYS_INLINE void advance_with_carry(bitblock128_t cursor, carry_t & carry, bitblock128_t & rslt)
{
bitblock128_t shift_out = simd128<64>::srli<63>(cursor);
bitblock128_t low_bits = esimd128<64>::mergel(shift_out, carry2bitblock(carry));
carry = bitblock2carry(simd128<128>::srli<64>(shift_out));
rslt = simd_or(simd128<64>::add(cursor, cursor), low_bits);
}
IDISA_ALWAYS_INLINE void advance_with_carry(bitblock128_t cursor, carry_t carry_in, carry_t & carry_out, bitblock128_t & rslt)
{
bitblock128_t shift_out = simd128<64>::srli<63>(cursor);
bitblock128_t low_bits = esimd128<64>::mergel(shift_out, carry2bitblock(carry_in));
carry_out = bitblock2carry(simd128<128>::srli<64>(shift_out));
rslt = simd_or(simd128<64>::add(cursor, cursor), low_bits);
}
IDISA_ALWAYS_INLINE bitblock128_t convert(uint64_t s)
{
ubitblock b;
b._128 = simd128<128>::constant<0>();
b._64[0] = s;
return b._128;
}
IDISA_ALWAYS_INLINE uint64_t convert (bitblock128_t v)
{
return (uint64_t) mvmd128<64>::extract<0>(v);
}
#endif // BITBLOCK128_HPP_
| 46.15493 | 157 | 0.753891 | mendlin |
acc01bb97f2f24bf15130535be776cafc72c18ad | 2,236 | cpp | C++ | Classes/Application.cpp | InversePalindrome/Apophis | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | 7 | 2018-08-20T17:28:29.000Z | 2020-09-05T15:19:31.000Z | Classes/Application.cpp | InversePalindrome/JATR66 | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | null | null | null | Classes/Application.cpp | InversePalindrome/JATR66 | c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8 | [
"MIT"
] | 1 | 2019-12-25T12:02:03.000Z | 2019-12-25T12:02:03.000Z | /*
Copyright (c) 2018 Inverse Palindrome
Apophis - Application.cpp
InversePalindrome.com
*/
#include "Application.hpp"
#include "AppSettings.hpp"
#include "SplashScene.hpp"
#include "LevelManager.hpp"
#include "ResourceParser.hpp"
#include "CCIMGUIGLViewImpl.h"
#include <imgui.h>
#include <cocos/base/CCDirector.h>
#include <cocos/platform/CCFileUtils.h>
#include <cocos/audio/include/AudioEngine.h>
#include <cocos/platform/desktop/CCGLViewImpl-desktop.h>
Application::~Application()
{
AppSettings::getInstance().save(cocos2d::FileUtils::getInstance()->getWritablePath() + "Settings.xml");
LevelManager::getInstance().save(cocos2d::FileUtils::getInstance()->getWritablePath() + "Levels.xml");
cocos2d::experimental::AudioEngine::end();
}
bool Application::applicationDidFinishLaunching()
{
auto* director = cocos2d::Director::getInstance();
if (auto* view = director->getOpenGLView(); !view)
{
view = cocos2d::IMGUIGLViewImpl::createWithRect("Apophis", { 0, 0, 2048, 1536 });
view->setDesignResolutionSize(1024.f, 768.f, ResolutionPolicy::EXACT_FIT);
director->setOpenGLView(view);
director->setClearColor(cocos2d::Color4F::WHITE);
}
auto* files = cocos2d::FileUtils::getInstance();
files->addSearchPath("Entities");
files->addSearchPath("Sprites");
files->addSearchPath("Animations");
files->addSearchPath("Particles");
files->addSearchPath("Fonts");
files->addSearchPath("Sounds");
files->addSearchPath("Music");
files->addSearchPath(cocos2d::FileUtils::getInstance()->getWritablePath());
ResourceParser::parseResources("Resources.xml");
ImGui::GetIO().Fonts->AddFontFromFileTTF("Fonts/OpenSans-Regular.ttf", 40.f);
AppSettings::getInstance().load("Settings.xml");
LevelManager::getInstance().load("Levels.xml");
director->runWithScene(getSplashScene());
return true;
}
void Application::applicationDidEnterBackground()
{
cocos2d::Director::getInstance()->stopAnimation();
cocos2d::experimental::AudioEngine::pauseAll();
}
void Application::applicationWillEnterForeground()
{
cocos2d::Director::getInstance()->startAnimation();
cocos2d::experimental::AudioEngine::resumeAll();
} | 29.421053 | 107 | 0.718247 | InversePalindrome |
accabed9773495b37cc003cdcb3ede1ddc826818 | 1,903 | cpp | C++ | server/Server.cpp | MohamedAshrafTolba/http-client-server | 3776f1a5ff1921564d6c288be0ba870dbdacce22 | [
"MIT"
] | null | null | null | server/Server.cpp | MohamedAshrafTolba/http-client-server | 3776f1a5ff1921564d6c288be0ba870dbdacce22 | [
"MIT"
] | null | null | null | server/Server.cpp | MohamedAshrafTolba/http-client-server | 3776f1a5ff1921564d6c288be0ba870dbdacce22 | [
"MIT"
] | null | null | null | #include "Server.h"
#include <cmath>
#include <iostream>
Server::Server(std::string &port_number, unsigned short backlog, unsigned long max_workers) {
this->port_number = port_number;
this->backlog = backlog;
this->max_workers = max_workers;
server_socket = new ServerSocket(port_number, backlog);
}
Server::~Server() {
delete(server_socket);
}
void Server::run() {
std::string http_version(HTTP_VERSION);
std::mutex pool_mutex;
auto f = [&] {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(5));
pool_mutex.lock();
for (auto it = workers_pool.begin(); it < workers_pool.end();) {
HttpWorkerThread *worker = *it;
if (worker != nullptr && worker->is_done()) {
delete worker;
it = workers_pool.erase(it);
} else {
it++;
}
}
pool_mutex.unlock();
}
};
std::thread gc(f);
while (true) {
while (workers_pool.size() >= max_workers) {
sleep(2);
}
int connecting_socket_fd = server_socket->accept_connection();
if (connecting_socket_fd == -1) {
// Error
}
int timeout = TIMEOUT - floor(0.01 * TIMEOUT * workers_pool.size());
HttpWorkerThread *worker = new HttpWorkerThread(connecting_socket_fd, http_version, timeout);
pool_mutex.lock();
workers_pool.push_back(worker);
pool_mutex.unlock();
}
gc.join();
}
std::string Server::get_port_number() const {
return port_number;
}
unsigned short Server::get_backlog() const {
return backlog;
}
unsigned long Server::get_max_workers() const {
return max_workers;
}
int Server::get_server_socket_fd() const {
return server_socket->get_socket_fd();
} | 25.373333 | 101 | 0.576458 | MohamedAshrafTolba |
accc435d7cfda937b5795bb73b4dd0a4303d522c | 1,627 | cpp | C++ | xpcom_chimera/ChimeraRiderModule.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | xpcom_chimera/ChimeraRiderModule.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | xpcom_chimera/ChimeraRiderModule.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2012 Stevens Institute of Technology.
*
* 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.
*
* Author: Shoufu Luo (sluo2@stevens.edu)
* Mon Jan 2 6:36:10 EDT 2012
*
*/
#include "mozilla/ModuleUtils.h"
#include "nsIClassInfoImpl.h"
#include "ChimeraRider.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(ChimeraRider)
NS_DEFINE_NAMED_CID(CHIMERA_RIDER_CID);
static const mozilla::Module::CIDEntry ChimeraRiderCIDs[] =
{
{ &kCHIMERA_RIDER_CID, false, NULL, ChimeraRiderConstructor },
{ NULL }
};
static const mozilla::Module::ContractIDEntry ChimeraRiderContracts[] =
{
{ CHIMERA_RIDER_CONTRACTID, &kCHIMERA_RIDER_CID},
{ NULL }
};
static const mozilla::Module::CategoryEntry ChimeraRiderCategories[] =
{
{ "profile-after-change", "ChimeraRider", CHIMERA_RIDER_CONTRACTID },
{ NULL }
};
static const mozilla::Module kChimeraRiderModule =
{
mozilla::Module::kVersion,
ChimeraRiderCIDs,
ChimeraRiderContracts,
ChimeraRiderCategories,
};
NSMODULE_DEFN(ChimeraRiderModule) = &kChimeraRiderModule;
NS_IMPL_MOZILLA192_NSGETMODULE(&kChimeraRiderModule)
| 27.116667 | 76 | 0.749232 | ShoufuLuo |
acccf113c3833c66f7da346f52b79524050ee4b4 | 5,045 | cpp | C++ | src/trident/utils/tridentutils.cpp | jrbn/trident | e56a4977054eea01cb3f716db92bde5d6a49bfb7 | [
"Apache-2.0"
] | null | null | null | src/trident/utils/tridentutils.cpp | jrbn/trident | e56a4977054eea01cb3f716db92bde5d6a49bfb7 | [
"Apache-2.0"
] | null | null | null | src/trident/utils/tridentutils.cpp | jrbn/trident | e56a4977054eea01cb3f716db92bde5d6a49bfb7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Jacopo Urbani
*
* 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.
**/
#include <trident/utils/tridentutils.h>
#include <boost/lexical_cast.hpp>
#include <boost/log/trivial.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;
long parseLine(char* line, int skip){
long i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i - skip] = '\0';
i = atol(p);
return i;
}
long TridentUtils::getVmRSS() {
FILE* file = fopen("/proc/self/status", "r");
long result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line, 3);
break;
}
//cout << line << endl;
}
fclose(file);
return result;
}
static unsigned long long lastTotalUser = 0, lastTotalUserLow = 0, lastTotalSys = 0, lastTotalIdle = 0;
double TridentUtils::getCPUUsage() {
double percent;
FILE* file;
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow, &totalSys, &totalIdle);
fclose(file);
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow || totalSys < lastTotalSys || totalIdle < lastTotalIdle) {
percent = -1.0;
} else {
total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) + (totalSys - lastTotalSys);
percent = total;
total += (totalIdle - lastTotalIdle);
percent /= total;
percent *= 100;
}
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return percent;
}
long TridentUtils::diskread() {
FILE* file = fopen("/proc/self/io", "r");
long result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "rchar: ", 7) == 0){
result = parseLine(line, 0);
break;
}
}
fclose(file);
return result;
}
long TridentUtils::diskwrite() {
FILE* file = fopen("/proc/self/io", "r");
long result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "wchar: ", 7) == 0){
result = parseLine(line, 0);
break;
}
}
fclose(file);
return result;
}
long TridentUtils::phy_diskread() {
FILE* file = fopen("/proc/self/io", "r");
long result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "read_bytes: ", 12) == 0){
result = parseLine(line, 0);
break;
}
}
fclose(file);
return result;
}
long TridentUtils::phy_diskwrite() {
FILE* file = fopen("/proc/self/io", "r");
long result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "write_bytes: ", 13) == 0){
result = parseLine(line, 0);
break;
}
}
fclose(file);
return result;
}
void TridentUtils::loadFromFile(string inputfile, std::vector<long> &values) {
std::ifstream ifs(inputfile);
std::string line;
while (std::getline(ifs, line)) {
long value;
try {
value = boost::lexical_cast<long>(line);
} catch (boost::bad_lexical_cast &) {
BOOST_LOG_TRIVIAL(error) << "Failed conversion of " << line;
throw 10;
}
values.push_back(value);
}
ifs.close();
}
void TridentUtils::loadPairFromFile(std::string inputfile,
std::vector<std::pair<long,long>> &values, char sep) {
std::ifstream ifs(inputfile);
std::string line;
while (std::getline(ifs, line)) {
long v1, v2;
try {
auto pos = line.find(sep);
v1 = boost::lexical_cast<long>(line.substr(0, pos));
v2 = boost::lexical_cast<long>(line.substr(pos+1, line.size()));
} catch (boost::bad_lexical_cast &) {
BOOST_LOG_TRIVIAL(error) << "Failed conversion of " << line;
throw 10;
}
values.push_back(std::make_pair(v1, v2));
}
ifs.close();
}
| 28.027778 | 127 | 0.596432 | jrbn |
accfbbce45432c9ac4235b5c5cbb6a3ed224148d | 9,908 | cpp | C++ | src/sc.cpp | josephnoir/indexing | 99f6a02c22451d0db204731a6c53ed56ad751365 | [
"BSD-3-Clause"
] | 5 | 2017-01-30T17:02:24.000Z | 2017-04-22T04:20:41.000Z | src/sc.cpp | josephnoir/indexing | 99f6a02c22451d0db204731a6c53ed56ad751365 | [
"BSD-3-Clause"
] | null | null | null | src/sc.cpp | josephnoir/indexing | 99f6a02c22451d0db204731a6c53ed56ad751365 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* Copyright (C) 2017 *
* Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
******************************************************************************/
#include <cmath>
#include <tuple>
#include <chrono>
#include <limits>
#include <random>
#include <vector>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <unordered_map>
#include "caf/all.hpp"
#include "caf/opencl/all.hpp"
using namespace std;
using namespace std::chrono;
using namespace caf;
using namespace caf::opencl;
// required to allow sending mem_ref<int> in messages
namespace caf {
template <>
struct allowed_unsafe_message_type<mem_ref<uint32_t>> : std::true_type {};
template <>
struct allowed_unsafe_message_type<opencl::dim_vec> : std::true_type {};
template <>
struct allowed_unsafe_message_type<nd_range> : std::true_type {};
}
namespace {
using uval = uint32_t;
using uvec = std::vector<uval>;
using uref = mem_ref<uval>;
/*****************************************************************************\
JUST FOR STUFF
\*****************************************************************************/
template <class T, class E = typename enable_if<is_integral<T>::value>::type>
T round_up(T numToRound, T multiple) {
assert(multiple > 0);
return ((numToRound + multiple - 1) / multiple) * multiple;
}
template <class T, typename std::enable_if<is_integral<T>{}, int>::type = 0>
uval as_uval(T val) { return static_cast<uval>(val); }
template <class T>
vector<T> compact(vector<T> values, vector<T> heads) {
assert(values.size() == heads.size());
vector<T> result;
auto res_size = count(begin(heads), end(heads), 1u);
result.reserve(res_size);
for (size_t i = 0; i < values.size(); ++i) {
if (heads[i] == 1)
result.emplace_back(values[i]);
}
return result;
}
/*****************************************************************************\
INTRODUCE SOME CLI ARGUMENTS
\*****************************************************************************/
class config : public actor_system_config {
public:
size_t iterations = 1000;
size_t threshold = 1500;
string filename = "";
uval bound = 0;
string device_name = "GeForce GTX 780M";
bool print_results;
double frequency = 0.01;
config() {
load<opencl::manager>();
opt_group{custom_options_, "global"}
.add(filename, "data-file,f", "file with test data (one value per line)")
.add(bound, "bound,b", "maximum value (0 will scan values)")
.add(device_name, "device,d", "device for computation (GeForce GTX 780M, "
"empty string will take first available device)")
.add(print_results, "print,p", "print resulting bitmap index")
.add(threshold, "threshold,t", "Threshold for output (1500)")
.add(iterations, "iterations,i", "Number of times the empty kernel is supposed to run (1000)")
.add(frequency, "frequency,F", "Frequency of 1 in the heads array.(0.1)");
}
};
} // namespace <anonymous>
/*****************************************************************************\
MAIN!
\*****************************************************************************/
void caf_main(actor_system& system, const config& cfg) {
uvec values;
uvec heads;
random_device rd; //Will be used to obtain a seed for the random number engine
mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
uniform_int_distribution<size_t> s_gen(1, 100);
uniform_int_distribution<size_t> v_gen(1, numeric_limits<uint16_t>::max());
bernoulli_distribution h_gen(cfg.frequency);
// ---- get data ----
if (cfg.filename.empty()) {
auto size = s_gen(gen) * 1048576 + s_gen(gen);
cout << "Compacting " << size << " values." << endl;
values.reserve(size);
for (size_t i = 0; i < size; ++i)
values.emplace_back(v_gen(gen));
} else {
ifstream source{cfg.filename, std::ios::in};
uval next;
while (source >> next) {
values.push_back(next);
}
}
heads.reserve(values.size());
heads.emplace_back(1);
for (size_t i = 1; i < values.size(); ++i)
heads.emplace_back(h_gen(gen) ? 1 : 0);
// ---- get device ----
auto& mngr = system.opencl_manager();
auto opt = mngr.find_device_if([&](const device_ptr dev) {
if (cfg.device_name.empty())
return true;
return dev->name() == cfg.device_name;
});
if (!opt) {
opt = mngr.find_device_if([&](const device_ptr) { return true; });
if (!opt) {
cout << "No device found." << endl;
return;
}
cerr << "Using device '" << (*opt)->name() << "'." << endl;
}
// ---- general ----
auto dev = move(*opt);
auto prog_es = mngr.create_program_from_file("./include/scan.cl", "", dev);
auto prog_sc = mngr.create_program_from_file("./include/stream_compaction.cl",
"", dev);
{
// ---- funcs ----
auto half_block = dev->max_work_group_size() / 2;
auto get_size = [half_block](size_t n) -> size_t {
return round_up((n + 1) / 2, half_block);
};
auto half_size_for = [](size_t n, size_t block) -> size_t {
return round_up((n + 1) / 2, block);
};
auto reduced_scan = [&](const uref&, uval n) {
// calculate number of groups from the group size from the values size
return size_t{get_size(n) / half_block};
};
auto ndr_scan = [half_size_for, half_block](size_t dim) {
return nd_range{dim_vec{half_size_for(dim,half_block)}, {},
dim_vec{half_block}};
};
auto ndr_compact = [](uval dim) {
return nd_range{dim_vec{round_up(dim, 128u)}, {}, dim_vec{128}};
};
auto reduced_compact = [](const uref&, uval n) {
return size_t{round_up(n, 128u) / 128u};
};
auto one = [](uref&, uref&, uref&, uval) { return size_t{1}; };
auto k_compact = [](uref&, uref&, uref&, uval k) { return size_t{k}; };
// spawn arguments
auto ndr = nd_range{dim_vec{half_block}, {}, dim_vec{half_block}};
// actors
// exclusive scan
auto scan1 = mngr.spawn(
prog_es, "es_phase_1", ndr,
[ndr_scan](nd_range& range, message& msg) -> optional<message> {
msg.apply([&](const uref&, uval n) { range = ndr_scan(n); });
return std::move(msg);
},
in_out<uval, mref, mref>{},
out<uval,mref>{reduced_scan},
local<uval>{half_block * 2},
priv<uval, val>{}
);
auto scan2 = mngr.spawn(
prog_es, "es_phase_2",
nd_range{dim_vec{half_block}, {}, dim_vec{half_block}},
in_out<uval,mref,mref>{},
in_out<uval,mref,mref>{},
priv<uval, val>{}
);
auto scan3 = mngr.spawn(
prog_es, "es_phase_3", ndr,
[ndr_scan](nd_range& range, message& msg) -> optional<message> {
msg.apply([&](const uref&, const uref&, uval n) {
range = ndr_scan(n);
});
return std::move(msg);
},
in_out<uval,mref,mref>{},
in<uval,mref>{},
priv<uval, val>{}
);
// stream compaction
auto sc_count = mngr.spawn(
prog_sc,"countElts", ndr,
[ndr_compact](nd_range& range, message& msg) -> optional<message> {
msg.apply([&](const uref&, uval n) { range = ndr_compact(n); });
return std::move(msg);
},
out<uval,mref>{reduced_compact},
in_out<uval,mref,mref>{},
local<uval>{128},
priv<uval,val>{}
);
// --> sum operation is handled by es actors belows (exclusive scan)
auto sc_move = mngr.spawn(
prog_sc, "moveValidElementsStaged", ndr,
[ndr_compact](nd_range& range, message& msg) -> optional<message> {
msg.apply([&](const uref&, const uref&, const uref&, uval n) {
range = ndr_compact(n);
});
return std::move(msg);
},
out<uval,mref>{one},
in_out<uval,mref,mref>{},
out<uval,mref>{k_compact},
in_out<uval,mref,mref>{},
in_out<uval,mref,mref>{},
local<uval>{128},
local<uval>{128},
local<uval>{128},
priv<uval,val>{}
);
auto values_r = dev->global_argument(values);
auto heads_r = dev->global_argument(heads);
auto expected = compact(values, heads);
uref data_r;
// computations
scoped_actor self{system};
self->send(sc_count, heads_r, as_uval(heads_r.size()));
self->receive([&](uref& blocks, uref& heads) {
self->send(scan1, blocks, as_uval(blocks.size()));
heads_r = heads;
});
self->receive([&](uref& data, uref& incs) {
self->send(scan2, data, incs, as_uval(incs.size()));
});
self->receive([&](uref& data, uref& incs) {
self->send(scan3, data, incs, as_uval(data.size()));
});
self->receive([&](uref& results) {
self->send(sc_move, values_r, heads_r, results, as_uval(values_r.size()));
});
self->receive([&](uref& size, uref&, uref& data, uref&, uref&) {
auto size_exp = size.data();
auto num = (*size_exp)[0];
auto exp = data.data(num);
auto actual = std::move(*exp);
cout << (expected != actual ? "FAILURE" : "SUCCESS") << endl;
});
}
// clean up
system.await_all_actors_done();
}
CAF_MAIN()
| 34.643357 | 98 | 0.552382 | josephnoir |
acd046ee059426ae791159e5ed3a53fd19cfc83e | 3,632 | cpp | C++ | dp/sg/ui/manipulator/src/FlightCameraManipulatorHIDSync.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 217 | 2015-01-06T09:26:53.000Z | 2022-03-23T14:03:18.000Z | dp/sg/ui/manipulator/src/FlightCameraManipulatorHIDSync.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 10 | 2015-01-25T12:42:05.000Z | 2017-11-28T16:10:16.000Z | dp/sg/ui/manipulator/src/FlightCameraManipulatorHIDSync.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 44 | 2015-01-13T01:19:41.000Z | 2022-02-21T21:35:08.000Z | // Copyright NVIDIA Corporation 2010
// 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 NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <dp/sg/ui/manipulator/FlightCameraManipulatorHIDSync.h>
namespace dp
{
namespace sg
{
namespace ui
{
namespace manipulator
{
FlightCameraManipulatorHIDSync::FlightCameraManipulatorHIDSync( const dp::math::Vec2f & sensitivity )
: FlightCameraManipulator( sensitivity )
, PID_Pos(0)
, PID_Wheel(0)
, PID_Forward(0)
, PID_Reverse(0)
, m_speed(1.f)
{
}
FlightCameraManipulatorHIDSync::~FlightCameraManipulatorHIDSync()
{
}
bool FlightCameraManipulatorHIDSync::updateFrame( float dt )
{
if (!m_hid)
{
return false;
}
setCursorPosition( m_hid->getValue<dp::math::Vec2i>( PID_Pos ) );
setWheelTicks( m_hid->getValue<int>( PID_Wheel ) );
bool forward = m_hid->getValue<bool>( PID_Forward );
bool reverse = m_hid->getValue<bool>( PID_Reverse );
// set speed based on wheel and buttons
m_speed += getWheelTicksDelta() * 0.1f;
if( m_speed < 0.f )
{
m_speed = 0.f;
}
if( forward || reverse )
{
// set forward, reverse here
FlightCameraManipulator::setSpeed( forward ? m_speed : -m_speed );
}
else
{
// stopped
FlightCameraManipulator::setSpeed( 0.f );
}
return FlightCameraManipulator::updateFrame( dt );
}
void FlightCameraManipulatorHIDSync::setHID( HumanInterfaceDevice *hid )
{
m_hid = hid;
PID_Pos = m_hid->getProperty( "Mouse_Position" );
PID_Forward = m_hid->getProperty( "Mouse_Left" );
PID_Reverse = m_hid->getProperty( "Mouse_Middle" );
PID_Wheel = m_hid->getProperty( "Mouse_Wheel" );
}
} // namespace manipulator
} // namespace ui
} // namespace sg
} // namespace dp
| 35.960396 | 110 | 0.627753 | asuessenbach |
acd1919f833609fcc07594346191cfa8d2f00d16 | 2,156 | cpp | C++ | examples/gestures/Canvas.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | examples/gestures/Canvas.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | examples/gestures/Canvas.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /**
* A Gesture Recognition system in C++
* This library is based on the following paper:
*
* Wobbrock, J, Wilson, A, Li, Y 2007
* Gestures without Libraries, Toolkits or Training:
* A $1 Recognizer for User Interface Prototypes
* UIST 2007
*
* @author Michael Marner (marnermr@cs.unisa.edu.au)
*/
#include "Canvas.h"
#include "GestureIO.h"
#include <QPainter>
using namespace wcl;
Canvas::Canvas()
{
recording = false;
tracking = false;
}
void Canvas::mousePressEvent(QMouseEvent *event)
{
qDebug("mousePressed");
tracking = true;
}
void Canvas::mouseReleaseEvent(QMouseEvent *event)
{
qDebug("mouseReleased");
tracking = false;
//prepare the pointlist that we just recorded
PointList points = gEngine.prepare(lineList);
qDebug("have prepared the points");
if (recording)
{
//save gesture
if (gestureName != "")
{
gIO.saveGesture(points, gestureName.toAscii().constData());
gEngine.addTemplate(points, gestureName.toAscii().constData());
}
recording = false;
emit gestureRecognised("");
}
else
{
//recognise gesture
std::string gesture = gEngine.recognise(points);
emit gestureRecognised(QString(gesture.c_str()));
qDebug("%s",gesture.c_str());
}
//clear our line list and repaint
lineList.clear();
this->repaint();
}
void Canvas::mouseMoveEvent(QMouseEvent *event)
{
//if we are currently tracking, push the current mouse location onto
//our linelist
if (tracking)
{
lineList.push_back(Point(event->x(), event->y()));
this->repaint();
}
}
void Canvas::paintEvent(QPaintEvent *event)
{
/*
* Draw each line that we currently have
*/
if (lineList.size() > 0)
{
QPainter p(this);
PointList::iterator it = lineList.begin();
Point first = *it;
it++;
for (;it<lineList.end();it++)
{
Point p2 = *it;
p.drawLine(first[0], first[1], p2[0], p2[1]);
first = p2;
}
}
}
void Canvas::startRecording()
{
this->recording = true;
//This is a hack to get the status bar to display when we are
//recording. Really this should be a different signal.
emit gestureRecognised("RECORDING");
}
void Canvas::setGestureName(QString name)
{
this->gestureName = name;
}
| 19.779817 | 69 | 0.684601 | WearableComputerLab |
acd40d0d2213ae5664925e8dbc79e1e387a18863 | 1,396 | cpp | C++ | Plugins/GStreamer/Source/GStreamer/Private/GStreamerModule.cpp | kevinrev26/UnrealGAMS | 74b53f5d0e52bd8826e5991192a62cc04547d93e | [
"BSD-3-Clause"
] | 7 | 2019-02-19T23:28:25.000Z | 2021-09-06T16:23:49.000Z | Plugins/GStreamer/Source/GStreamer/Private/GStreamerModule.cpp | kevinrev26/UnrealGAMS | 74b53f5d0e52bd8826e5991192a62cc04547d93e | [
"BSD-3-Clause"
] | 1 | 2019-02-19T21:46:07.000Z | 2019-02-19T21:46:07.000Z | Plugins/GStreamer/Source/GStreamer/Private/GStreamerModule.cpp | racsoraul/UnrealGAMS | 3931d6d45ddc7aed7acf941740bd60250e9db196 | [
"BSD-3-Clause"
] | 8 | 2019-02-18T18:00:25.000Z | 2019-07-12T19:33:36.000Z | #include "GStreamerModule.h"
#include "GstCoreImpl.h"
#include "SharedUnreal.h"
#include "Runtime/Core/Public/Misc/Paths.h"
class FGStreamerModule : public IGStreamerModule
{
public:
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
DEFINE_LOG_CATEGORY(LogGStreamer);
static FString GetGstRoot()
{
const int32 BufSize = 2048;
TCHAR RootPath[BufSize] = {0};
FPlatformMisc::GetEnvironmentVariable(TEXT("GSTREAMER_ROOT_X86_64"), RootPath, BufSize);
if (!RootPath[0])
{
FPlatformMisc::GetEnvironmentVariable(TEXT("GSTREAMER_ROOT"), RootPath, BufSize);
}
return FString(RootPath);
}
void FGStreamerModule::StartupModule()
{
GST_LOG_DBG(TEXT("StartupModule"));
INIT_PROFILER;
FString RootPath = GetGstRoot();
FString BinPath = FPaths::Combine(RootPath, TEXT("bin"));
FString PluginPath = FPaths::Combine(RootPath, TEXT("lib"), TEXT("gstreamer-1.0"));
GST_LOG_DBG(TEXT("GStreamer: GSTREAMER_ROOT=\"%s\""), *RootPath);
if (FGstCoreImpl::Init(TCHAR_TO_ANSI(*BinPath), TCHAR_TO_ANSI(*PluginPath)))
{
GST_LOG_DBG(TEXT("GStreamer: Init SUCCESS"));
}
else
{
GST_LOG_ERR(TEXT("GStreamer: Init FAILED"));
}
}
void FGStreamerModule::ShutdownModule()
{
GST_LOG_DBG(TEXT("ShutdownModule"));
FGstCoreImpl::Deinit();
SHUT_PROFILER;
}
IMPLEMENT_MODULE(FGStreamerModule, GStreamer)
| 22.885246 | 90 | 0.7149 | kevinrev26 |
acd7897e769aab58bcc5ae81e2e9dd3515cf1ad6 | 2,207 | cpp | C++ | software/zynq/Synthesizer/src/TGFReader.cpp | EPiCS/soundgates | a6014d6a68fa209703d749ffe21a1e58b9279d30 | [
"MIT"
] | null | null | null | software/zynq/Synthesizer/src/TGFReader.cpp | EPiCS/soundgates | a6014d6a68fa209703d749ffe21a1e58b9279d30 | [
"MIT"
] | 1 | 2017-04-10T10:57:53.000Z | 2017-04-10T10:57:53.000Z | software/zynq/Synthesizer/src/TGFReader.cpp | EPiCS/soundgates | a6014d6a68fa209703d749ffe21a1e58b9279d30 | [
"MIT"
] | 3 | 2016-09-12T14:08:20.000Z | 2021-03-22T20:07:34.000Z | /*
* TGFReader.cpp
*
* Created on: Nov 29, 2013
* Author: lukas
*/
#include "TGFReader.h"
TGFReader::TGFReader(){ }
TGFReader::~TGFReader(){ }
void TGFReader::normalize(vector<string>& params){
for(vector<string>::iterator iter = params.begin(); iter != params.end(); ++iter ){
boost::algorithm::erase_first((*iter), "'");
boost::algorithm::erase_last((*iter), "'");
LOG_DEBUG("Normalizing token " << *iter);
}
}
void TGFReader::read(Patch* patch, string filename){
string line;
vector<string> linetokens;
ifstream sgfile(filename.c_str());
if(!sgfile.good()){
LOG_ERROR("input file does not exist");
return;
}
boost::regex nodexpr("([0-9]+)[[:space:]]+([a-z]+)/([a-z]+)(\\(([0-9]+)\\))?(/('.*',?)+)?");
boost::regex edgeexpr("([0-9]+)[[:space:]]+([0-9]+)[[:space:]]+'[[:space:]]*([0-9]+)[[:space:]]*,[[:space:]]*([0-9]+)[[:space:]]*'");
boost::smatch match;
while(sgfile){
getline(sgfile, line);
boost::trim(line);
/* match node */
if (boost::regex_match(line, match, nodexpr)){
int uid = boost::lexical_cast<int>(match[1]);
string type = match[2];
string impltype = match[3];
string params = match[7];
vector<string> paramtokens;
boost::split(paramtokens, params, boost::is_any_of(","));
normalize(paramtokens);
if(!impltype.compare(SoundComponents::ImplTypeNames[SoundComponents::HW])){
int slot = boost::lexical_cast<int>(match[5]);
patch->createSoundComponent(uid, type, paramtokens, slot);
}else if(!impltype.compare(SoundComponents::ImplTypeNames[SoundComponents::SW])){
patch->createSoundComponent(uid, type, paramtokens);
}else{
throw std::invalid_argument("Unknown implementation type");
}
}
/* match edge */
if (boost::regex_match(line, match, edgeexpr)){
int source_uid = boost::lexical_cast<int>(match[1]);
int dest_uid = boost::lexical_cast<int>(match[2]);
int source_port = boost::lexical_cast<int>(match[3]);
int dest_port = boost::lexical_cast<int>(match[4]);
try{
patch->createLink(source_uid, source_port, dest_uid, dest_port);
}catch(std::exception& e){
LOG_ERROR("Exception: " << e.what());
}
}
}
}
| 21.851485 | 134 | 0.624377 | EPiCS |
acdc41f45d220f0e49dc58fbee296d41adf55335 | 363 | hpp | C++ | dialogs/loadMenu/dialogs.hpp | Kortonki/antistasi_remastered | 11c005467d8efb7c709621c00d9b16ae1a5f3be2 | [
"BSD-3-Clause"
] | null | null | null | dialogs/loadMenu/dialogs.hpp | Kortonki/antistasi_remastered | 11c005467d8efb7c709621c00d9b16ae1a5f3be2 | [
"BSD-3-Clause"
] | 26 | 2020-05-15T14:38:08.000Z | 2021-06-28T18:26:53.000Z | dialogs/loadMenu/dialogs.hpp | Kortonki/antistasi_remastered | 11c005467d8efb7c709621c00d9b16ae1a5f3be2 | [
"BSD-3-Clause"
] | null | null | null | class AS_loadMenu
{
idd=1601;
movingenable=false;
class controls
{
AS_DIALOG(5,"Load game", "[] spawn AS_fnc_UI_loadMenu_close;");
LIST_L(0,1,0,4,"");
BTN_L(5,-1,"Delete selected", "Delete the selected saved game", "[] spawn AS_fnc_UI_loadMenu_delete;");
BTN_R(5,-1,"Load game", "Load the selected saved game", "[] spawn AS_fnc_UI_loadMenu_load;");
};
};
| 22.6875 | 103 | 0.699725 | Kortonki |
acdc6e0c949c8ae6caf265e2497c4d6c7e1d24c9 | 3,033 | cpp | C++ | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pH.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pH.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/bcw_codebook-master/Contest/XVIOpenCupJapan/pH.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define REP(i,x) for (int i=0; i<(x); i++)
#define REP1(i,a,b) for (int i=(a); i<=(b); i++)
#ifdef ONLINE_JUDGE
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#else
#define FILEIO(name)
#endif
template<typename A, typename B>
ostream& operator <<(ostream &s, const pair<A,B> &p) {
return s<<"("<<p.first<<","<<p.second<<")";
}
template<typename T>
ostream& operator <<(ostream &s, const vector<T> &c) {
s<<"[ ";
for (auto it : c) s << it << " ";
s<<"]";
return s;
}
// Let's Fight!
#define loop(i, a, b) for (auto (i) = (a); (i) != (b); (i) += (((a) < (b) ? 1 : -1)))
typedef pair<int, int> pii;
const int MAXN = 303;
const int MXN = MAXN;
const double INF = 1E20;
const double HHHHH = 10000;
const double EPS = 1E-8;
double getdis(pii a, pii b)
{
int dx = a.F - b.F, dy = a.S - b.S;
return sqrt(dx*dx + dy*dy);
}
int N;
pii ps[MAXN], pt[MAXN];
struct KM{
// Maximum Bipartite Weighted Matching (Perfect Match)
int n,match[MXN],vx[MXN],vy[MXN];
double edge[MXN][MXN],lx[MXN],ly[MXN],slack[MXN];
// ^^^^ long long
void init(int _n){
n = _n;
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
edge[i][j] = 0;
}
void add_edge(int x, int y, double w){ // long long
edge[x][y] = w;
}
bool DFS(int x){
vx[x] = 1;
for (int y=0; y<n; y++){
if (vy[y]) continue;
if (lx[x]+ly[y] > edge[x][y] + EPS){
slack[y] = min(slack[y], lx[x]+ly[y]-edge[x][y]);
} else {
vy[y] = 1;
if (match[y] == -1 || DFS(match[y])){
match[y] = x;
return true;
}
}
}
return false;
}
double solve(){
fill(match,match+n,-1);
fill(lx,lx+n,-INF);
fill(ly,ly+n,0);
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
lx[i] = max(lx[i], edge[i][j]);
for (int i=0; i<n; i++){
fill(slack,slack+n,INF);
while (true){
fill(vx,vx+n,0);
fill(vy,vy+n,0);
if ( DFS(i) ) break;
double d = INF; // long long
for (int j=0; j<n; j++)
if (!vy[j]) d = min(d, slack[j]);
for (int j=0; j<n; j++){
if (vx[j]) lx[j] -= d;
if (vy[j]) ly[j] += d;
else slack[j] -= d;
}
}
}
double res=0;
for (int i=0; i<n; i++)
res += edge[match[i]][i];
return res;
}
}graph;
double calc()
{
double ans = 0;
for(int i=0; i<N; i++)
ans += getdis(ps[i], pt[i]);
graph.init(N);
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
graph.add_edge(i, j, -getdis(ps[i], pt[j]) + HHHHH);
double res = graph.solve() - HHHHH * N;
ans -= res;
return ans;
}
int main() {
IOS;
cin>>N;
pii trash;
cin>>trash.F>>trash.S;
for(int i=0; i<N; i++)
cin>>ps[i].F>>ps[i].S>>pt[i].F>>pt[i].S;
double ans = calc();
cout<<fixed<<setprecision(12)<<ans<<endl;
return 0;
}
| 20.917241 | 85 | 0.536433 | daemonslayer |
acdcb8043ea1a66f833c1f5574ff78cf610e7fe3 | 1,335 | cpp | C++ | old/old_vinput.cpp | ron2015schmitt/COOLL | 5516714e5fea6d73e0b2eaa8c04876e5e54ef355 | [
"MIT"
] | 1 | 2019-08-17T00:30:22.000Z | 2019-08-17T00:30:22.000Z | old/old_vinput.cpp | ron2015schmitt/COOLL | 5516714e5fea6d73e0b2eaa8c04876e5e54ef355 | [
"MIT"
] | null | null | null | old/old_vinput.cpp | ron2015schmitt/COOLL | 5516714e5fea6d73e0b2eaa8c04876e5e54ef355 | [
"MIT"
] | null | null | null |
// flag for run-time bounds and size checking
#define MATHQ_DEBUG 1
#include "mathq.h"
using namespace mathq;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int N = 4;
Vector<double> v1(N,"vec1");
Vector<double> v2(N,"vec2");
Vector<double> v3(N,"vec3");
DISP(v1);
DISP(v2);
DISP(v3);
// intitiliaze a vector using a string
"{1,2,3,4}">>v1;
DISP(v1);
// once the vector is filled, the oepration ends
"{100,200,300,400} {1,2,3,3,4,5,5,6,6}">>v1;
DISP(v1);
// so you can initialize several vectors at once
"{1,2,3,4} {5,6,7,8}{9,10,11,12}">>v1>>v2>>v3;
DISP(v1);
DISP(v2);
DISP(v3);
// white space is irrelavent
" { -1, -2 , -3, -4} \n{ 21 , 22,\n23,24 } ">>v1>>v2;
DISP(v1);
DISP(v2);
// of course you can use any stream to intialize
istringstream strm;
strm.str("{11,12,13,14}");
strm >> v1;
DISP(v1);
// can input strings of numbers separated by white space "no braces or commas"
v1.textformat(text_nobraces);
"1 2.2 3.3 4.4">>v1;
DISP(v1);
v1.textformat(text_braces);
DISP(v1);
v1.textformat(text_nobraces);
v2.textformat(text_nobraces);
" -1 -2 -3 -4 56 57 58 59 100 101 ">>v1>>v2;
DISP(v1);
DISP(v2);
// can also use streams from files; see examples in fileio.cpp
return 0;
}
| 16.280488 | 80 | 0.606742 | ron2015schmitt |
acdf0c5876147daab059a3e5bcb48643137dc070 | 958 | cpp | C++ | Userland/Demos/ModelGallery/main.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 650 | 2019-03-01T13:33:03.000Z | 2022-03-15T09:26:44.000Z | Userland/Demos/ModelGallery/main.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 51 | 2019-04-03T08:32:38.000Z | 2019-05-19T13:44:28.000Z | Userland/Demos/ModelGallery/main.cpp | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 33 | 2019-03-26T05:47:59.000Z | 2021-11-22T18:18:45.000Z | /*
* Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "GalleryWidget.h"
#include <LibGUI/Application.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/Frame.h>
#include <LibGUI/MessageBox.h>
#include <unistd.h>
int main(int argc, char** argv)
{
if (pledge("stdio recvfd sendfd rpath wpath cpath unix", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app = GUI::Application::construct(argc, argv);
if (pledge("stdio recvfd sendfd rpath", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app_icon = GUI::Icon::default_icon("app-model-gallery");
auto window = GUI::Window::construct();
window->set_title("Model Gallery");
window->set_icon(app_icon.bitmap_for_size(16));
window->resize(430, 480);
window->set_main_widget<GalleryWidget>();
window->show();
return app->exec();
}
| 23.95 | 76 | 0.646138 | TheCrott |
acdfb7986a63e425ad08820c50aa0b34dbb63dac | 28,026 | cpp | C++ | docs/simple.cpp | ief015/libfada | 97dc34a96fd3a6fb454680303229b6295ef3d28a | [
"Zlib"
] | null | null | null | docs/simple.cpp | ief015/libfada | 97dc34a96fd3a6fb454680303229b6295ef3d28a | [
"Zlib"
] | null | null | null | docs/simple.cpp | ief015/libfada | 97dc34a96fd3a6fb454680303229b6295ef3d28a | [
"Zlib"
] | null | null | null | /***********************************************************
** libfada Full Example Visualizer
** Written by Nathan Cousins - December 2013
**
** Usage: full_visualizer <audio_filepath>
** `audio_filepath' may be any filetype supported by SFML/libsndfile.
***********************************************************/
//////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////
#include <stdio.h>
#include <string>
#include <vector>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <fada/fada.hpp>
#if defined(_WIN32) || defined(__WIN32__)
#include <Windows.h>
#include <Shlwapi.h>
#ifndef _WINDOWS_
#define _WINDOWS_
#endif
#endif
//////////////////////////////////////////////////
// Declarations
//////////////////////////////////////////////////
class AudioAnalyzer;
class AudioFileStream;
sf::RenderWindow* rw = NULL;
AudioFileStream* audio = NULL;
sf::Time continueInterval, nextContinue;
bool isRunning;
sf::Mutex mutex;
const unsigned WINDOW_BUFFER_SIZE = 2048;
const unsigned FFT_BUFFER_SIZE = WINDOW_BUFFER_SIZE * 2;
fada_Res resultBuffer[WINDOW_BUFFER_SIZE];
sf::CircleShape orbBeat, orbBass;
sf::VertexArray vertexArray;
struct FreqBar {
fada_Res value;
double linePos, lineVel;
};
const unsigned NUM_FREQBARS = 12;
FreqBar freqBars[NUM_FREQBARS];
enum {
DRAW_NONE,
DRAW_FFT,
DRAW_WAVEFORM,
DRAW_FFT_MIXED,
DRAW_WAVEFORM_MIXED
} drawMode;
bool showSubBands;
bool showOrbs;
bool debugMode;
double debugFPS, debugMS;
sf::Font* fontDebug;
sf::Text txtDebug;
bool mouseHoverProgressBar;
// Application loop sub-routines.
bool initialize(const std::string& filename);
void finish();
void processEvents();
void tick(float ms);
void render();
// Utility functions.
fada_Res calcFreqBar(fada_Pos start, fada_Pos end);
// User events.
void onMouseDown(int x, int y, unsigned b);
void onMouseUp(int x, int y, unsigned b);
void onMouseWheel(int x, int y, int d);
void onMouseMove(int x, int y, int dx, int dy);
void onKeyDown(int key);
void onKeyUp(int key);
void onWindowResize(unsigned w, unsigned h);
void onWindowClose();
// Logging functions.
void logMessage(const char* func, const char* fmt, ...);
void logWarning(const char* func, const char* fmt, ...);
void logError(const char* func, const char* fmt, ...);
// FADA error checking.
fada_Error checkFADA(unsigned int line, fada_Error err);
#ifndef NDEBUG
#define CHECK_FADA(x) checkFADA(__LINE__, (x))
#else
#define CHECK_FADA(x) (x)
#endif
// Base class for audio analyzation via libfada.
class AudioAnalyzer
{
private:
bool m_fadaLoaded;
fada_Res m_beat, m_bass, m_normal;
protected:
std::vector<fada_FFTBuffer*> m_buffers;
fada_FFTBuffer* m_mixedBuffer;
fada_Manager* m_fada;
void setup(unsigned int sampleRate, unsigned int channelCount)
{
fada_Error err;
m_fadaLoaded = false;
// Set up our FADA manager.
err = CHECK_FADA(fada_bindstream(m_fada, FADA_TSAMPLE_INT16, sampleRate, channelCount));
if (err != FADA_ERROR_SUCCESS)
{
logError("AudioFileStream::onGetData", "could not initialize stream (manager=0x%p, rate=%d, channels=%d, error=%d)\n", m_fada, sampleRate, channelCount, err);
return;
}
// Set up the analyzation window to 2048 frames.
err = CHECK_FADA(fada_setwindowframes(m_fada, WINDOW_BUFFER_SIZE));
if (err != FADA_ERROR_SUCCESS)
{
logWarning("AudioFileStream::onGetData", "could not set window size to 2048 (manager=0x%p, error=%d)\n", m_fada, err);
}
// Close any current buffers before making new ones.
this->closeBuffers();
// Set up FFT buffers.
for (unsigned int i = 0; i < channelCount; ++i)
{
m_buffers.push_back(fada_newfftbuffer(FFT_BUFFER_SIZE));
}
m_mixedBuffer = fada_newfftbuffer(FFT_BUFFER_SIZE);
m_normal = fada_getnormalizer(m_fada);
m_fadaLoaded = true;
}
void closeBuffers()
{
// Close buffers.
if (m_mixedBuffer)
fada_closefftbuffer(m_mixedBuffer);
m_mixedBuffer = NULL;
for (size_t i = 0, sz = m_buffers.size(); i < sz; ++i)
fada_closefftbuffer(m_buffers[i]);
m_buffers.clear();
// For added security, tell the manager that no FFT buffer is in use.
CHECK_FADA(fada_usefftbuffer(m_fada, NULL));
}
public:
AudioAnalyzer()
{
m_fadaLoaded = false;
m_beat = 0.;
m_bass = 0.;
m_normal = 1.;
m_mixedBuffer = NULL;
m_fada = fada_newmanager();
}
virtual ~AudioAnalyzer()
{
// Close our FFT buffers.
this->closeBuffers();
// Close manager.
fada_closemanager(m_fada);
}
bool isReady() const
{
return m_fadaLoaded;
}
fada_Error pushSamples(const sf::Int16* samples, size_t sampleCount)
{
// Remove old sample data from the manager.
fada_trimchunks(m_fada);
// Push a new chunk of samples into the manager.
return CHECK_FADA(fada_pushsamples(m_fada, (void*)samples, sampleCount, FADA_TRUE));
}
void update()
{
if (!m_fadaLoaded)
return;
// Calculate beat and audible bass.
CHECK_FADA(fada_calcbeat(m_fada, &m_beat));
m_beat /= m_normal;
CHECK_FADA(fada_calcbass(m_fada, &m_bass));
m_bass /= m_normal;
// Generate a mixed FFT on the mixed buffer.
CHECK_FADA(fada_usefftbuffer(m_fada, m_mixedBuffer));
CHECK_FADA(fada_calcfft(m_fada));
// Generate a channel-specific FFT on each buffer.
for (size_t i = 0, sz = m_buffers.size(); i < sz; ++i)
{
CHECK_FADA(fada_usefftbuffer(m_fada, m_buffers[i]));
CHECK_FADA(fada_calcfft_channel(m_fada, i));
}
}
bool advance(long advanceFrames = FADA_NEXT_WINDOW)
{
return fada_continue(m_fada, advanceFrames) == FADA_TRUE;
}
fada_Res getBeat() const
{
return m_beat;
}
fada_Res getBass() const
{
return m_bass;
}
fada_Res getFFTValue(fada_Pos pos) const
{
// Get FFT value.
fada_Res res;
CHECK_FADA(fada_getfftvalue(m_fada, pos, &res));
return res;
}
void getFFTValues(fada_Res* out, fada_Pos offset = 0, fada_Pos length = 0)
{
// Get all FFT values.
if (offset == 0 && length == 0)
CHECK_FADA(fada_getfftvalues(m_fada, out));
// Get all `length' FFT values starting from offset.
else
CHECK_FADA(fada_getfftvaluesrange(m_fada, out, offset, length));
}
const fada_Res getNormal() const
{
return m_normal;
}
void useFFTBuffer(unsigned int channel)
{
if (channel >= m_buffers.size())
{
logWarning("AudioAnalyzer::useFFTBuffer", "invalid channel selected, must be below buffer count (manager=0x%p, channel=%d, buffers=%d)\n", m_fada, channel, m_buffers.size());
return;
}
// Use this buffer for grabbing values from getFFTValue()
CHECK_FADA(fada_usefftbuffer(m_fada, m_buffers[channel]));
}
void useFFTMixedBuffer()
{
// Use the mixed buffer for grabbing values from getFFTValue()
CHECK_FADA(fada_usefftbuffer(m_fada, m_mixedBuffer));
}
fada_Manager* getManager()
{
return m_fada;
}
const fada_Manager* getManager() const
{
return m_fada;
}
};
// Used for streaming an audio file, using SFML's Music class to stream sample chunks.
class AudioFileStream : public sf::Music, public AudioAnalyzer
{
protected:
virtual void onSeek(sf::Time timeOffset)
{
//sf::Lock lock(mutex);
sf::Music::onSeek(timeOffset);
logMessage("AudioFileStream::onSeek", "seeking... (sec=%.2f)\n", timeOffset.asSeconds());
fada_freechunks(m_fada);
}
virtual bool onGetData(sf::SoundStream::Chunk& chunk)
{
fada_Error err;
if (sf::Music::onGetData(chunk))
{
sf::Lock lock(mutex);
// Is this our first chunk?
// Also make sure that audio information is still valid. This may change when changing audio sources.
if (!this->isReady() ||
fada_getchannels(m_fada) != this->getChannelCount() ||
fada_getsamplerate(m_fada) != this->getSampleRate() )
{
this->setup(this->getSampleRate(), this->getChannelCount());
}
err = this->pushSamples(chunk.samples, chunk.sampleCount);
if (err != FADA_ERROR_SUCCESS)
logError("AudioFileStream::onGetData", "could not push samples (chunk=0x%p, count=%d, error=%d)\n", chunk.samples, chunk.sampleCount, err);
return true;
}
return false;
}
};
//////////////////////////////////////////////////
// Definitions
//////////////////////////////////////////////////
//////////////////////////////////////////////////
int main(int argc, char* args[])
{
const float TICKRATE = 1.f/60;
std::string filename = "";
if (argc > 1)
filename = args[1];
isRunning = initialize(filename);
if (!isRunning)
return 1;
sf::Clock clkFPS = sf::Clock();
sf::Clock clkMS = sf::Clock();
sf::Clock clk = sf::Clock();
sf::Time clkTime;
do
{
processEvents();
while ((clkTime += clk.restart()) >= sf::seconds(TICKRATE))
{
clkMS.restart();
clkTime -= sf::seconds(TICKRATE);
tick(TICKRATE*1000.f);
debugMS = clkMS.getElapsedTime().asMicroseconds() / 1000.;
}
render();
debugFPS = 1000. / (clkFPS.restart().asMicroseconds() / 1000.);
sf::sleep(sf::milliseconds(1));
} while (isRunning);
finish();
return 0;
}
//////////////////////////////////////////////////
bool initialize(const std::string& filename)
{
sf::Lock lock(mutex);
std::string title = "Example libfada Visualizer";
#ifdef _WINDOWS_
// Force application to use root executable directory on Windows.
{
char strPath[MAX_PATH];
GetModuleFileName(NULL, strPath, MAX_PATH);
std::string strExePathS = strPath;
size_t found = strExePathS.find_last_of("/\\");
strExePathS = strExePathS.substr(0,found);
SetCurrentDirectory(strExePathS.c_str());
title += " - ";
if (PathCompactPathEx(strPath, filename.c_str(), 64, NULL))
{
title += strPath;
}
else
{
title += filename;
}
}
#else
title += " - ";
title += filename;
#endif
// Create and open a new SFML window.
rw = new sf::RenderWindow();
rw->create(sf::VideoMode(800, 600), title, sf::Style::Default, sf::ContextSettings(16, 0, 4));
// Setup VA for drawing the waveforms/transforms.
vertexArray.resize(WINDOW_BUFFER_SIZE);
vertexArray.setPrimitiveType(sf::LinesStrip);
// Corner beat/bass orbs.
orbBeat = sf::CircleShape(1.f, 60u);
orbBass = sf::CircleShape(1.f, 60u);
orbBeat.setPosition(0.f, (float)rw->getSize().y);
orbBass.setPosition((float)rw->getSize().x, (float)rw->getSize().y);
orbBeat.setOrigin(1.f, 1.f);
orbBass.setOrigin(1.f, 1.f);
orbBeat.setFillColor(sf::Color(255, 180, 0, 200));
orbBass.setFillColor(sf::Color(0, 180, 255, 200));
// Frequency subbands.
for (unsigned i = 0; i < NUM_FREQBARS; ++i)
{
freqBars[i].value = 0.;
freqBars[i].linePos = 0.;
freqBars[i].lineVel = 0.;
}
// Set up font so we can render text.
fontDebug = new sf::Font();
if (!fontDebug->loadFromFile("font.ttf"))
logWarning("initialize", "unable to load font file (filename=\"%s\"), file may be corrupted, unreadable, an invalid format, or not exist\n", "font.ttf");
// Set up debug text.
txtDebug.setFont(*fontDebug);
txtDebug.setPosition(10.f, 10.f);
txtDebug.setCharacterSize(14);
// Let SFML decode the audio file if it isn't an mp3.
// SFML will use streaming to load the audio.
audio = new AudioFileStream();
if (!audio->openFromFile(filename))
return false;
// Update every 1024 samples.
continueInterval = sf::seconds(1024.f / audio->getSampleRate());
nextContinue = continueInterval;
// Initialize everything else.
showSubBands = true;
showOrbs = true;
drawMode = DRAW_FFT;
debugMode = false;
mouseHoverProgressBar = false;
// Some controls information.
printf("libfada - Example Visualizer\n");
printf("Playing '%s'\n", filename.c_str());
printf("Left-click on the progress bar at the bottom of the screen to seek.\n");
printf("\n");
printf("[0]\tNone\n");
printf("[1]\tStereo FFT (if applicable)\n");
printf("[2]\tStereo waveform (if applicable)\n");
printf("[3]\tMixed FFT\n");
printf("[4]\tMixed waveform\n");
printf("\n");
printf("[I]\tToggle subband bars\n");
printf("[O]\tToggle orbs\n");
printf("[~]\tToggle debug mode\n");
printf("\n");
// Start the audio.
audio->play();
return true;
}
//////////////////////////////////////////////////
void finish()
{
sf::Lock lock(mutex);
if (audio)
{
audio->stop();
delete audio;
}
if (fontDebug)
delete fontDebug;
if (rw)
{
if (rw->isOpen())
rw->close();
delete rw;
}
}
//////////////////////////////////////////////////
void processEvents()
{
sf::Lock lock(mutex);
sf::Event ev;
while (rw->pollEvent(ev))
switch(ev.type)
{
case sf::Event::Closed:
onWindowClose();
break;
case sf::Event::Resized:
onWindowResize(ev.size.width, ev.size.height);
break;
case sf::Event::MouseButtonPressed:
onMouseDown(ev.mouseButton.x, ev.mouseButton.y, ev.mouseButton.button);
break;
case sf::Event::MouseButtonReleased:
onMouseUp(ev.mouseButton.x, ev.mouseButton.y, ev.mouseButton.button);
break;
case sf::Event::MouseMoved:
{
static int px = ev.mouseMove.x, py = ev.mouseMove.y;
onMouseMove(ev.mouseMove.x, ev.mouseMove.y, ev.mouseMove.x - px, ev.mouseMove.y - py);
px = ev.mouseMove.x;
py = ev.mouseMove.y;
} break;
case sf::Event::MouseWheelMoved:
onMouseWheel(ev.mouseWheel.x, ev.mouseWheel.y, ev.mouseWheel.delta);
break;
case sf::Event::KeyPressed:
onKeyDown(ev.key.code);
break;
case sf::Event::KeyReleased:
onKeyUp(ev.key.code);
break;
}
}
//////////////////////////////////////////////////
void tick(float ms)
{
sf::Lock lock(mutex);
static bool updateReady = true;
const float SCRW = static_cast<float>(rw->getSize().x);
const float SCRH = static_cast<float>(rw->getSize().y);
if (!audio->isReady())
return;
if (updateReady)
{
// Update FADA beat, bass and FFT.
audio->update();
// Update sub-band values.
const fada_Res FACTOR = 1.0;
audio->useFFTMixedBuffer();
freqBars[11].value = calcFreqBar(0, 3) / FACTOR; // 0 - 43 Hz
freqBars[10].value = calcFreqBar(4, 7) / FACTOR; // 43 - 86 Hz
freqBars[9].value = calcFreqBar(8, 15) / FACTOR; // 86 - 167 Hz
freqBars[8].value = calcFreqBar(16, 31) / FACTOR; // 167 - 344 Hz
freqBars[7].value = calcFreqBar(32, 63) / FACTOR; // 344 - 689 Hz
freqBars[6].value = calcFreqBar(64, 127) / FACTOR; // 689 - 1378 Hz
freqBars[5].value = calcFreqBar(128, 255) / FACTOR; // 1378 - 2756 Hz
freqBars[4].value = calcFreqBar(256, 511) / FACTOR; // 2756 - 5512 Hz
freqBars[3].value = calcFreqBar(512, 767) / FACTOR; // 5512 - 8268 Hz
freqBars[2].value = calcFreqBar(768, 1023) / FACTOR; // 8268 - 11025 Hz
freqBars[1].value = calcFreqBar(1024, 1535) / FACTOR; // 11025 - 16537 Hz
freqBars[0].value = calcFreqBar(1536, 2047) / FACTOR; // 16537 - 22050 Hz
// Update orbs based on beat and bass values.
orbBeat.setScale(static_cast<float>(audio->getBeat() * 7000.), static_cast<float>(audio->getBeat() * 7000.));
orbBass.setScale(static_cast<float>(audio->getBass() * 700.), static_cast<float>(audio->getBass() * 700.));
updateReady = false;
}
// Update sub-bands.
for (unsigned i = 0; i < NUM_FREQBARS; ++i)
{
FreqBar& bar = freqBars[i];
bar.lineVel += 0.0005;
bar.linePos -= bar.lineVel;
if (bar.linePos < bar.value)
{
bar.linePos = bar.value;
bar.lineVel = 0.;
}
if (bar.linePos < 0.)
{
bar.linePos = 0.;
bar.lineVel = 0.;
}
}
// Move FADA to the next window when audio has finished playing the current set of 1024 samples.
while (audio->getPlayingOffset() >= nextContinue)
{
nextContinue += continueInterval;
audio->advance(1024);
updateReady = true;
}
// Stop program when audio is finished.
if (audio->getStatus() == sf::Music::Stopped)
isRunning = false;
}
//////////////////////////////////////////////////
void render()
{
sf::Lock lock(mutex);
if (!audio->isReady())
return;
const float SCRW = static_cast<float>(rw->getSize().x);
const float SCRH = static_cast<float>(rw->getSize().y);
const float SCRW_H = SCRW / 2.f;
const float SCRH_H = SCRH / 2.f;
const unsigned MAX_CHANNEL_COLOURS = 8;
const sf::Color CHANNEL_COLOURS[MAX_CHANNEL_COLOURS] = {
sf::Color(200, 80, 80),
sf::Color( 80, 80, 200),
sf::Color( 80, 200, 80),
sf::Color(200, 80, 200),
sf::Color(200, 200, 80),
sf::Color( 80, 200, 200),
sf::Color( 80, 80, 80),
sf::Color(200, 200, 200)
};
rw->clear();
// Draw subband bars.
if (showSubBands)
{
for (unsigned i = 0; i < NUM_FREQBARS; ++i)
{
sf::RectangleShape r;
FreqBar& bar = freqBars[i];
double p = bar.linePos * 3.;
p = (p < 0.) ? 0. : (p > 2.) ? 2. : p;
unsigned char red, green;
red = (p >= 1.) ? 255 : static_cast<unsigned char>(floor( p * 255.));
green = (p <= 1.) ? 255 : static_cast<unsigned char>(floor((1.-p) * 255.));
float x, width;
width = (SCRW_H / NUM_FREQBARS) - 10.f;
x = (width + 10.f) * i + 10.f + (SCRW_H / 2.f);
// Draw bar.
r.setSize(sf::Vector2f(width, -static_cast<float>(bar.value * SCRH / 2.) ));
r.setPosition(x, SCRH + 16.f);
r.setFillColor(sf::Color(red, green, 40, 160));
rw->draw(r);
p = bar.linePos * SCRH / 2.;
p = (p < 12.) ? 12. : p;
// Draw falling bar.
r.setSize(sf::Vector2f( (SCRW_H / NUM_FREQBARS) - 10.f, 12.f) );
r.setPosition(x, -static_cast<float>(p) + SCRH);
r.setFillColor(sf::Color(255, 255, 255, 160));
rw->draw(r);
}
}
// Draw beat and bass orbs.
if (showOrbs)
{
rw->draw(orbBeat);
rw->draw(orbBass);
}
// Draw progress bar.
{
float progress = audio->getPlayingOffset().asSeconds() / audio->getDuration().asSeconds();
sf::RectangleShape r;
r.setFillColor(sf::Color(80, 80, 255));
r.setPosition(0.f, SCRH - 6.f);
r.setSize(sf::Vector2f(progress * SCRW, 6.f));
rw->draw(r, sf::RenderStates(sf::BlendAdd));
// Mouse-over highlight.
if (mouseHoverProgressBar)
{
sf::VertexArray va;
va.setPrimitiveType(sf::Quads);
va.resize(4);
va[0].position.x = 0.f;
va[0].position.y = SCRH;
va[1].position.x = SCRW;
va[1].position.y = SCRH;
va[2].position.x = va[1].position.x;
va[2].position.y = va[1].position.y - 16.f;
va[3].position.x = va[0].position.x;
va[3].position.y = va[0].position.y - 16.f;
va[0].color = sf::Color(200, 200, 200);
va[1].color = va[0].color;
va[2].color = sf::Color::Transparent;
va[3].color = va[2].color;
rw->draw(va, sf::RenderStates(sf::BlendAdd));
}
}
// Draw FFT/Waveform.
if (drawMode == DRAW_FFT)
{
// Draw FFTs for each channel.
for (size_t c = 0, chans = audio->getChannelCount(); c < chans && c < MAX_CHANNEL_COLOURS; ++c)
{
audio->useFFTBuffer(c);
audio->getFFTValues(resultBuffer, 0, WINDOW_BUFFER_SIZE);
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz && i < FFT_BUFFER_SIZE; ++i)
{
sf::Vertex& v = vertexArray[i];
v.color = CHANNEL_COLOURS[c];
v.position.x = i / static_cast<float>(sz) * SCRW;
v.position.y = SCRH_H - static_cast<float>(resultBuffer[i] * SCRH * 10);
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
// Mirror Y coodinates.
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz && i < FFT_BUFFER_SIZE; ++i)
{
sf::Vertex& v = vertexArray[i];
v.position.y = SCRH - v.position.y;
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
}
}
else if (drawMode == DRAW_FFT_MIXED)
{
// Draw the mixed-channel FFT.
audio->useFFTMixedBuffer();
audio->getFFTValues(resultBuffer, 0, WINDOW_BUFFER_SIZE);
const sf::Color mixedColour = sf::Color(100, 220, 220);
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz && i < FFT_BUFFER_SIZE; ++i)
{
sf::Vertex& v = vertexArray[i];
v.color = mixedColour;
v.position.x = i / static_cast<float>(sz) * SCRW;
v.position.y = SCRH_H - static_cast<float>(resultBuffer[i] * SCRH * 10);
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
// Mirror Y coodinates.
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz; ++i)
{
sf::Vertex& v = vertexArray[i];
v.position.y = SCRH - v.position.y;
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
}
else if (drawMode == DRAW_WAVEFORM)
{
// Draw waveforms for each channel.
for (size_t c = 0, chans = audio->getChannelCount(); c < chans && c < MAX_CHANNEL_COLOURS; ++c)
{
CHECK_FADA(fada_getsamples(audio->getManager(), c, resultBuffer));
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz; ++i)
{
sf::Vertex& v = vertexArray[i];
v.color = CHANNEL_COLOURS[c];
v.position.x = i / static_cast<float>(sz) * SCRW;
v.position.y = SCRH_H + static_cast<float>(resultBuffer[i] / audio->getNormal()) * (SCRH / 3.f);
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
}
}
else if (drawMode == DRAW_WAVEFORM_MIXED)
{
CHECK_FADA(fada_getframes(audio->getManager(), resultBuffer));
const sf::Color mixedColour = sf::Color(100, 220, 220);
// Mixed channels.
for (size_t i = 0, sz = vertexArray.getVertexCount(); i < sz; ++i)
{
sf::Vertex& v = vertexArray[i];
v.color = mixedColour;
v.position.x = i / static_cast<float>(sz) * SCRW;
v.position.y = SCRH_H + static_cast<float>(resultBuffer[i] / audio->getNormal()) * (SCRH / 3.f);
}
rw->draw(vertexArray, sf::RenderStates(sf::BlendAdd));
}
// Draw debug to display FPS and tick MS.
if (debugMode)
{
char buf[32];
sprintf(buf, "FPS: %.0f\nMS: %.2f", debugFPS, debugMS);
txtDebug.setString(buf);
txtDebug.setColor(sf::Color::Black);
txtDebug.move(1.5f, 1.5f);
rw->draw(txtDebug);
txtDebug.move(-1.5f, -1.5f);
txtDebug.setColor(sf::Color::White);
rw->draw(txtDebug);
}
rw->display();
}
//////////////////////////////////////////////////
fada_Res calcFreqBar(fada_Pos start, fada_Pos end)
{
const fada_Manager* fada = audio->getManager();
fada_Pos fft_sz = fada_getfftsize(fada);
if (start >= fft_sz)
return 0.;
if (end >= fft_sz)
end = fft_sz-1;
fada_Res cur;
fada_Res res = 0.;
for (unsigned i = start; i <= end; ++i)
{
CHECK_FADA(fada_getfftvalue(fada, i, &cur));
res += cur;
}
return res;
}
//////////////////////////////////////////////////
void onMouseDown(int x, int y, unsigned b)
{
#ifdef _WINDOWS_
// Weird SFML 2.1 bug on Windows - force window to focus when clicked on.
::SetFocus(rw->getSystemHandle());
#endif
}
//////////////////////////////////////////////////
void onMouseUp(int x, int y, unsigned b)
{
if (b != sf::Mouse::Left)
return;
// Audio seeking.
if (mouseHoverProgressBar)
{
sf::Time offset = audio->getDuration() * (static_cast<float>(x) / rw->getSize().x);
audio->setPlayingOffset(offset);
nextContinue = offset;
}
}
//////////////////////////////////////////////////
void onMouseWheel(int x, int y, int d)
{
}
//////////////////////////////////////////////////
void onMouseMove(int x, int y, int dx, int dy)
{
mouseHoverProgressBar = ( static_cast<unsigned int>(y) > rw->getSize().y - 32 );
}
//////////////////////////////////////////////////
void onKeyDown(int key)
{
switch (key)
{
// Debug mode.
case sf::Keyboard::Tilde: debugMode = !debugMode; break;
// Show subband bars.
case sf::Keyboard::I: showSubBands = !showSubBands; break;
// Show orbs.
case sf::Keyboard::O: showOrbs = !showOrbs; break;
// Draw modes.
case sf::Keyboard::Num0:
case sf::Keyboard::Numpad0:
drawMode = DRAW_NONE;
break;
case sf::Keyboard::Num1:
case sf::Keyboard::Numpad1:
drawMode = DRAW_FFT;
break;
case sf::Keyboard::Num2:
case sf::Keyboard::Numpad2:
drawMode = DRAW_WAVEFORM;
break;
case sf::Keyboard::Num3:
case sf::Keyboard::Numpad3:
drawMode = DRAW_FFT_MIXED;
break;
case sf::Keyboard::Num4:
case sf::Keyboard::Numpad4:
drawMode = DRAW_WAVEFORM_MIXED;
break;
}
}
//////////////////////////////////////////////////
void onKeyUp(int key)
{
}
//////////////////////////////////////////////////
void onWindowResize(unsigned w, unsigned h)
{
// Modify view to fill the new screen size.
sf::View view = rw->getView();
view.setSize(static_cast<float>(w), static_cast<float>(h));
view.setCenter(w/2.f, h/2.f);
rw->setView(view);
// Reset positions of orbs.
orbBeat.setPosition(0.f, static_cast<float>(rw->getSize().y));
orbBass.setPosition(static_cast<float>(rw->getSize().x), static_cast<float>(rw->getSize().y));
}
//////////////////////////////////////////////////
void onWindowClose()
{
isRunning = false;
}
//////////////////////////////////////////////////
void logMessage(const char* where, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf("[INFO] (in '%s'): ", where);
vprintf(fmt, args);
va_end(args);
}
//////////////////////////////////////////////////
void logWarning(const char* where, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf("[WARNING] (in '%s'): ", where);
vprintf(fmt, args);
va_end(args);
}
//////////////////////////////////////////////////
void logError(const char* where, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf("[ERROR] (in '%s'): ", where);
vprintf(fmt, args);
va_end(args);
}
//////////////////////////////////////////////////
fada_Error checkFADA(unsigned int line, fada_Error err)
{
if (err != FADA_ERROR_SUCCESS)
{
char buf[16];
char* msg;
switch (err)
{
default: msg = "unknown error"; break;
case FADA_ERROR_INVALID_MANAGER: msg = "passed an invalid manager"; break;
case FADA_ERROR_INVALID_PARAMETER: msg = "passed an invalid parameter"; break;
case FADA_ERROR_INVALID_TYPE: msg = "manager does not have a valid sample type bound to it"; break;
case FADA_ERROR_INVALID_SIZE: msg = "passed an invalid size"; break;
case FADA_ERROR_INVALID_SAMPLE_RATE: msg = "passed an invalid sample rate"; break;
case FADA_ERROR_INVALID_CHANNEL: msg = "passed an invalid channel index"; break;
case FADA_ERROR_INVALID_FFT_BUFFER: msg = "passed an invalid FFT buffer"; break;
case FADA_ERROR_MANAGER_NOT_READY: msg = "manager is not ready yet"; break;
case FADA_ERROR_NO_DATA: msg = "no data was bound to the manager"; break;
case FADA_ERROR_NOT_MULTIPLE_OF_CHANNELS: msg = "value was not a multiple of the channel count"; break;
case FADA_ERROR_NOT_ENOUGH_MEMORY: msg = "not enough memory"; break;
case FADA_ERROR_INDEX_OUT_OF_BOUNDS: msg = "index was out of bounds"; break;
case FADA_ERROR_POSITION_OUT_OF_BOUNDS: msg = "position was out of bounds"; break;
case FADA_ERROR_FREQUENCY_OUT_OF_BOUNDS: msg = "frequency was out of the valid frequency range"; break;
case FADA_ERROR_WINDOW_NOT_CREATED: msg = "manager does not have a window buffer created"; break;
}
sprintf(buf, "Line %d", line);
logWarning(buf, "libfada check failed (error=%d): %s\n", err, msg);
}
return err;
} | 24.139535 | 178 | 0.603261 | ief015 |