text string | size int64 | token_count int64 |
|---|---|---|
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Cleaver - A MultiMaterial Tetrahedral Mesher
// -- Mesher Class
//
// Author: Jonathan Bronson (bronson@sci.utah.edu)
//
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Copyright (C) 2011, 2012, Jonathan Bronson
// Scientific Computing & Imaging Institute
// University of Utah
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files ( the "Software" ), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall
// be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
//-------------------------------------------------------------------
//-------------------------------------------------------------------
#include "Cleaver.h"
#include "CleaverMesher.h"
#include "TetMesh.h"
#include "ScalarField.h"
#include "Volume.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
namespace cleaver
{
const std::string VersionNumber = "2.4";
const std::string VersionDate = __DATE__;
const std::string Version = std::string("Cleaver") + " " + VersionNumber + " " + VersionDate;
TetMesh* cleaveMeshToVolume(const Volume *volume, TetMesh *bgMesh, bool verbose)
{
CleaverMesher mesher;
mesher.setVolume(volume);
mesher.setBackgroundMesh(bgMesh);
mesher.buildAdjacency();
mesher.sampleVolume();
mesher.computeAlphas();
mesher.computeInterfaces();
mesher.generalizeTets();
mesher.snapsAndWarp();
mesher.stencilTets();
return mesher.getTetMesh();
}
TetMesh* createMeshFromVolume(const Volume *volume, bool verbose)
{
CleaverMesher mesher;
mesher.setVolume(volume);
mesher.createTetMesh(verbose);
return mesher.getTetMesh();
}
Volume* createFloatFieldVolumeFromVolume(Volume *base_volume)
{
int width = base_volume->width();
int height = base_volume->height();
int depth = base_volume->depth();
std::vector<AbstractScalarField*> fields;
for (int m = 0; m < base_volume->numberOfMaterials(); m++)
{
float *data = new float[width*height*depth];
for (int d = 0; d < depth; d++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
data[d*width*height + h*width + w] = (float)base_volume->valueAt(w + 0.5, h + 0.5, d + 0.5, m);
}
}
}
ScalarField<float> *floatField = new ScalarField<float>(data, width, height, depth);
floatField->setName(base_volume->getMaterial(m)->name() + "_asFloat");
fields.push_back(floatField);
}
cleaver::Volume *floatVolume = new Volume(fields);
floatVolume->setName(base_volume->name());
return floatVolume;
}
ScalarField<float>* createFloatFieldFromScalarField(AbstractScalarField *scalarField)
{
int w = (int)(scalarField->bounds().size.x);
int h = (int)(scalarField->bounds().size.y);
int d = (int)(scalarField->bounds().size.z);
int wh = w*h;
int whd = wh*d;
float *data = new float[whd];
for (int k = 0; k < d; k++)
{
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
data[k*wh + j*w + i] = (float)scalarField->valueAt(i + 0.5, j + 0.5, k + 0.5);
}
}
}
ScalarField<float> *floatField = new ScalarField<float>(data, w, h, d);
floatField->setBounds(scalarField->bounds());
return floatField;
}
ScalarField<double>* createDoubleFieldFromScalarField(AbstractScalarField *scalarField)
{
int w = (int)(scalarField->bounds().size.x);
int h = (int)(scalarField->bounds().size.y);
int d = (int)(scalarField->bounds().size.z);
int wh = w*h;
int whd = wh*d;
double *data = new double[whd];
for (int k = 0; k < d; k++)
{
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
data[k*wh + j*w + i] = scalarField->valueAt(i + 0.5, j + 0.5, k + 0.5);
}
}
}
ScalarField<double> *doubleField = new ScalarField<double>(data, w, h, d);
doubleField->setBounds(scalarField->bounds());
return doubleField;
}
void stripExteriorTets(TetMesh *mesh, const Volume *volume, bool verbose)
{
// exterior material is equal to material count
mesh->stripMaterial(volume->numberOfMaterials(), verbose);
}
}
| 5,441 | 1,884 |
/*Problem Statement: You are given an array of integers ARR[] of size N consisting of zeros and ones. You have to select a subset and flip bits of that subset.
You have to return the count of maximum one’s that you can obtain by flipping chosen sub-array at most once.
A flip operation is one in which you turn 1 into 0 and 0 into 1.
Time Complexity : O(n)
*/
#include<bits/stdc++.h>
using namespace std;
int flipBits(vector<int> v, int n)
{
int ones=0;
for(int i=0;i<n;i++)
{
if(v[i]==1)
{
ones++;
}
}
for(int i=0;i<n;i++)
{
if(v[i]==1)
{
v[i]=-1;
}
else
{
v[i]=1;
}
}
int curr=0,max_sum=0;
for(int i=0;i<n;i++)
{
curr+=v[i];
max_sum = max(curr, max_sum);
if(curr<0)
{
curr=0;
}
}
return max_sum+ones;
}
int main()
{
int test;
cout<<"Enter total testcases: "<<endl;
cin>>test;
while(test--)
{
int n;
cout<<"Enter total: "<<endl;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
v.push_back(t);
}
cout<<flipBits(v,n)<<endl;
}
return 0;
}
| 1,289 | 481 |
// Rama Simulator, Copyright (C) 2014-2020 Russell Smith.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
#include <QMessageBox>
#include "nelder_mead.h"
#include "ui_nelder_mead.h"
NelderMeadOptimizer::Settings NelderMead::s_;
NelderMead::NelderMead(QWidget *parent) :
QDialog(parent),
ui(new Ui::NelderMead)
{
ui->setupUi(this);
resize(0, 0);
ui->edit_time
->setText(QString::asprintf("%.10g", s_.annealing_time));
ui->edit_initial_fraction
->setText(QString::asprintf("%.10g", s_.initial_fraction));
ui->edit_initial_temperature
->setText(QString::asprintf("%.10g", s_.initial_temperature));
ui->edit_final_temperature
->setText(QString::asprintf("%.10g", s_.final_temperature));
}
NelderMead::~NelderMead() {
delete ui;
}
void NelderMead::on_ok_button_clicked() {
if (Check()) {
accept();
}
}
void NelderMead::on_cancel_button_clicked() {
reject();
}
bool NelderMead::Check() {
bool ok;
s_.annealing_time = ui->edit_time->text().toDouble(&ok);
if (!ok || s_.annealing_time < 0) {
QMessageBox::warning(this, "Error",
"Bad annealing time value (must be a number >= 0)");
return false;
}
s_.initial_fraction = ui->edit_initial_fraction->text().toDouble(&ok);
if (!ok || s_.initial_fraction < 0 || s_.initial_fraction > 1) {
QMessageBox::warning(this, "Error", "Bad initial fraction value "
"(must be a number in the range 0..1)");
return false;
}
s_.initial_temperature = ui->edit_initial_temperature->text().toDouble(&ok);
if (!ok || s_.initial_temperature < 0) {
QMessageBox::warning(this, "Error",
"Bad initial temperature value (must be a number >= 0)");
return false;
}
s_.final_temperature = ui->edit_final_temperature->text().toDouble(&ok);
if (!ok || s_.final_temperature <= 0 || s_.final_temperature >= 1) {
QMessageBox::warning(this, "Error", "Bad final temperature value "
"(must be a number >0 and <1)");
return false;
}
return true;
}
| 2,520 | 876 |
#include "DHASLogging.h"
#include "Call.h"
#include <stdio.h>
#include "resip/dum/InviteSession.hxx"
#include "resip/dum/ClientInviteSession.hxx"
#include "AppDialogSetNotifySoundsEmptyCommand.h"
using namespace resip;
Call::Call(resip::DialogUsageManager &dum, ActionMachine* am):AppDialogSet(dum)
{
this->mpActionMachine = am;
this->mCallState = Initial;
this->mRtpSession = 0;
this->mIncomming = false;
this->mpCurrentAction = 0;
}
Call::~Call()
{
mpActionMachine->destroyChain(this);
if (this->mRtpSession)
{
delete this->mRtpSession;
this->mRtpSession = 0;
}
}
void Call::setCurrentAction(IPhoneAction* a)
{
this->mpCurrentAction = a;
}
void Call::onCallAnswered()
{
// The call is answered by UAS, this is what triggers the action chain
mpActionMachine->asyncRunAction(this);
}
CallState Call::getCallState()
{
return mCallState;
}
void Call::setIncomming(bool i)
{
this->mIncomming = i;
}
IPhoneAction* Call::getCurrentAction()
{
return mpCurrentAction;
}
void Call::removeRTPObserver(RTPObserver *obs)
{
for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++)
{
if (*it != obs) continue;
this->mRtpObservers.erase(it);
return;
}
}
void Call::addRTPObserver(RTPObserver *obs)
{
for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++)
{
if (*it == obs) return;
}
this->mRtpObservers.push_back(obs);
}
void Call::appendAction(IPhoneAction* action)
{
if (mpCurrentAction == 0)
{
mpCurrentAction = action;
//if no action was set and the call was answered, then schedule the action to run
if (getCallState() == Answered) mpActionMachine->asyncRunAction(this);
}
else
{
// if an action is already in queue, it means that we can just append to it and
// it will eventually get invoked
IPhoneAction *a = mpCurrentAction;
while (a->getNextAction() != 0)
{
a = a->getNextAction();
}
a->setNextAction(action);
}
}
void Call::setRTPSession(Dumais::Sound::RTPSession *rtpSession)
{
this->mRtpSession = rtpSession;
this->mRtpSession->addObserver(this); //TODO should unsubscribe if overwriting observer
}
Dumais::Sound::RTPSession* Call::getRTPSession()
{
return this->mRtpSession;
}
//WARNING: This is called from the sound player thread
void Call::onSoundQueueEmpty()
{
// Don't notify from this thread, post it on the dum's thread
AppDialogSetNotifySoundsEmptyCommand* cmd = new AppDialogSetNotifySoundsEmptyCommand(this);
this->mDum.post(cmd);
}
void Call::notifySoundsEmpty()
{
// we copy the list because observers could unsubscribe in the meantime
auto list = this->mRtpObservers;
for (std::list<RTPObserver*>::iterator it = list.begin();it!=list.end();it++)
{
(*it)->onRTPSessionSoundQueueEmpty(this);
}
}
DialogUsageManager& Call::getDUM()
{
return this->mDum;
}
bool Call::isIncomming()
{
return this->mIncomming;
}
std::string Call::getDigitQueue()
{
return this->mDigitQueue;
}
void Call::clearDigitQueue()
{
this->mDigitQueue="";
}
resip::NameAddr Call::getFrom()
{
return mFrom;
}
resip::NameAddr Call::getContact()
{
return mContact;
}
std::string Call::getID()
{
return this->getDialogSetId().getCallId().c_str();
}
void Call::onTerminated()
{
}
void Call::toJSON(Dumais::JSON::JSON& json)
{
Dumais::JSON::JSON& j = json.addObject("call");
j.addValue(getID(),"id");
j.addValue(mFrom.uri().getAor().data(),"from");
j.addValue(mTo.uri().getAor().data(),"to");
}
| 3,704 | 1,299 |
#include <cassert>
#include <functional>
#include <algorithm>
using namespace std;
#include "avlTree.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <numeric>
#include <set>
#include <vector>
#include <iostream>
#include "../common/iostreamhelper.h"
#include "../common/profile.h"
#include "../common/rand.h"
static void checkSearch(AVLTree<int>& tree, vector<int>& in) {
for (int i = 0; i < int(in.size()); i++) {
int x = in[i];
assert(tree.find(x)->value == x);
}
}
static void checkIndex(AVLTree<int>& tree, vector<int>& in) {
assert(tree.size() == int(in.size()));
for (int i = 0; i < int(in.size()); i++) {
assert(tree[i]->value == in[i]);
assert(tree.indexOf(tree[i]) == i);
}
}
static int getHeight(const AVLTree<int>::Node* node) {
return node == nullptr ? 0 : node->height;
}
static void checkHeight(AVLTree<int>& tree, AVLTree<int>::Node* node) {
if (!node || node == tree.sentinel)
return;
assert(node->height == max(getHeight(node->left), getHeight(node->right)) + 1);
checkHeight(tree, node->left);
checkHeight(tree, node->right);
}
void testAVLTree() {
return; //TODO: if you want to test, make this line a comment.
cout << "--- AVL Tree -------------------------------" << endl;
{
AVLTree<int> tree;
vector<int> in(1000);
iota(in.begin(), in.end(), 0);
assert(tree.empty());
{
vector<int> t(in);
random_shuffle(t.begin(), t.end());
for (int i = 0; i < int(in.size()); i++) {
auto p = tree.insert(t[i]);
if (!p.second)
cerr << "It'll never be shown!" << endl;
assert(p.first->value == t[i] && p.second);
}
checkSearch(tree, in);
checkIndex(tree, in);
checkHeight(tree, tree.root);
}
{
assert(tree.lowerBound(-1)->value == 0);
assert(tree.lowerBound(0)->value == 0);
assert(tree.lowerBound(3)->value == 3);
assert(tree.lowerBound(77)->value == 77);
assert(tree.lowerBound(999)->value == 999);
assert(tree.upperBound(0)->value == 1);
assert(tree.upperBound(3)->value == 4);
assert(tree.upperBound(77)->value == 78);
assert(tree.upperBound(999) == tree.nullNode());
auto it = tree.lowerBound(10);
auto itE = tree.upperBound(77);
for (int i = 10; i < 77; i++) {
assert(it->value == i);
it = tree.next(it);
}
for (int i = 76; i >= 10; i--) {
it = tree.prev(it);
assert(it->value == i);
}
}
{
vector<int> t(in), org(in);
random_shuffle(t.begin(), t.end());
while (!tree.empty()) {
int x = t.back();
t.pop_back();
org.erase(find(org.begin(), org.end(), x));
bool b = tree.erase(x);
if (!b)
cerr << "It'll never be shown!" << endl;
assert(b);
assert(tree.size() == int(t.size()));
checkSearch(tree, org);
checkIndex(tree, org);
checkHeight(tree, tree.root);
}
}
}
cout << "OK!" << endl;
}
| 3,517 | 1,130 |
#include "bvec.h"
int main(int argc, char *argv[]) {
vector<uint64_t> vec1,vec2;
vec1.push_back(0);
vec1.push_back(100);
vec2.push_back(0);
vec2.push_back(10);
BitVector *bv1 = new BitVector(vec1);
BitVector *bv2 = new BitVector(vec2);
printf("bv1->cnt()=%llu\n",bv1->cnt());
printf("bv2->cnt()=%llu\n",bv2->cnt());
BitVector *bvu = *bv1 | *bv2;
printf("bvu->cnt()=%llu\n",bvu->cnt());
BitVector *bvi = *bv1 & *bv2;
printf("bvi->cnt()=%llu\n",bvi->cnt());
return 0;
} | 482 | 246 |
/* -------------------------------------------------------------------------- *
* Simbody(tm) Adhoc Test: Cable Over Bicubic Surfaces *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2012 Stanford University and the Authors. *
* Authors: Michael Sherman, Andreas Scholz *
* Contributors: *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* Simbody OpenSimPartyDemoCable
THIS DOESN'T WORK YET */
#include "Simbody.h"
#include <cassert>
#include <iostream>
using std::cout; using std::endl;
using namespace SimTK;
// This gets called periodically to dump out interesting things about
// the cables and the system as a whole. It also saves states so that we
// can play back at the end.
static Array_<State> saveStates;
class ShowStuff : public PeriodicEventReporter {
public:
ShowStuff(const MultibodySystem& mbs,
const CableSpring& cable1, Real interval)
: PeriodicEventReporter(interval),
mbs(mbs), cable1(cable1) {}
static void showHeading(std::ostream& o) {
printf("%8s %10s %10s %10s %10s %10s %10s %10s %10s %12s\n",
"time", "length", "rate", "integ-rate", "unitpow", "tension", "disswork",
"KE", "PE", "KE+PE-W");
}
/** This is the implementation of the EventReporter virtual. **/
void handleEvent(const State& state) const OVERRIDE_11 {
const CablePath& path1 = cable1.getCablePath();
printf("%8g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %12.6g CPU=%g\n",
state.getTime(),
path1.getCableLength(state),
path1.getCableLengthDot(state),
path1.getIntegratedCableLengthDot(state),
path1.calcCablePower(state, 1), // unit power
cable1.getTension(state),
cable1.getDissipatedEnergy(state),
mbs.calcKineticEnergy(state),
mbs.calcPotentialEnergy(state),
mbs.calcEnergy(state)
+ cable1.getDissipatedEnergy(state),
cpuTime());
saveStates.push_back(state);
}
private:
const MultibodySystem& mbs;
CableSpring cable1;
};
int main() {
try {
// Create the system.
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
matter.setShowDefaultGeometry(false);
CableTrackerSubsystem cables(system);
GeneralForceSubsystem forces(system);
Force::Gravity gravity(forces, matter, -YAxis, 9.81);
// Force::GlobalDamper(forces, matter, 5);
system.setUseUniformBackground(true); // no ground plane in display
MobilizedBody Ground = matter.Ground(); // convenient abbreviation
// Read in some bones.
PolygonalMesh femur;
PolygonalMesh tibia;
femur.loadVtpFile("CableOverBicubicSurfaces-femur.vtp");
tibia.loadVtpFile("CableOverBicubicSurfaces-tibia.vtp");
femur.scaleMesh(30);
tibia.scaleMesh(30);
// Build a pendulum
Body::Rigid pendulumBodyFemur( MassProperties(1.0, Vec3(0, -5, 0),
UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0))));
pendulumBodyFemur.addDecoration(Transform(), DecorativeMesh(femur).setColor(Vec3(0.8, 0.8, 0.8)));
Body::Rigid pendulumBodyTibia( MassProperties(1.0, Vec3(0, -5, 0),
UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0))));
pendulumBodyTibia.addDecoration(Transform(), DecorativeMesh(tibia).setColor(Vec3(0.8, 0.8, 0.8)));
Rotation z180(Pi, YAxis);
MobilizedBody::Pin pendulumFemur( matter.updGround(),
Transform(Vec3(0, 0, 0)),
pendulumBodyFemur,
Transform(Vec3(0, 0, 0)) );
Rotation rotZ45(-Pi/4, ZAxis);
MobilizedBody::Pin pendulumTibia( pendulumFemur,
Transform(rotZ45, Vec3(0, -12, 0)),
pendulumBodyTibia,
Transform(Vec3(0, 0, 0)) );
Real initialPendulumOffset = -0.25*Pi;
Constraint::PrescribedMotion pres(matter,
new Function::Sinusoid(0.25*Pi, 0.2*Pi, 0*initialPendulumOffset), pendulumTibia, MobilizerQIndex(0));
// Build a wrapping cable path
CablePath path2(cables, Ground, Vec3(1, 3, 1), // origin
pendulumTibia, Vec3(1, -4, 0)); // termination
// Create a bicubic surface
Vec3 patchOffset(0, -5, -1);
Rotation rotZ90(0.5*Pi, ZAxis);
Rotation rotX90(0.2*Pi, XAxis);
Rotation patchRotation = rotZ90 * rotX90 * rotZ90;
Transform patchTransform(patchRotation, patchOffset);
Real patchScaleX = 2.0;
Real patchScaleY = 2.0;
Real patchScaleF = 0.75;
const int Nx = 4, Ny = 4;
const Real xData[Nx] = { -2, -1, 1, 2 };
const Real yData[Ny] = { -2, -1, 1, 2 };
const Real fData[Nx*Ny] = { 2, 3, 3, 1,
0, 1.5, 1.5, 0,
0, 1.5, 1.5, 0,
2, 3, 3, 1 };
const Vector x_(Nx, xData);
const Vector y_(Ny, yData);
const Matrix f_(Nx, Ny, fData);
Vector x = patchScaleX*x_;
Vector y = patchScaleY*y_;
Matrix f = patchScaleF*f_;
BicubicSurface patch(x, y, f, 0);
Real highRes = 30;
Real lowRes = 1;
PolygonalMesh highResPatchMesh = patch.createPolygonalMesh(highRes);
PolygonalMesh lowResPatchMesh = patch.createPolygonalMesh(lowRes);
pendulumFemur.addBodyDecoration(patchTransform,
DecorativeMesh(highResPatchMesh).setColor(Cyan).setOpacity(.75));
pendulumFemur.addBodyDecoration(patchTransform,
DecorativeMesh(lowResPatchMesh).setRepresentation(DecorativeGeometry::DrawWireframe));
Vec3 patchP(-0.5,-1,2), patchQ(-0.5,1,2);
pendulumFemur.addBodyDecoration(patchTransform,
DecorativePoint(patchP).setColor(Green).setScale(2));
pendulumFemur.addBodyDecoration(patchTransform,
DecorativePoint(patchQ).setColor(Red).setScale(2));
CableObstacle::Surface patchObstacle(path2, pendulumFemur, patchTransform,
ContactGeometry::SmoothHeightMap(patch));
patchObstacle.setContactPointHints(patchP, patchQ);
patchObstacle.setDisabledByDefault(true);
// Sphere
Real sphRadius = 1.5;
Vec3 sphOffset(0, -0.5, 0);
Rotation sphRotation(0*Pi, YAxis);
Transform sphTransform(sphRotation, sphOffset);
CableObstacle::Surface tibiaSphere(path2, pendulumTibia, sphTransform,
ContactGeometry::Sphere(sphRadius));
Vec3 sphP(1.5,-0.5,0), sphQ(1.5,0.5,0);
tibiaSphere.setContactPointHints(sphP, sphQ);
pendulumTibia.addBodyDecoration(sphTransform,
DecorativeSphere(sphRadius).setColor(Red).setOpacity(0.5));
// Make cable a spring
CableSpring cable2(forces, path2, 50., 18., 0.1);
Visualizer viz(system);
viz.setShowFrameNumber(true);
system.addEventReporter(new Visualizer::Reporter(viz, 1./30));
system.addEventReporter(new ShowStuff(system, cable2, 0.02));
// Initialize the system and state.
system.realizeTopology();
State state = system.getDefaultState();
system.realize(state, Stage::Position);
viz.report(state);
cout << "path2 init length=" << path2.getCableLength(state) << endl;
cout << "Hit ENTER ...";
getchar();
// path1.setIntegratedCableLengthDot(state, path1.getCableLength(state));
// Simulate it.
saveStates.clear(); saveStates.reserve(2000);
// RungeKutta3Integrator integ(system);
RungeKuttaMersonIntegrator integ(system);
// CPodesIntegrator integ(system);
// integ.setAllowInterpolation(false);
integ.setAccuracy(1e-5);
TimeStepper ts(system, integ);
ts.initialize(state);
ShowStuff::showHeading(cout);
const Real finalTime = 10;
const double startTime = realTime();
ts.stepTo(finalTime);
cout << "DONE with " << finalTime
<< "s simulated in " << realTime()-startTime
<< "s elapsed.\n";
while (true) {
cout << "Hit ENTER FOR REPLAY, Q to quit ...";
const char ch = getchar();
if (ch=='q' || ch=='Q') break;
for (unsigned i=0; i < saveStates.size(); ++i)
viz.report(saveStates[i]);
}
} catch (const std::exception& e) {
cout << "EXCEPTION: " << e.what() << "\n";
}
}
| 9,465 | 3,449 |
/* _ _
* _ __ ___ (_)_ __ | | __
* | '_ ` _ \| | '_ \| |/ /
* | | | | | | | | | | <
* |_| |_| |_|_|_| |_|_|\_\
*
* SPDX-License-Identifier: MIT
*
*/
#include <endian.h>
#include <errno.h>
#include <iomanip>
#include <gdt_utils.h>
bool gdt::ServiceParam::FRAGMENTATION_DONE = false;
bool gdt::ServiceParam::FRAGMENTATION_NEXT = true;
gdt::ServiceMessageAsyncDone gdt::ServiceMsgManager::cb_async_done;
gdt::ServiceParam::ServiceParam() : data_size(0),
total_data_size(0),
type(SPT_UNKNOWN),
id(0),
index(0),
extra_type(0),
thread_safe(false),
fragmented(false),
linked_index(0),
param_fctry(nullptr),
fragments(0),
fragment_index(0) {
memset(data, 0, sizeof(data));
data_p = data;
in_data_p = data_p;
param_data_cb = ¶m_data_default;
pthread_mutex_init(&mtx, nullptr);
}
gdt::ServiceParam::~ServiceParam() { pthread_mutex_destroy(&mtx); }
void gdt::ServiceParam::fragment(const void *_data, unsigned int _data_size) {
// set in data pointer
in_data_p = _data;
// set first fragment data
data_size = 256;
total_data_size = _data_size;
// get param count needed to fit data size
int pc = _data_size / 256;
// remainder
int rem = _data_size % 256;
// set fragment index
fragment_index = 0;
// set total number of fragments
fragments = pc + ((rem > 0) ? 1 : 0);
// set fragmentation flag
fragmented = true;
}
int gdt::ServiceParam::param_data_file(ServiceParam *sc_param,
const void *in,
int in_size) {
FILE *f = (FILE *)in;
// get tmp service param buffer
if (sc_param->linked_index >= sc_param->linked.size())
sc_param->linked_index = 0;
ServiceParam *new_sc_param = sc_param->linked[sc_param->linked_index++];
// read file
int bc = fread(new_sc_param->data, 1, sizeof(new_sc_param->data), f);
// decrement from previous fread
sc_param->total_data_size -= sc_param->data_size;
// switch buffer of original param with new one
sc_param->data_p = new_sc_param->data;
// set data size
sc_param->data_size = bc;
return bc;
}
int gdt::ServiceParam::param_data_default(ServiceParam *sc_param,
const void *in,
int in_size) {
// calculate number of bytes needed for current fragment
int bc = (sc_param->total_data_size > sizeof(sc_param->data)
? sizeof(sc_param->data)
: sc_param->total_data_size);
sc_param->data_p += bc;
sc_param->total_data_size -= bc;
return bc;
}
int gdt::ServiceParam::set_data(FILE *_data, unsigned int _file_size) {
lock();
if (_file_size > 256) {
// file param data fetch method
param_data_cb = ¶m_data_file;
// fragmentation
fragment(_data, _file_size);
// read initial block
data_size = fread(data, 1, 256, _data);
// data_p points to internal buffer
data_p = data;
unlock();
return 0;
}
fragmented = false;
// read initial block
data_size = fread(data, 1, 256, _data);
total_data_size = data_size;
data_p = data;
unlock();
return 0;
}
void gdt::ServiceParam::set(mink_utils::VariantParam *vparam) {
switch (vparam->get_type()) {
case mink_utils::DPT_INT: {
uint64_t tmp = htobe64(vparam->get_data()->i64);
set_data(&tmp, sizeof(tmp));
extra_type = vparam->get_type();
break;
}
case mink_utils::DPT_STRING:
case mink_utils::DPT_OCTETS:
set_data(vparam->get_data()->str, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_DOUBLE:
set_data(&vparam->get_data()->d, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_CHAR:
set_data(&vparam->get_data()->c, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_BOOL:
set_data(&vparam->get_data()->b, vparam->get_size());
extra_type = vparam->get_type();
break;
default:
break;
}
}
int gdt::ServiceParam::set_data(const void *_data, unsigned int _data_size) {
lock();
if (_data_size > 256) {
// default param data fetch method
param_data_cb = ¶m_data_default;
// fragmentation
fragment(_data, _data_size);
// set data pointer (fragmented stream does not imply copying of data)
data_p = (unsigned char *)_data;
unlock();
return 0;
}
fragmented = false;
memcpy(data, _data, _data_size);
data_size = _data_size;
total_data_size = _data_size;
data_p = data;
unlock();
return 0;
}
void gdt::ServiceParam::std_out() {
lock();
std::cout << data << std::endl;
unlock();
}
unsigned char *gdt::ServiceParam::get_data() { return data; }
unsigned char *gdt::ServiceParam::get_data_p() { return data_p; }
void gdt::ServiceParam::set_data_p(unsigned char *_data_p) {
data_p = _data_p;
}
void gdt::ServiceParam::reset_data_p() {
data_p = data;
in_data_p = data_p;
}
int gdt::ServiceParam::get_data_size() {
lock();
unsigned int tmp = data_size;
unlock();
return tmp;
}
void gdt::ServiceParam::inc_total_data_size(unsigned int _inc) {
total_data_size += _inc;
++fragment_index;
}
int gdt::ServiceParam::get_total_data_size() const { return total_data_size; }
void gdt::ServiceParam::reset() {
lock();
data_size = 0;
unlock();
id = 0;
fragmented = false;
param_data_cb = ¶m_data_default;
}
void gdt::ServiceParam::set_thread_safety(bool _thread_safe) {
thread_safe = _thread_safe;
}
void gdt::ServiceParam::set_param_factory(ServiceParamFactory *_pfact) {
param_fctry = _pfact;
}
bool gdt::ServiceParam::is_fragmented() const { return fragmented; }
bool *gdt::ServiceParam::get_fragmentation_p() { return &fragmented; }
uint32_t gdt::ServiceParam::get_index() const { return index; }
int gdt::ServiceParam::get_extra_type() const { return extra_type; }
void gdt::ServiceParam::set_extra_type(int _type) { extra_type = _type; }
int gdt::ServiceParam::get_fragment_index() const { return fragment_index; }
void gdt::ServiceParam::set_fragmented(bool _fragmented) {
fragmented = _fragmented;
}
void gdt::ServiceParam::set_callback(GDTEventType _type,
GDTCallbackMethod *cback) {
cb_handler.set_callback(_type, cback);
}
bool gdt::ServiceParam::process_callback(GDTEventType _type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(_type, args);
}
void gdt::ServiceParam::clear_callbacks() { cb_handler.clear(); }
void gdt::ServiceParam::lock() {
if (thread_safe)
pthread_mutex_lock(&mtx);
}
void gdt::ServiceParam::unlock() {
if (thread_safe)
pthread_mutex_unlock(&mtx);
}
gdt::ServiceParamType gdt::ServiceParam::get_type() const { return type; }
void gdt::ServiceParam::set_id(uint32_t _id) { id = htobe32(_id); }
void gdt::ServiceParam::set_index(uint32_t idx) { index = idx; }
uint32_t gdt::ServiceParam::get_id() const { return be32toh(id); }
uint32_t *gdt::ServiceParam::get_idp() { return &id; }
gdt::ServiceParamVARIANT::ServiceParamVARIANT() { type = SPT_VARIANT; }
gdt::ServiceParamVARIANT::~ServiceParamVARIANT() = default;
int gdt::ServiceParamVARIANT::extract(void *_out) {
lock();
switch (extra_type) {
case mink_utils::DPT_INT: {
auto res = (uint64_t *)_out;
auto src = (uint64_t *)data;
// Big endian -> little endian
*res = be64toh(*src);
break;
}
default:
memcpy(_out, data, data_size);
break;
}
unlock();
return 0;
}
int gdt::ServiceParamVARIANT::set_data(const void *_data, unsigned int _data_size) {
return ServiceParam::set_data(_data, _data_size);
}
void gdt::ServiceParamVARIANT::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamUNKNOWN::ServiceParamUNKNOWN() { type = SPT_UNKNOWN; }
gdt::ServiceParamUNKNOWN::~ServiceParamUNKNOWN() = default;
int gdt::ServiceParamUNKNOWN::extract(void *_out) {
lock();
memcpy(_out, data, data_size);
unlock();
return 0;
}
int gdt::ServiceParamUNKNOWN::set_data(const void *_data, unsigned int _data_size) {
return ServiceParam::set_data(_data, _data_size);
}
void gdt::ServiceParamUNKNOWN::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamBOOL::ServiceParamBOOL() { type = SPT_BOOL; }
gdt::ServiceParamBOOL::~ServiceParamBOOL() = default;
int gdt::ServiceParamBOOL::extract(void *_out) {
auto res = (bool *)_out;
auto src = (bool *)data;
lock();
*res = *src;
unlock();
// success
return 0;
}
int gdt::ServiceParamBOOL::set_bool(bool _data) {
return ServiceParam::set_data(&_data, sizeof(bool));
}
void gdt::ServiceParamBOOL::std_out() {
auto tmp = (bool *)data;
lock();
std::cout << *tmp << std::endl;
unlock();
}
gdt::ServiceParamUINT32::ServiceParamUINT32() { type = SPT_UINT32; }
gdt::ServiceParamUINT32::~ServiceParamUINT32() = default;
int gdt::ServiceParamUINT32::extract(void *_out) {
auto res = (uint32_t *)_out;
auto src = (uint32_t *)data;
lock();
// Big endian -> little endian
*res = be32toh(*src);
unlock();
// success
return 0;
}
int gdt::ServiceParamUINT32::set_uint32(uint32_t _data) {
uint32_t tmp = htobe32(_data);
return ServiceParam::set_data(&tmp, sizeof(uint32_t));
}
void gdt::ServiceParamUINT32::std_out() {
auto tmp = (uint32_t *)data;
lock();
std::cout << be32toh(*tmp) << std::endl;
unlock();
}
gdt::ServiceParamUINT64::ServiceParamUINT64() { type = SPT_UINT64; }
gdt::ServiceParamUINT64::~ServiceParamUINT64() = default;
void gdt::ServiceParamUINT64::std_out() {
auto tmp = (uint64_t *)data;
lock();
std::cout << be64toh(*tmp) << std::endl;
unlock();
}
int gdt::ServiceParamUINT64::extract(void *_out) {
auto res = (uint64_t *)_out;
auto src = (uint64_t *)data;
lock();
// Big endian -> little endian
*res = be64toh(*src);
unlock();
// success
return 0;
}
int gdt::ServiceParamUINT64::set_uint64(uint64_t _data) {
uint64_t tmp = htobe64(_data);
return ServiceParam::set_data(&tmp, sizeof(uint64_t));
}
gdt::ServiceParamCString::ServiceParamCString() { type = SPT_CSTRING; }
gdt::ServiceParamCString::~ServiceParamCString() = default;
int gdt::ServiceParamCString::extract(void *_out) {
auto _out_cs = (char *)_out;
lock();
strncpy(_out_cs, (char *)data, strlen((char *)data) + 1);
unlock();
// success
return 0;
}
void gdt::ServiceParamCString::set_cstring(const char *cstring) {
if (cstring == nullptr) {
data_size = 0;
return;
}
set_data(cstring, strnlen(cstring, (sizeof(data) - 1) + 1));
}
gdt::ServiceParamOctets::ServiceParamOctets() { type = SPT_OCTETS; }
gdt::ServiceParamOctets::~ServiceParamOctets() = default;
int gdt::ServiceParamOctets::extract(void *_out) {
lock();
memcpy(_out, data, data_size);
unlock();
// success
return 0;
}
void gdt::ServiceParamOctets::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamFactory::ServiceParamFactory(bool _pooled,
bool _th_safe,
unsigned int pool_size) {
pooled = _pooled;
if (pooled) {
cstr_pool.init(pool_size);
cstr_pool.construct_objects();
oct_pool.init(pool_size);
oct_pool.construct_objects();
uint32_pool.init(pool_size);
uint32_pool.construct_objects();
uint64_pool.init(pool_size);
uint64_pool.construct_objects();
unknown_pool.init(pool_size);
unknown_pool.construct_objects();
bool_pool.init(pool_size);
bool_pool.construct_objects();
var_pool.init(pool_size);
var_pool.construct_objects();
ServiceParam *tmp_arr[pool_size];
// cstr
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = cstr_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
cstr_pool.deallocate_constructed((ServiceParamCString *)tmp_arr[i]);
// oct
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = oct_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
oct_pool.deallocate_constructed((ServiceParamOctets *)tmp_arr[i]);
// uint32
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = uint32_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
uint32_pool.deallocate_constructed(
(ServiceParamUINT32 *)tmp_arr[i]);
// uint64
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = uint64_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
uint64_pool.deallocate_constructed(
(ServiceParamUINT64 *)tmp_arr[i]);
// unknown
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = unknown_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
unknown_pool.deallocate_constructed(
(ServiceParamUNKNOWN *)tmp_arr[i]);
// bool
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = bool_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
bool_pool.deallocate_constructed((ServiceParamBOOL *)tmp_arr[i]);
// var
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = var_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
var_pool.deallocate_constructed((ServiceParamVARIANT *)tmp_arr[i]);
}
}
gdt::ServiceParamFactory::~ServiceParamFactory() = default;
gdt::ServiceParam *gdt::ServiceParamFactory::new_param(ServiceParamType param_type) {
ServiceParam *tmp = nullptr;
if (pooled) {
switch (param_type) {
case SPT_CSTRING:
tmp = cstr_pool.allocate_constructed();
break;
case SPT_OCTETS:
tmp = oct_pool.allocate_constructed();
break;
case SPT_UINT32:
tmp = uint32_pool.allocate_constructed();
break;
case SPT_UINT64:
tmp = uint64_pool.allocate_constructed();
break;
case SPT_BOOL:
tmp = bool_pool.allocate_constructed();
break;
case SPT_VARIANT:
tmp = var_pool.allocate_constructed();
break;
default:
tmp = unknown_pool.allocate_constructed();
break;
}
} else {
switch (param_type) {
case SPT_CSTRING:
tmp = new ServiceParamCString();
break;
case SPT_OCTETS:
tmp = new ServiceParamOctets();
break;
case SPT_UINT32:
tmp = new ServiceParamUINT32();
break;
case SPT_UINT64:
tmp = new ServiceParamUINT64();
break;
case SPT_BOOL:
tmp = new ServiceParamBOOL();
break;
case SPT_VARIANT:
tmp = new ServiceParamVARIANT();
break;
default:
tmp = new ServiceParamUNKNOWN();
break;
}
}
return tmp;
}
int gdt::ServiceParamFactory::free_param(ServiceParam *param) {
if (param == nullptr)
return 5;
if (pooled) {
int res = 0;
switch (param->get_type()) {
case SPT_CSTRING:
res =
cstr_pool.deallocate_constructed((ServiceParamCString *)param);
break;
case SPT_OCTETS:
res = oct_pool.deallocate_constructed((ServiceParamOctets *)param);
break;
case SPT_UINT32:
res =
uint32_pool.deallocate_constructed((ServiceParamUINT32 *)param);
break;
case SPT_UINT64:
res =
uint64_pool.deallocate_constructed((ServiceParamUINT64 *)param);
break;
case SPT_UNKNOWN:
res = unknown_pool.deallocate_constructed(
(ServiceParamUNKNOWN *)param);
break;
case SPT_BOOL:
res = bool_pool.deallocate_constructed((ServiceParamBOOL *)param);
break;
case SPT_VARIANT:
res = var_pool.deallocate_constructed((ServiceParamVARIANT *)param);
break;
default:
res = 7;
break;
}
return res;
} else {
delete param;
return 0;
}
}
gdt::ParamIdTypeMap::~ParamIdTypeMap() = default;
int gdt::ParamIdTypeMap::add(uint32_t _id, ServiceParamType _type) {
idtmap[_id] = _type;
return 0;
}
int gdt::ParamIdTypeMap::remove(uint32_t id) {
idtmap.erase(id);
return 0;
}
gdt::ServiceParamType gdt::ParamIdTypeMap::get(uint32_t id) {
// find
auto it = idtmap.find(id);
if (it != idtmap.end())
return it->second;
return SPT_UNKNOWN;
}
int gdt::ParamIdTypeMap::clear() {
idtmap.clear();
return 0;
}
gdt::ServiceMessageDone::ServiceMessageDone() {
usr_method = nullptr;
status = 0;
smsg = nullptr;
}
void gdt::ServiceMessageDone::run(GDTCallbackArgs *args) {
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
// check status (in_msg is nullptr in case if stream timeout)
if ((in_msg != nullptr) && (in_msg->_header->_status != nullptr)) {
if (in_msg->_header->_status->has_linked_data(*in_sess)) {
status = in_msg->_header->_status->linked_node->tlv->value[0];
}
// stream timeout error
} else
status = 300;
// run user handler (async mode)
if (usr_method != nullptr) {
args->add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg);
usr_method->run(args);
}
// signal
smsg->signal_post();
}
static void process_fragments(unsigned int *bc,
unsigned int *tbc,
const gdt::ServiceParam *sc_param,
asn1::Parameters *params,
unsigned int idx){
// calculate number of bytes needed for current fragment
*bc = (sc_param->get_total_data_size() > gdt::ServiceParam::DATA_SZ
? gdt::ServiceParam::DATA_SZ
: sc_param->get_total_data_size());
// check if more allocations are needed
if (params->get_child(idx) == nullptr) {
params->set_child(idx);
params->get_child(idx)->set_value();
params->get_child(idx)->_value->set_child(0);
params->get_child(idx)->_value->set_child(1);
params->get_child(idx)->_value->set_child(2);
params->get_child(idx)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// update total byte count
*tbc += *bc + 25;
}
void gdt::ServiceMessageNext::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
asn1::GDTMessage *gdtm = stream->get_gdt_message();
auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_BODY);
// param map
std::vector<ServiceParam *> *pmap = smsg->get_param_map();
// more segments
if (pindex < pc) {
unsigned int bc;
unsigned int tbc = 0;
// prepare body
if (gdtm->_body != nullptr) {
gdtm->_body->unlink(1);
gdtm->_body->_service_msg->set_linked_data(1);
} else {
gdtm->set_body();
gdtm->prepare();
}
asn1::ServiceMessage *sm = gdtm->_body->_service_msg;
// set params, allocate 10 initial children
if (sm->_params == nullptr) {
sm->set_params();
// set children, allocate more
for (int i = 0; i < 10; i++) {
sm->_params->set_child(i);
sm->_params->get_child(i)->set_value();
sm->_params->get_child(i)->_value->set_child(0);
sm->_params->get_child(i)->_value->set_child(1);
sm->_params->get_child(i)->_value->set_child(2);
sm->_params->get_child(i)->_value->set_child(3);
}
// prepare
asn1::prepare(sm, sm->parent_node);
}
// set service id
sm->_service_id->set_linked_data(1,
(unsigned char *)smsg->get_service_idp(),
sizeof(uint32_t));
// set service action
sm->_service_action->set_linked_data(1,
(unsigned char *)smsg->get_service_actionp(),
1);
// params
ServiceParam *sc_param = nullptr;
asn1::Parameters *params = sm->_params;
unsigned int j;
for (j = 0;
(tbc < ServiceMsgManager::MAX_PARAMS_SIZE) && (pos < pmap->size());
pos++, j++, pindex++) {
sc_param = (*pmap)[pos];
// check if more allocations are needed
if (params->get_child(j) == nullptr) {
params->set_child(j);
params->get_child(j)->set_value();
params->get_child(j)->_value->set_child(0);
params->get_child(j)->_value->set_child(1);
params->get_child(j)->_value->set_child(2);
params->get_child(j)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// check fragmentation
if (sc_param->fragmented) {
// process fragments
while ((tbc < ServiceMsgManager::MAX_PARAMS_SIZE) &&
(sc_param->fragment_index < sc_param->fragments)) {
process_fragments(&bc, &tbc, sc_param, params, j);
// check if limit reached
if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE)
break;
// set gdt values
params->get_child(j)
->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)
->_value
->get_child(0)
->set_linked_data(1, sc_param->data_p, bc);
// variant param id index and type
params->get_child(j)
->_value
->get_child(2)
->set_linked_data(1, (unsigned char *)&sc_param->index, 1);
params->get_child(j)
->_value
->get_child(3)
->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1);
// check if last fragment, disable fragmentation flag (last
// fragment must not contain fragmentation flag)
if (sc_param->fragment_index == (sc_param->fragments - 1)) {
// set gdt fragmentation flag
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_DONE,
1);
} else {
// set gdt fragmentation flag
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_NEXT,
1);
}
// next
++sc_param->fragment_index;
++j;
++pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
}
// break if fragmentation in progress and not finished (to skip
// increment, next call should process the same param again)
if (sc_param->fragment_index < sc_param->fragments)
break;
// rewind gdt param child count and packet index
else {
--j;
--pindex;
}
// no fragmentation
} else {
// update total byte count
tbc += sc_param->data_size + 25;
// check if limit reached
if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE)
break;
params->get_child(j)
->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)
->_value
->get_child(0)
->set_linked_data(1, sc_param->data, sc_param->data_size);
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char *)&ServiceParam::FRAGMENTATION_DONE,
1);
params->get_child(j)
->_value
->get_child(2)
->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)
->_value
->get_child(3)
->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
}
}
// remove unused chidren
for (; j < params->children.size(); j++)
params->get_child(j)->unlink(1);
// include body
*include_body = true;
// continue
if (pindex < pc)
stream->continue_sequence();
}
}
gdt::ServiceMessage::ServiceMessage() : missing_params(false),
idt_map(nullptr),
service_id(0),
service_action(0),
smsg_m(nullptr),
frag_param(nullptr),
auto_free(true) {
sem_init(&smsg_sem, 0, 0);
sem_init(&new_param_sem, 0, 0);
msg_done.smsg = this;
msg_next.smsg = this;
}
gdt::ServiceMessage::~ServiceMessage() { tlvs.clear(); }
int gdt::ServiceMessage::add_param(uint32_t id, ServiceParam *param,
uint32_t index) {
tlvs.push_back(param);
param->set_id(id);
param->index = index;
return 0;
}
int gdt::ServiceMessage::remove_param(uint32_t id) {
for (unsigned int i = 0; i < tlvs.size(); i++)
if (tlvs[i]->get_id() == id) {
tlvs.erase(tlvs.begin() + i);
}
return 0;
}
int gdt::ServiceMessage::get_param(uint32_t id,
std::vector<ServiceParam *> *out) const {
std::all_of(tlvs.cbegin(), tlvs.cend(), [out, id](ServiceParam *p) {
if (p->get_id() == id) out->push_back(p);
return true;
});
return 0;
}
int gdt::ServiceMessage::reset() {
ServiceMsgManager *sm = get_smsg_manager();
std::all_of(tlvs.cbegin(), tlvs.cend(), [sm](ServiceParam *p) {
sm->get_param_factory()->free_param(p);
return true;
});
tlvs.clear();
return 0;
}
uint32_t gdt::ServiceMessage::get_service_id() const { return be32toh(service_id); }
uint32_t *gdt::ServiceMessage::get_service_idp() { return &service_id; }
uint32_t gdt::ServiceMessage::get_service_action() const {
return be32toh(service_action);
}
uint32_t *gdt::ServiceMessage::get_service_actionp() {
return &service_action;
}
void gdt::ServiceMessage::set_service_id(uint32_t _service_id) {
service_id = htobe32(_service_id);
}
void gdt::ServiceMessage::set_service_action(uint32_t _service_action) {
service_action = htobe32(_service_action);
}
void gdt::ServiceMessage::set_smsg_manager(ServiceMsgManager *_smsg_m) {
smsg_m = _smsg_m;
}
gdt::ServiceMsgManager *gdt::ServiceMessage::get_smsg_manager() {
return smsg_m;
}
gdt::ServiceParam *gdt::ServiceMessage::get_frag_param() {
return frag_param;
}
void gdt::ServiceMessage::set_frag_param(ServiceParam *_frag_param) {
frag_param = _frag_param;
if (frag_param != nullptr)
frag_param->fragment_index = 0;
}
bool gdt::ServiceMessage::is_complete() { return complete.get(); }
bool gdt::ServiceMessage::set_complete(bool _is_complete) {
return complete.comp_swap(!_is_complete, _is_complete);
}
bool gdt::ServiceMessage::set_auto_free(bool _auto_free) {
auto_free = _auto_free;
return auto_free;
}
bool gdt::ServiceMessage::get_auto_free() const { return auto_free; }
void gdt::ServiceMessage::set_callback(GDTEventType type,
GDTCallbackMethod *cback) {
cb_handler.set_callback(type, cback);
}
bool gdt::ServiceMessage::process_callback(GDTEventType type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(type, args);
}
void gdt::ServiceMessage::clear_callbacks() { cb_handler.clear(); }
std::vector<gdt::ServiceParam *> *gdt::ServiceMessage::get_param_map() {
return &tlvs;
}
mink_utils::VariantParam *gdt::ServiceMessage::vpget(uint32_t id,
uint32_t index,
uint32_t fragment,
uint32_t context) {
return vpmap.get_param(id, index, fragment, context);
}
mink_utils::VariantParam *gdt::ServiceMessage::vpset(uint32_t id,
const std::string &s,
uint32_t index,
uint32_t fragment,
uint32_t context) {
return vpmap.set_cstr(id, s.c_str(), index, fragment, context);
}
gdt::ServiceMessageDone *gdt::ServiceMessage::get_sdone_hndlr() {
return &msg_done;
}
gdt::ServiceMessageNext *gdt::ServiceMessage::get_snext_hndlr() {
return &msg_next;
}
int gdt::ServiceMessage::signal_wait() {
// wait for signal
timespec ts;
clock_gettime(0, &ts);
ts.tv_sec += 5;
int sres = sem_wait(&smsg_sem);
// error check
if (sres == -1) {
return 1;
}
// ok
return 0;
}
int gdt::ServiceMessage::signal_post() { return sem_post(&smsg_sem); }
void gdt::ServiceMessage::set_idt_map(ParamIdTypeMap *idtm) { idt_map = idtm; }
gdt::ServiceStreamHandlerNext::ServiceStreamHandlerNext(): ssh_new(nullptr){}
void gdt::ServiceStreamHandlerNext::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
GDTCallbackArgs cb_args;
// check for params part
if ((in_msg->_body->_service_msg->_params != nullptr) &&
(in_msg->_body->_service_msg->_params->has_linked_data(*in_sess))) {
// get ID->TYPE map
ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// ServiceMessage pointer
auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG);
// nullptr check
if (smsg != nullptr) {
// fragmentation
bool frag = false;
asn1::ServiceMessage *sm = in_msg->_body->_service_msg;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < sm->_params->children.size(); i++) {
// check for value
if (!sm->_params
->get_child(i)
->_value) continue;
// check if value exists in current session
if (!sm->_params
->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!sm->_params
->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current sesion
if (!sm->_params
->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)sm->_params
->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
int extra_type = sm->_params
->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = ssh_new->smsg_m->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentatio flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)sm->_params
->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
int tmp_val_l = sm->_params
->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val, tmp_val_l);
// check for fragmentation
if ((sm->_params
->get_child(i)
->_value
->get_child(1)) &&
(sm->_params
->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = sm->_params
->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag (value
// length 1 and value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and type
sparam->index = sm->_params
->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and pointer to
// first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment pointer
smsg->set_frag_param(sparam);
sparam->fragment_index = 0;
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool (fragmented
// params are not retained in
// memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam) vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool (fragmented
// params are not retained in
// memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
ssh_new->smsg_m
->get_param_factory()
->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
ssh_new->smsg_m->stats.inc(
SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream->continue_sequence();
}
}
}
gdt::ServiceStreamHandlerDone::ServiceStreamHandlerDone(): ssh_new(nullptr){
}
void gdt::ServiceStreamHandlerDone::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG);
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
// get ID->TYPE map
ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// raw data length
int tmp_val_l = 0;
// fragmentation
bool frag = false;
// extra type
int extra_type;
GDTCallbackArgs cb_args;
asn1::ServiceMessage *sm = nullptr;
asn1::Parameters *p = nullptr;
if(!smsg) return;
if(!in_msg) goto stream_complete;
sm = in_msg->_body->_service_msg;
// in_msg is nullptr in case of stream timeout
// check for params part
if (!sm->_params) goto stream_pre_complete;
if (!sm->_params->has_linked_data(*in_sess)) goto stream_pre_complete;
p = sm->_params;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < p->children.size(); i++) {
// check for value
if (!p->get_child(i)->_value) continue;
// check if value exists in current session
if (!p->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!p->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current sesion
if (!p->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)p->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
extra_type = p->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = ssh_new->smsg_m
->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentatio flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
tmp_val_l = p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val,
tmp_val_l);
// check for fragmentation
if ((p->get_child(i)
->_value
->get_child(1)) &&
(p->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = p->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag (value
// length 1 and value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and type
sparam->index = p->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and
// pointer to first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment
// pointer
smsg->set_frag_param(sparam);
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool
// (fragmented params are
// not retained in memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last
// fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam != nullptr)
vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool
// (fragmented params are
// not retained in memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
ssh_new->smsg_m
->get_param_factory()
->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
ssh_new->smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream_pre_complete:
// set as completed if status is present and == ok (0)
if (asn1::node_exists(in_msg->_header->_status, *in_sess)) {
if (in_msg->_header->_status->linked_node->tlv->value[0] == 0)
smsg->set_complete(true);
// no status, set as completed
} else
smsg->set_complete(true);
stream_complete:
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream);
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARG_CLIENT,
stream->get_client());
smsg->process_callback(GDT_ET_SRVC_MSG_COMPLETE, &cb_args);
// check for pass param
auto smsg_pass = (ServiceMessage *)stream->get_param(SMSG_PT_PASS);
// if pass not set
// free message if auto_free flag was set (default)
if ((smsg_pass != smsg) && (smsg->get_auto_free())) {
ssh_new->smsg_m->free_smsg(smsg);
}
// remove params
stream->remove_param(SMSG_PT_SMSG);
stream->remove_param(SMSG_PT_PASS);
// smsg not allocated in new stream event
// error should be handled in GDT_ET_SRVC_MSG_ERROR handler
}
void gdt::ServiceStreamNewClient::run(GDTCallbackArgs *args) {
auto client = (gdt::GDTClient *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_CLIENT);
smsg_m->setup_client(client);
// user NEW CLIENT handler
if (usr_stream_nc_hndlr != nullptr)
usr_stream_nc_hndlr->run(args);
}
void gdt::ServiceStreamHandlerNew::run(GDTCallbackArgs *args) {
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
GDTCallbackArgs cb_args;
// check for body
if (!in_msg->_body) {
// NON ServiceMessage user handler
if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args);
return;
}
// check for ServiceMessage
if (!in_msg->_body->_service_msg->has_linked_data(*in_sess)) {
if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args);
return;
}
// set event handlers
stream->set_callback(gdt::GDT_ET_STREAM_NEXT, &ssh_next);
stream->set_callback(gdt::GDT_ET_STREAM_END, &ssh_done);
stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT, &ssh_done);
// create new ServiceMessage
ServiceMessage *smsg = smsg_m->new_smsg();
// nullptr check
if (!smsg) {
smsg_m->stats.inc(SST_RX_SMSG_POOL_EMPTY, 1);
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream);
smsg_m->process_callback(GDT_ET_SRVC_MSG_ERROR, &cb_args);
return;
}
// reset frag
smsg->set_frag_param(nullptr);
// reset callbacks
smsg->clear_callbacks();
// clear vpmap
smsg->vpmap.clear_params();
// set as incomplete
smsg->set_complete(false);
// clear stream params
stream->clear_params();
// set ServiceMessage as GDT stream param
stream->set_param(SMSG_PT_SMSG, smsg);
// reset auto free
smsg->set_auto_free(true);
// reset missing params
smsg->missing_params = false;
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG,
smsg);
smsg_m->process_callback(GDT_ET_SRVC_MSG_NEW, &cb_args);
asn1::ServiceMessage *sm = in_msg->_body->_service_msg;
asn1::Parameters *p = sm->_params;
// get ID->TYPE map
ParamIdTypeMap *idt_map = smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// raw data length
int tmp_val_l = 0;
// fragmentation
bool frag = false;
// extra type
int extra_type;
// check for params part
if (!p) goto stream_continue;
if (!p->has_linked_data(*in_sess)) goto stream_continue;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < p->children.size(); i++) {
// check for value
if (!p->get_child(i)->_value) continue;
// check if value exists in current session
if (!p->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!p->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current
// sesion
if (!p->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)p->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
extra_type = p->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = smsg_m->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentation flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
tmp_val_l = p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val,
tmp_val_l);
// check for fragmentation
if ((p->get_child(i)
->_value
->get_child(1)) &&
(p->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = p->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag
// (value length 1 and
// value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and
// type
sparam->index = p->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and
// pointer to first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment
// pointer
smsg->set_frag_param(sparam);
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool
// (fragmented params
// are not retained in
// memory)
smsg_m->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last
// fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam != nullptr)
vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool
// (fragmented params
// are not retained in
// memory)
smsg_m->get_param_factory()->free_param(sparam);
smsg_m->get_param_factory()->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream_continue:
// continue
stream->continue_sequence();
}
gdt::ServiceMsgManager::ServiceMsgManager(ParamIdTypeMap *_idt_map,
GDTCallbackMethod *_new_msg_hndlr,
GDTCallbackMethod *_nonsrvc_stream_hndlr,
unsigned int pool_size,
unsigned int param_pool_size) {
idt_map = _idt_map;
param_factory = new ServiceParamFactory(true, false, param_pool_size);
sem_init(&q_sem, 0, 0);
srvcs_hndlr.smsg_m = this;
srvcs_nc.smsg_m = this;
srvcs_hndlr.usr_stream_hndlr = _nonsrvc_stream_hndlr;
srvcs_hndlr.ssh_next.ssh_new = &srvcs_hndlr;
srvcs_hndlr.ssh_done.ssh_new = &srvcs_hndlr;
msg_pool.init(pool_size);
msg_pool.construct_objects();
cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, _new_msg_hndlr);
// set manager pointers
ServiceMessage *tmp_arr[pool_size];
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = msg_pool.allocate_constructed();
tmp_arr[i]->set_smsg_manager(this);
}
// return back to pool
for (unsigned int i = 0; i < pool_size; i++)
msg_pool.deallocate_constructed(tmp_arr[i]);
// random generator
timespec tmp_time;
clock_gettime(0, &tmp_time);
// stats
stats.register_item(SST_RX_SMSG_POOL_EMPTY);
stats.register_item(SST_RX_SPARAM_POOL_EMPTY);
}
gdt::ServiceMsgManager::~ServiceMsgManager() {
sem_destroy(&q_sem);
delete param_factory;
}
void gdt::ServiceMsgManager::generate_uuid(unsigned char *out) {
random_gen.generate(out, 16);
}
gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_hndlr() {
return &srvcs_hndlr;
}
gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_nc_hndlr() {
return &srvcs_nc;
}
void gdt::ServiceMsgManager::set_new_msg_handler(GDTCallbackMethod *hndlr) {
cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, hndlr);
}
void gdt::ServiceMsgManager::set_msg_err_handler(GDTCallbackMethod *hndlr) {
cb_handler.set_callback(GDT_ET_SRVC_MSG_ERROR, hndlr);
}
bool gdt::ServiceMsgManager::process_callback(GDTEventType type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(type, args);
}
void gdt::ServiceMsgManager::setup_server(GDTSession *gdts,
gdt::GDTCallbackMethod *_usr_stream_nc_hndlr,
gdt::GDTCallbackMethod *_usr_stream_hndlr) {
// set extra user stream handler
srvcs_nc.usr_stream_nc_hndlr = _usr_stream_nc_hndlr;
srvcs_nc.usr_stream_hndlr = _usr_stream_hndlr;
// set end event handler
gdts->set_callback(gdt::GDT_ET_CLIENT_NEW, &srvcs_nc);
}
void gdt::ServiceMsgManager::setup_client(GDTClient *gdtc) {
// nullptr check
if (gdtc == nullptr)
return;
// set end event handler
gdtc->set_callback(gdt::GDT_ET_STREAM_NEW, &srvcs_hndlr);
}
gdt::ServiceMessage *gdt::ServiceMsgManager::new_smsg() {
ServiceMessage *tmp = msg_pool.allocate_constructed();
return tmp;
}
int gdt::ServiceMsgManager::free_smsg(ServiceMessage *msg,
bool params_only,
bool clear_vpmap) {
// free params
std::vector<ServiceParam *> *params = msg->get_param_map();
ServiceParam *param = nullptr;
for (unsigned int i = 0; i < params->size(); i++) {
param = (*params)[i];
// check for temp linked buffer params
for (unsigned int j = 0; j < param->linked.size(); j++) {
param_factory->free_param(param->linked[j]);
}
param->linked.clear();
// free param
param_factory->free_param(param);
}
// check frag param
if (msg->get_frag_param() != nullptr) {
// check for temp linked buffer params in frag param
for (unsigned int j = 0; j < msg->get_frag_param()->linked.size();
j++) {
param_factory->free_param(msg->get_frag_param()->linked[j]);
}
msg->get_frag_param()->linked.clear();
// free frag param
param_factory->free_param(msg->get_frag_param());
}
// clear params
params->clear();
// clear vpmap
if (clear_vpmap)
msg->vpmap.clear_params();
// if freeing smsg also
if (!params_only) {
msg->params.clear_params();
// return to pool
int res = msg_pool.deallocate_constructed(msg);
// result
return res;
}
// ok
return 0;
}
gdt::ServiceParamFactory *gdt::ServiceMsgManager::get_param_factory() {
return param_factory;
}
gdt::ParamIdTypeMap *gdt::ServiceMsgManager::get_idt_map() { return idt_map; }
int gdt::ServiceMsgManager::vpmap_sparam_sync(ServiceMessage *msg,
const std::vector<ServiceParam*> *pmap) {
// freee sparams, do not clear vpmap
free_smsg(msg, true, false);
// vars
ServiceParam *param = nullptr;
bool err = false;
// process vpmap
for (mink_utils::VariantParamMap<uint32_t>::it_t it =
msg->vpmap.get_begin();
it != msg->vpmap.get_end(); it++) {
// skip pointer param type
if (it->second.get_type() == mink_utils::DPT_POINTER)
continue;
// skip context other then default 0
if (it->first.context != 0)
continue;
// allocate new service param
param = get_param_factory()->new_param(gdt::SPT_VARIANT);
// sanity check
if (param == nullptr) {
err = true;
break;
}
// set service param data from decoded param
param->set(&it->second);
// add service param to service message
msg->add_param(it->first.key, param, it->first.index);
}
// extra params
if(pmap != nullptr){
for(auto it = pmap->begin(); it != pmap->end(); it++){
// add service param to service message
msg->add_param((*it)->get_id(), (*it), (*it)->get_index());
}
}
// result
return err;
}
int gdt::ServiceMsgManager::send(ServiceMessage *msg,
GDTClient *gdtc,
const char *dtype,
const char *did,
bool async,
gdt::GDTCallbackMethod *on_sent) {
if ((msg != nullptr) && (gdtc != nullptr)) {
// start new GDT stream
GDTStream *gdt_stream = gdtc->allocate_stream_pool();
// if stream cannot be created, return err
if (gdt_stream == nullptr) {
gdtc->get_stats(GDT_OUTBOUND_STATS)
->strm_alloc_errors.add_fetch(1);
return 10;
}
// setup stream directly
gdt_stream->set_client(gdtc);
gdt_stream->reset(true);
gdt_stream->clear_callbacks();
gdt_stream->clear_params();
gdt_stream->set_destination(dtype, did);
unsigned int pc;
unsigned int bc;
unsigned int tbc = 0;
// param map
std::vector<ServiceParam *> *pmap = msg->get_param_map();
pc = pmap->size();
// calculate total param size (add extra 3 bytes for dual byte length
// and single byte tag)
ServiceParam *tmp_param = nullptr;
for (unsigned int i = 0; i < pmap->size(); i++) {
tmp_param = (*pmap)[i];
// check fragmentation
if (tmp_param->is_fragmented()) {
// -1 to exclude already included first fragment
pc += tmp_param->fragments - 1;
// add extra 3 bytes to size calculation (Tag + Length (BER
// Definite long))
}
}
// add extra buffer for fragmented params (used when streaming from non
// pre-allocated sources) max size is pps
ServiceParam *new_param = nullptr;
for (unsigned int i = 0; i < pmap->size(); i++) {
tmp_param = (*pmap)[i];
if (tmp_param->is_fragmented()) {
for (unsigned int j = 0; j < 4; j++) {
new_param = param_factory->new_param(tmp_param->type);
if (new_param != nullptr)
tmp_param->linked.push_back(new_param);
}
tmp_param->linked_index = 0;
}
}
// reset user handler from previous instance
msg->get_sdone_hndlr()->usr_method = nullptr;
// reset status from previous instance
msg->get_sdone_hndlr()->status = 0;
// set end event handler
gdt_stream->set_callback(gdt::GDT_ET_STREAM_END,
msg->get_sdone_hndlr());
gdt_stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT,
msg->get_sdone_hndlr());
// if async mode, set user handler
if (async)
msg->get_sdone_hndlr()->usr_method = on_sent;
// get handler
ServiceMessageNext *cb = msg->get_snext_hndlr();
// reset pos (param pos)
cb->pos = 0;
// reset pindex (param pos including fragments)
cb->pindex = 0;
cb->pc = pc;
// set callback
gdt_stream->set_callback(gdt::GDT_ET_STREAM_NEXT, cb);
// create body
asn1::GDTMessage *gdtm = gdt_stream->get_gdt_message();
// prepare body
if (gdtm->_body != nullptr) {
gdtm->_body->unlink(1);
gdtm->_body->_service_msg->set_linked_data(1);
} else {
gdtm->set_body();
gdtm->prepare();
}
asn1::ServiceMessage *sm = gdtm->_body->_service_msg;
// set params, allocate 10 initial children
if (!sm->_params) {
sm->set_params();
asn1::Parameters *p = sm->_params;
// set children, allocate more
for (int i = 0; i < 10; i++) {
p->set_child(i);
p->get_child(i)->set_value();
p->get_child(i)->_value->set_child(0);
p->get_child(i)->_value->set_child(1);
p->get_child(i)->_value->set_child(2);
p->get_child(i)->_value->set_child(3);
}
// prepare
asn1::prepare(sm, sm->parent_node);
}
// set service id
sm->_service_id->set_linked_data(1,
(unsigned char *)msg->get_service_idp(),
sizeof(uint32_t));
// set service action
sm->_service_action->set_linked_data(1,
(unsigned char *)msg->get_service_actionp(),
1);
// params
ServiceParam *sc_param = nullptr;
asn1::Parameters *params = gdtm->_body->_service_msg->_params;
// loop params
for (unsigned int j = 0;
(tbc < MAX_PARAMS_SIZE) && (cb->pos < pmap->size());
j++, cb->pos++, cb->pindex++) {
sc_param = (*pmap)[cb->pos];
// check if more allocations are needed
if (params->get_child(j) == nullptr) {
params->set_child(j);
params->get_child(j)->set_value();
params->get_child(j)->_value->set_child(0);
params->get_child(j)->_value->set_child(1);
params->get_child(j)->_value->set_child(2);
params->get_child(j)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// update total byte count
tbc += sc_param->data_size + 25;
// check if limit reached
if (tbc > MAX_PARAMS_SIZE)
break;
// set gdt param id and data
params->get_child(j)->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)->_value->get_child(0)->set_linked_data(1,
sc_param->data_p,
sc_param->data_size);
// check fragmentation
if (sc_param->is_fragmented()) {
params->get_child(j)->_value->get_child(1)->set_linked_data(1,
(unsigned char *)sc_param->get_fragmentation_p(),
1);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
// next fragment
++sc_param->fragment_index;
++j;
++cb->pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
// process fragments
while ((tbc < MAX_PARAMS_SIZE) && (sc_param->fragment_index < sc_param->fragments)) {
process_fragments(&bc, &tbc, sc_param, params, j);
// check if limit reached
if (tbc > MAX_PARAMS_SIZE)
break;
// set gdt values
params->get_child(j)->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)->_value->get_child(0)->set_linked_data(1,
sc_param->data_p,
bc);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
// check if last fragment, disable fragmentation flag (last
// fragment must not contain fragmentation flag)
if (sc_param->fragment_index == (sc_param->fragments - 1)) {
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_DONE,
1);
} else {
// set gdt fragmentation flag
params->get_child(j)
->_value->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_NEXT,
1);
}
// next
++sc_param->fragment_index;
++j;
++cb->pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
}
// break if fragmentation in progress and not finished (to skip
// increment, next call should process the same param again)
if (sc_param->fragment_index < sc_param->fragments)
break;
// rewind gdt param child count and packet index
else {
--j;
--cb->pindex;
}
// no fragmentation
} else {
params->get_child(j)->_value->get_child(1)->set_linked_data(1,
(unsigned char *)sc_param->get_fragmentation_p(),
1);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
}
}
// remove unused chidren
for (unsigned int i = cb->pindex; i < params->children.size(); i++)
params->get_child(i)->unlink(1);
// add to list of active streams directly
gdtc->add_stream(gdt_stream);
// start stream
gdt_stream->send(true);
// sync mode
if (!async) {
if (msg->signal_wait() == 1)
return 100;
else
return msg->get_sdone_hndlr()->status;
// async mode
} else {
// ok
return 0;
}
}
// err
return 1;
}
void gdt::ServiceMessageAsyncDone::run(GDTCallbackArgs *args) {
auto smsg = (gdt::ServiceMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARGS_SRVC_MSG);
smsg->get_smsg_manager()->free_smsg(smsg);
}
| 100,758 | 28,368 |
// KizuEngine Copyright (c) 2019 Jed Fakhfekh. This software is released under the MIT License.
#include "Core/Combat/KizuCombat.h"
| 135 | 54 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdn/v20180606/model/HttpHeaderRule.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace std;
HttpHeaderRule::HttpHeaderRule() :
m_headerModeHasBeenSet(false),
m_headerNameHasBeenSet(false),
m_headerValueHasBeenSet(false)
{
}
CoreInternalOutcome HttpHeaderRule::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("HeaderMode") && !value["HeaderMode"].IsNull())
{
if (!value["HeaderMode"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderMode` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerMode = string(value["HeaderMode"].GetString());
m_headerModeHasBeenSet = true;
}
if (value.HasMember("HeaderName") && !value["HeaderName"].IsNull())
{
if (!value["HeaderName"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderName` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerName = string(value["HeaderName"].GetString());
m_headerNameHasBeenSet = true;
}
if (value.HasMember("HeaderValue") && !value["HeaderValue"].IsNull())
{
if (!value["HeaderValue"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerValue = string(value["HeaderValue"].GetString());
m_headerValueHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void HttpHeaderRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_headerModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderMode";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerMode.c_str(), allocator).Move(), allocator);
}
if (m_headerNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerName.c_str(), allocator).Move(), allocator);
}
if (m_headerValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerValue.c_str(), allocator).Move(), allocator);
}
}
string HttpHeaderRule::GetHeaderMode() const
{
return m_headerMode;
}
void HttpHeaderRule::SetHeaderMode(const string& _headerMode)
{
m_headerMode = _headerMode;
m_headerModeHasBeenSet = true;
}
bool HttpHeaderRule::HeaderModeHasBeenSet() const
{
return m_headerModeHasBeenSet;
}
string HttpHeaderRule::GetHeaderName() const
{
return m_headerName;
}
void HttpHeaderRule::SetHeaderName(const string& _headerName)
{
m_headerName = _headerName;
m_headerNameHasBeenSet = true;
}
bool HttpHeaderRule::HeaderNameHasBeenSet() const
{
return m_headerNameHasBeenSet;
}
string HttpHeaderRule::GetHeaderValue() const
{
return m_headerValue;
}
void HttpHeaderRule::SetHeaderValue(const string& _headerValue)
{
m_headerValue = _headerValue;
m_headerValueHasBeenSet = true;
}
bool HttpHeaderRule::HeaderValueHasBeenSet() const
{
return m_headerValueHasBeenSet;
}
| 4,181 | 1,317 |
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/value.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/kumi.hpp>
#include <eve/function/bit_cast.hpp>
#include <eve/function/replace.hpp>
#include <eve/memory/aligned_ptr.hpp>
namespace eve::detail
{
// -----------------------------------------------------------------------------------------------
// simd Tuple case
template<kumi::product_type T, typename S, kumi::sized_product_type<T::size()> Ptr>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, Ptr ptrs) noexcept
requires std::same_as<abi_t<T, S>, bundle_>
{
kumi::for_each( [](auto v, auto p) { store(v, p); }, value, ptrs );
}
template< kumi::product_type T, typename S
, kumi::sized_product_type<T::size()> Ptr
, relative_conditional_expr C
>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
C const &c,
wide<T, S> const &value,
Ptr ptrs) noexcept
{
if constexpr ( C::has_alternative )
{
auto alt = [&]{
if constexpr ( kumi::product_type<typename C::alternative_type> ) return c.alternative;
else return c.alternative.storage();
}();
kumi::for_each( [&](auto v, auto part_alt, auto p) {
auto new_c = c.map_alternative([&](auto) { return part_alt; });
store[new_c](v, p);
}, value.storage(), alt, ptrs);
}
else
{
kumi::for_each( [&](auto v, auto p) { store[c](v, p); }, value.storage(), ptrs );
}
}
// -----------------------------------------------------------------------------------------------
// simd Regular case
template<real_scalar_value T, typename N>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept
requires std::same_as<abi_t<T, N>, emulated_>
{
apply<N::value>([&](auto... I) { ((*ptr++ = value.get(I)), ...); });
}
template<real_scalar_value T, typename N>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept
requires std::same_as<abi_t<T, N>, aggregated_>
{
value.storage().apply
( [&]<typename... Sub>(Sub&... v)
{
int k = 0;
((store(v, ptr + k), k += Sub::size()), ...);
}
);
}
// -----------------------------------------------------------------------------------------------
// simd Aligned case
template<real_scalar_value T, typename S, typename Lanes>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept
requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, emulated_>
{
store(value, ptr.get());
}
template<real_scalar_value T, typename S, typename Lanes>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept
requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, aggregated_>
{
auto cast = []<typename Ptr, typename Sub>(Ptr ptr, as<Sub>)
{
return eve::aligned_ptr<T, typename Sub::cardinal_type>{ptr.get()};
};
value.storage().apply
( [&]<typename... Sub>(Sub&... v)
{
int k = 0;
((store(v, cast(ptr, as<Sub>{}) + k), k += Sub::size()), ...);
}
);
}
template<simd_value T, relative_conditional_expr C, simd_compatible_ptr<T> Ptr>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
C const &cond,
T const &value,
Ptr ptr) noexcept
{
if constexpr ( C::is_complete && C::is_inverted ) store(value, ptr);
else if constexpr ( C::has_alternative ) store(replace_ignored(value, cond, cond.alternative), ptr);
else if constexpr ( C::is_complete ) return;
else if constexpr ( logical_simd_value<T> )
{
using mask_type_t = typename element_type_t<T>::mask_type;
if constexpr ( std::is_pointer_v<Ptr> ) store[cond](value.mask(), (mask_type_t*) ptr);
else
{
store[cond](value.mask(), typename Ptr::template rebind<mask_type_t>{(mask_type_t*)ptr.get()});
}
}
else if constexpr ( !std::is_pointer_v<Ptr> ) store[cond](value, ptr.get());
else if constexpr ( has_emulated_abi_v<T> )
{
auto offset = cond.offset( as<T>{} );
auto count = cond.count( as<T>{} );
using e_t = element_type_t<T>;
auto* src = (e_t*)(&value.storage());
std::memcpy((void*)(ptr + offset), (void*)(src + offset), sizeof(e_t) * count);
}
else
{
using e_t = element_type_t<T>;
alignas(sizeof(T)) std::array<e_t, T::size()> storage;
store(value, eve::aligned_ptr<e_t, typename T::cardinal_type>(storage.begin()));
auto offset = cond.offset( as<T>{} );
auto count = cond.count( as<T>{} );
std::memcpy((void*)(ptr + offset), (void*)(storage.begin() + offset), sizeof(e_t) * count);
}
}
template<real_scalar_value T, typename S>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
logical<wide<T, S>> const &value,
logical<T>* ptr) noexcept
{
store(value.mask(), (typename logical<T>::mask_type*) ptr);
}
template<real_scalar_value T, typename S,typename Lanes>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
logical<wide<T, S>> const &value,
aligned_ptr<logical<T>, Lanes> ptr) noexcept
requires (
requires {store(value.mask(), aligned_ptr<typename logical<T>::mask_type, Lanes>{}); } )
{
using mask_type_t = typename logical<T>::mask_type;
store(value.mask(), aligned_ptr<mask_type_t, Lanes>{(mask_type_t*)ptr.get()});
}
}
| 6,162 | 2,093 |
#include "MiniLua/table_functions.hpp"
#include "MiniLua/utils.hpp"
#include "MiniLua/values.hpp"
#include <algorithm>
#include <cmath>
#include <future>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#include <vector>
namespace minilua {
auto static try_value_is_int(Value s, const std::string& method_name, int arg_index) -> int {
try {
if (s.is_number()) {
return std::get<Number>(s).try_as_int();
}
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number expected, got " + s.type() + ")");
}
auto tmp = Number(1);
try {
if (s.is_string()) {
Value v = s.to_number();
if (v == Nil()) {
throw std::runtime_error("");
}
tmp = std::get<Number>(v);
} else if (!s.is_number()) {
throw std::runtime_error("");
}
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number expected, got " + s.type() + ")");
}
try {
return tmp.try_as_int();
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number has no integer representation)");
}
}
auto create_table_table(MemoryAllocator* allocator) -> Table {
Table table(allocator);
table.set("concat", table::concat);
table.set("insert", table::insert);
table.set("move", table::insert);
table.set("pack", table::pack);
table.set("remove", table::remove);
table.set("sort", table::sort);
table.set("unpack", table::unpack);
return table;
}
namespace table {
auto concat(const CallContext& ctx) -> Value {
// Didn't add an origin because i have no idea how i should reverse this because i would need
// the seperator to split it back up
std::string result;
auto list = ctx.arguments().get(0);
auto sep = ctx.arguments().get(1);
auto i = ctx.arguments().get(2);
auto j = ctx.arguments().get(3);
return std::visit(
overloaded{
[&result](const Table& list, Nil /*unused*/, Nil /*unused*/, Nil /*unused*/) -> Value {
for (int m = 1; m <= list.border(); m++) {
Value v = list.get(m);
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
}
return Value(result);
},
[&result,
&sep](const Table& list, auto /*sep*/, Nil /*unused*/, Nil /*unused*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
for (int m = 1; m <= list.border(); m++) {
Value v = list.get(m);
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != list.border()) {
result += s.value;
}
}
return Value(result);
},
[&result, &sep,
&i](const Table& list, auto /*sep*/, auto /*i*/, Nil /*unused*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
int m = try_value_is_int(std::move(i), "concat", 3);
for (; m <= list.border(); m++) {
Value v;
if (list.has(m)) {
v = list.get(m);
} else {
throw std::runtime_error(
"invalid value (nil) at index " + std::to_string(m) + " for 'concat'");
}
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != list.border()) {
result += s.value;
}
}
return Value(result);
},
[&result, &sep, &i,
&j](const Table& list, auto /*sep*/, auto /*i*/, auto /*j*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
int m = try_value_is_int(std::move(i), "concat", 3);
int j_int = try_value_is_int(std::move(j), "concat", 4);
;
for (; m <= j_int; m++) {
Value v;
if (list.has(m)) {
v = list.get(m);
} else {
throw std::runtime_error(
"invalid value (nil) at index " + std::to_string(m) + " for 'concat'");
}
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != j_int) {
result += s.value;
}
}
return Value(result);
},
[](auto list, auto /*unused*/, auto /*unused*/, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'concat' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), sep.raw(), i.raw(), j.raw());
}
void insert(const CallContext& ctx) {
auto list = ctx.arguments().get(0);
auto pos = ctx.arguments().get(1);
auto value = ctx.arguments().get(2);
// Casulty because we return nil if no argument is given, but nil could be inserted. This edge
// case throws an error in our program, in lua the insertion works as intended I don't have an
// idea how to do that besides this way.
if (ctx.arguments().size() < 3) {
throw std::runtime_error("wrong number of arguments to 'insert'");
}
std::visit(
overloaded{
[&value](Table& table, Nil /*unused*/) {
Number pos = table.border() + 1;
table.set(pos, value);
},
[&pos, &value](Table& table, auto /*pos*/) {
int p = try_value_is_int(pos, "insert", 2);
if (p < 1 || p > table.border()) {
throw std::runtime_error(
"bad argument #2 to 'insert' (position out of bounds)");
} else {
// move every element one to the right so make space for the new element that is
// inserted if pos is already occupied
for (int i = table.border(); i >= p; i--) {
table.set(i + 1, table.get(i));
}
}
table.set(p, value);
},
[](auto table, auto /*unused*/) {
throw std::runtime_error(
"bad argument #1 to 'insert' (table expected, got " + std::string(table.TYPE) +
")");
}},
list.raw(), pos.raw());
}
auto move(const CallContext& ctx) -> Value {
// No origin needed because a2 is already given as an existing value
auto a1 = ctx.arguments().get(0);
auto f = ctx.arguments().get(1);
auto e = ctx.arguments().get(2);
auto t = ctx.arguments().get(3);
auto a2 = ctx.arguments().get(4);
return std::visit(
overloaded{
[&f, &e, &t](Table a1, Nil /*unused*/) -> Value {
int fi = try_value_is_int(f, "move", 2);
int ei = try_value_is_int(e, "move", 3);
int ti = try_value_is_int(t, "move", 4);
for (; fi <= ei; fi++) {
a1.set(ti, a1.get(fi));
ti++;
}
return a1;
},
[&f, &e, &t](const Table& a1, Table a2) -> Value {
int fi = try_value_is_int(f, "move", 2);
int ei = try_value_is_int(e, "move", 3);
int ti = try_value_is_int(t, "move", 4);
for (; fi <= ei; fi++) {
a2.set(ti, a1.get(fi));
ti++;
}
return a2;
},
[](const Table& /*unused*/, auto a2) -> Value {
throw std::runtime_error(
"bad argument #5 to 'move' (table expected, got " + std::string(a2.TYPE) + ")");
},
[](auto a1, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'move' (table expected, got " + std::string(a1.TYPE) + ")");
}},
a1.raw(), a2.raw());
}
auto pack(const CallContext& ctx) -> Value {
Origin origin = Origin(MultipleArgsOrigin{
.values = std::make_shared<Vallist>(ctx.arguments()),
.location = ctx.call_location(),
.reverse = [](const Value& new_value,
const Vallist& args) -> std::optional<SourceChangeTree> {
Table t = std::get<Table>(new_value);
SourceChangeCombination trees;
auto it = args.begin();
for (const auto& [key, value] : t) {
if (key.type() != Number::TYPE || std::get<Number>(key).try_as_int() < 1 ||
std::get<Number>(key).try_as_int() > t.border() ||
std::get<Number>(key).try_as_int() > args.size()) {
break;
}
auto sct = *it->force(value);
trees.add(sct);
it++;
}
return SourceChangeTree(trees);
}});
Table t = Table();
int i = 1;
for (const auto& a : ctx.arguments()) {
t.set(i++, a);
}
return Value(t).with_origin(origin);
}
auto remove(const CallContext& ctx) -> Value {
// Doesn't need an origin because the value that is returned already should has one since it
// isn't generated new
auto list = ctx.arguments().get(0);
auto pos = ctx.arguments().get(1);
return std::visit(
overloaded{
[](Table list, Nil /*unused*/) -> Value {
auto tmp = list.get(list.border());
list.remove(list.border());
return tmp;
},
[&pos](Table list, auto /*pos*/) -> Value {
int posi = try_value_is_int(pos, "remove", 2);
if (posi > list.border() + 1 || (posi < 1 && list.border() != 0)) {
throw std::runtime_error(
"bad argument #2 to 'remove' (position out of bounds)");
}
auto tmp = list.get(posi);
if (posi == list.border() + 1) {
list.remove(posi);
return tmp;
}
for (int i = posi + 1; i <= list.border(); i++) {
list.set(posi, list.get(i));
posi++;
}
list.remove(list.border());
return tmp;
},
[](auto list, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'remove' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), pos.raw());
}
void sort(const CallContext& ctx) {
auto list = ctx.arguments().get(0);
auto comp = ctx.arguments().get(1);
std::visit(
overloaded{
[](Table list, Nil /*unused*/) {
std::vector<Value> content;
for (int i = 1; i <= list.border(); i++) {
content.push_back(list.get(i));
}
std::sort(content.begin(), content.end(), [](const Value& a, const Value& b) {
return std::get<Bool>(a.less_than(b)).value;
});
for (int i = 1; i <= list.border(); i++) {
list.set(i, content.at(i - 1));
}
},
[&ctx](Table list, const Function& comp) {
std::vector<Value> content;
for (int i = 1; i <= list.border(); i++) {
content.push_back(list.get(i));
}
std::sort(
content.begin(), content.end(),
[&ctx, &comp](const Value& a, const Value& b) -> bool {
auto c = ctx.make_new(Vallist{a, b});
auto erg = comp.call(c).values().get(0);
// More arguments than 2 are possible, but they are always Nil.
// 2 arguments must be there always since we must compare two values
if (ctx.arguments().size() >= 2 && erg.type() == "boolean") {
return std::get<Bool>(erg).value;
} else {
throw std::runtime_error("invalid order function for sorting");
}
});
for (int i = 1; i <= list.border(); i++) {
list.set(i, content.at(i - 1));
}
},
[](const Table& /*unused*/, auto a) {
throw std::runtime_error(
"bad argument #2 to 'sort' (function expected, got " + std::string(a.TYPE) +
")");
},
[](auto list, auto /*unused*/) {
throw std::runtime_error(
"bad argument #1 to 'sort' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), comp.raw());
}
auto unpack(const CallContext& ctx) -> Vallist {
// It only returns the Values of the Table, so no new values are generated and every value in
// the vallist should keep its origin i think
std::vector<Value> vector;
auto list = ctx.arguments().get(0);
auto i = ctx.arguments().get(1);
auto j = ctx.arguments().get(2);
return std::visit(
overloaded{
[&vector](const Table& list, Nil /*unused*/, Nil /*unused*/) -> Vallist {
for (int i = 1; i <= list.border(); i++) {
auto v = list.get(i);
vector.push_back(v);
}
return Vallist(vector);
},
[&vector, &i](const Table& list, auto /*i*/, Nil /*unused*/) {
int i_int = try_value_is_int(i, "unpack", 2);
for (; i_int <= list.border(); i_int++) {
vector.push_back(list.get(i_int));
}
return Vallist(vector);
},
[&vector, &i, &j](const Table& list, auto /*i*/, auto /*j*/) {
int i_int = try_value_is_int(i, "unpack", 2);
int j_int = try_value_is_int(j, "unpack", 3);
for (; i_int <= j_int; i_int++) {
vector.push_back(list.get(i_int));
}
return Vallist(vector);
},
[](auto list, auto /*unused*/, auto /*unused*/) -> Vallist {
throw std::runtime_error(
"bad argument #1 for 'unpack' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), i.raw(), j.raw());
}
} // end namespace table
} // end namespace minilua
| 17,039 | 4,860 |
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main()
{
char str[80];
const char s[2] = "-";
char *token;
clrscr();
printf("Enter String for tokenization: ");
gets(str);
token = strtok(str, s);
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
getch();
return(0);
}
| 404 | 156 |
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <algorithm>
#include <type_traits>
#include "helper_search_scheme.hpp"
#include <seqan3/search/algorithm/detail/search_scheme_algorithm.hpp>
#include <gtest/gtest.h>
template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme>
void error_distributions(auto & expected, auto & actual)
{
if constexpr (precomputed_scheme)
{
auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>};
seqan3::search_scheme_error_distribution(actual, oss);
seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error,
max_error,
oss.front().blocks()));
}
else
{
auto const & ss{seqan3::detail::compute_ss(min_error, max_error)};
seqan3::search_scheme_error_distribution(actual, ss);
seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error,
max_error,
ss.front().blocks()));
}
std::sort(expected.begin(), expected.end());
std::sort(actual.begin(), actual.end());
}
TEST(search_scheme_test, error_distribution_coverage_optimum_search_schemes)
{
std::vector<std::vector<uint8_t> > expected, actual;
error_distributions<0, 0, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 1, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 1, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
}
TEST(search_scheme_test, error_distribution_coverage_computed_search_schemes)
{
std::vector<std::vector<uint8_t> > expected, actual;
error_distributions<0, 0, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 1, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 1, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 5, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 6, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<7, 7, false>(expected, actual);
EXPECT_EQ(actual, expected);
}
template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme>
bool check_disjoint_search_scheme()
{
std::vector<std::vector<uint8_t> > error_distributions;
auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>};
seqan3::search_scheme_error_distribution(error_distributions, oss);
uint64_t size = error_distributions.size();
std::sort(error_distributions.begin(), error_distributions.end());
error_distributions.erase(std::unique(error_distributions.begin(),
error_distributions.end()),
error_distributions.end());
return size == error_distributions.size();
}
TEST(search_scheme_test, error_distribution_disjoint_optimum_search_schemes)
{
bool ret;
ret = check_disjoint_search_scheme<0, 0, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 1, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 2, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 3, false>();
EXPECT_TRUE(ret);
}
| 5,392 | 1,711 |
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include "../libraries/core/messages.hpp"
#include "../libraries/core/serializers.hpp"
#include "../tests/utils.hpp"
//#include "worker.h"
#include "worker.hpp"
#include "handler.h"
Worker::Worker(int socket_fd) {
this->socket_fd = socket_fd;
}
std::vector<u_int8_t> open_handler(std::vector<u_int8_t> byte_request) {
std::cout << "OPEN" << std::endl;
OpenRequest request = DeserializeToOpenRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " path: " << request.path << std::endl;
std::cout << " oflag: " << request.oflag << std::endl;
std::cout << " mode: " << request.mode << std::endl;
int result = open(request.path.c_str(), request.oflag, request.mode);
OpenResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " fd: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeOpenResponse(response);
return byte_response;
}
std::vector<u_int8_t> read_handler(std::vector<u_int8_t> byte_request) {
std::cout << "READ" << std::endl;
ReadRequest request = DeserializeToReadRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " count: " << request.count << std::endl;
std::vector<u_int8_t> buf = std::vector<u_int8_t>(request.count);
int result = read(request.fd, buf.data(), request.count);
buf.resize(result);
ReadResponse response = {result, buf, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeReadResponse(response);
return byte_response;
}
std::vector<u_int8_t> write_handler(std::vector<u_int8_t> byte_request) {
std::cout << "WRITE" << std::endl;
WriteRequest request = DeserializeToWriteRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " buf_size: " << request.buf.size() << std::endl;
int result = write(request.fd, request.buf.data(), request.buf.size());
WriteResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeWriteResponse(response);
return byte_response;
};
std::vector<u_int8_t> lseek_handler(std::vector<u_int8_t> byte_request) {
std::cout << "LSEEK" << std::endl;
LseekRequest request = DeserializeToLseekRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " offset: " << request.offset << std::endl;
std::cout << " whence: " << request.whence << std::endl;
off_t result = lseek(request.fd, request.offset, request.whence);
LseekResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeLseekResponse(response);
return byte_response;
};
std::vector<u_int8_t> close_handler(std::vector<u_int8_t> byte_request) {
std::cout << "CLOSE" << std::endl;
CloseRequest request = DeserializeToCloseRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
int result = close(request.fd);
CloseResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeCloseResponse(response);
return byte_response;
};
std::vector<u_int8_t> unlink_handler(std::vector<u_int8_t> byte_request) {
std::cout << "UNLINK" << std::endl;
UnlinkRequest request = DeserializeToUnlinkRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " pathname: " << request.pathname << std::endl;
int result = unlink(request.pathname.c_str());
UnlinkResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeUnlinkResponse(response);
return byte_response;
};
//
std::vector<u_int8_t> opendir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "OPENDIR" << std::endl;
OpendirRequest request = DeserializeToOpendirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " name: " << request.name << std::endl;
int result = -1;
DIR* dirstream = opendir(request.name.c_str());
if (dirstream != nullptr)
result = dirfd(dirstream);
OpendirResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeOpendirResponse(response);
return byte_response;
};
std::vector<u_int8_t> readdir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "READDIR" << std::endl;
ReaddirRequest request = DeserializeToReaddirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " dirfd: " << request.dirfd << std::endl;
int isDirentNull = 0;
DIR *dirp = fdopendir(request.dirfd);
dirent result;
if (dirp == nullptr)
isDirentNull = 1;
else
{
dirent* resultPtr = readdir(dirp);
if (resultPtr == nullptr)
isDirentNull = 1;
else
memcpy((void *)&result,resultPtr,sizeof(result));
}
ReaddirResponse response = {isDirentNull, result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result.d_name << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeReaddirResponse(response);
return byte_response;
};
std::vector<u_int8_t> closedir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "CLOSEDIR" << std::endl;
ClosedirRequest request = DeserializeToClosedirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " dirfd: " << request.dirfd << std::endl;
int result = -1;
DIR *dirp = fdopendir(request.dirfd);
if (dirp != nullptr)
result = closedir(dirp);
ClosedirResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeClosedirResponse(response);
return byte_response;
};
std::vector<u_int8_t> make_response(std::vector<u_int8_t> byte_request) {
MessageParser parser = MessageParser(byte_request);
switch (parser.readMessageType()) {
case MessageType::OPEN_REQUEST:
return open_handler(byte_request);
case MessageType::READ_REQUEST:
return read_handler(byte_request);
case MessageType::WRITE_REQUEST:
return write_handler(byte_request);
case MessageType::LSEEK_REQUEST:
return lseek_handler(byte_request);
case MessageType::CLOSE_REQUEST:
return close_handler(byte_request);
case MessageType::UNLINK_REQUEST:
return unlink_handler(byte_request);
case MessageType::OPENDIR_REQUEST:
return opendir_handler(byte_request);
case MessageType::READDIR_REQUEST:
return readdir_handler(byte_request);
case MessageType::CLOSEDIR_REQUEST:
return closedir_handler(byte_request);
default:
return std::vector<u_int8_t>{0, 0, 0, 0, 0};
}
}
void Worker::run() {
if(!authenticateUser()) {
close(socket_fd);
return;
}
std::vector<u_int8_t> byte_request;
std::vector<u_int8_t> byte_response;
while(true){
try{
byte_request = receiveMessage(socket_fd);
byte_response = handler.make_response(byte_request);
sendMessage(socket_fd, byte_response);
}
catch (std::ios_base::failure&) {
std::cout << "Ending connection with client" << std::endl;
close(socket_fd);
break;
}
}
}
std::thread Worker::spawn() {
return std::thread( [this] { this->run(); } );
}
bool Worker::authenticateUser() {
std::vector<u_int8_t> byte_request = receiveMessage(socket_fd);
MessageParser parser = MessageParser(byte_request);
if(parser.readMessageType() != MessageType::AUTHENTICATE_REQUEST)
return false;
AuthenticateResponse authenticateResponse = handler.authenticate_handler(byte_request);
bool isAuthenticated = authenticateResponse.result == 0;
sendMessage(socket_fd, SerializeAuthenticateResponse(authenticateResponse));
return isAuthenticated;
}
| 9,374 | 3,297 |
/*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include <cuda_runtime.h>
namespace isaac {
// Converts a YUV420 (encoded as NV21) image bound to texture channels to RGB
void ConvertNv21ToRgb(cudaTextureObject_t y_channel, cudaTextureObject_t uv_channel,
unsigned char* rgb_output, unsigned int width, unsigned int height,
unsigned int output_pitch);
} // namespace isaac
| 790 | 225 |
#ifndef ML_RIFFBASE_HPP
#define ML_RIFFBASE_HPP
#include <cstddef>
#include <cstdint>
#include <ios>
#include <memory>
#include "../Source/SourceBase.hpp"
class RIFFDirBase;
class RIFFBase {
public:
enum class Type {
Chunk,
List,
Root,
};
protected:
RIFFDirBase* parent;
public:
RIFFBase();
virtual ~RIFFBase() = default;
virtual Type GetType() const = 0;
virtual std::streamsize GetOffset() const;
virtual std::streamsize GetSize() const = 0;
virtual std::shared_ptr<SourceBase> GetSource() = 0;
virtual void SetParent(RIFFDirBase* parent);
virtual void CreateSource();
};
#endif
| 627 | 235 |
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the Matroska parser
// library, which allows clients to handle a Matroska format file.
#include <memory>
#include "mkvreader.hpp"
#include "mkvparser.hpp"
#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
static const wchar_t* utf8towcs(const char* str) {
if (str == NULL)
return NULL;
// TODO: this probably requires that the locale be
// configured somehow:
const size_t size = mbstowcs(NULL, str, 0);
if (size == 0)
return NULL;
wchar_t* const val = new wchar_t[size + 1];
mbstowcs(val, str, size);
val[size] = L'\0';
return val;
}
bool InputHasCues(const mkvparser::Segment* const segment) {
const mkvparser::Cues* const cues = segment->GetCues();
if (cues == NULL)
return false;
while (!cues->DoneParsing())
cues->LoadCuePoint();
const mkvparser::CuePoint* const cue_point = cues->GetFirst();
if (cue_point == NULL)
return false;
return true;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
printf("\t\t\tMkv Parser Sample Application\n");
printf("\t\t\tUsage: \n");
printf("\t\t\t ./sample [input file] \n");
printf("\t\t\t ./sample sample.mkv \n");
return -1;
}
using namespace mkvparser;
MkvReader reader;
if (reader.Open(argv[1])) {
printf("\n Filename is invalid or error while opening.\n");
return -1;
}
int maj, min, build, rev;
GetVersion(maj, min, build, rev);
printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);
long long pos = 0;
EBMLHeader ebmlHeader;
ebmlHeader.Parse(&reader, pos);
printf("\t\t\t EBML Header\n");
printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
printf("\t\tPos\t\t\t: %lld\n", pos);
typedef mkvparser::Segment seg_t;
seg_t* pSegment_;
long long ret = seg_t::CreateInstance(&reader, pos, pSegment_);
if (ret) {
printf("\n Segment::CreateInstance() failed.");
return -1;
}
const std::auto_ptr<seg_t> pSegment(pSegment_);
ret = pSegment->Load();
if (ret < 0) {
printf("\n Segment::Load() failed.");
return -1;
}
const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
const long long duration_ns = pSegmentInfo->GetDuration();
const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
const wchar_t* const pTitle = utf8towcs(pTitle_);
const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);
const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);
printf("\n");
printf("\t\t\t Segment Info\n");
printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
printf("\t\tDuration\t\t: %lld\n", duration_ns);
const double duration_sec = double(duration_ns) / 1000000000;
printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);
if (pTitle == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else {
printf("\t\tTrack Name\t\t: %ls\n", pTitle);
delete[] pTitle;
}
if (pMuxingApp == NULL)
printf("\t\tMuxing App\t\t: NULL\n");
else {
printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
delete[] pMuxingApp;
}
if (pWritingApp == NULL)
printf("\t\tWriting App\t\t: NULL\n");
else {
printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
delete[] pWritingApp;
}
// pos of segment payload
printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);
// size of segment payload
printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);
const mkvparser::Tracks* pTracks = pSegment->GetTracks();
unsigned long track_num = 0;
const unsigned long num_tracks = pTracks->GetTracksCount();
printf("\n\t\t\t Track Info\n");
while (track_num != num_tracks) {
const Track* const pTrack = pTracks->GetTrackByIndex(track_num++);
if (pTrack == NULL)
continue;
const long trackType = pTrack->GetType();
const long trackNumber = pTrack->GetNumber();
const unsigned long long trackUid = pTrack->GetUid();
const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());
printf("\t\tTrack Type\t\t: %ld\n", trackType);
printf("\t\tTrack Number\t\t: %ld\n", trackNumber);
printf("\t\tTrack Uid\t\t: %lld\n", trackUid);
if (pTrackName == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else {
printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
delete[] pTrackName;
}
const char* const pCodecId = pTrack->GetCodecId();
if (pCodecId == NULL)
printf("\t\tCodec Id\t\t: NULL\n");
else
printf("\t\tCodec Id\t\t: %s\n", pCodecId);
const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
const wchar_t* const pCodecName = utf8towcs(pCodecName_);
if (pCodecName == NULL)
printf("\t\tCodec Name\t\t: NULL\n");
else {
printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
delete[] pCodecName;
}
if (trackType == mkvparser::Track::kVideo) {
const VideoTrack* const pVideoTrack =
static_cast<const VideoTrack*>(pTrack);
const long long width = pVideoTrack->GetWidth();
printf("\t\tVideo Width\t\t: %lld\n", width);
const long long height = pVideoTrack->GetHeight();
printf("\t\tVideo Height\t\t: %lld\n", height);
const double rate = pVideoTrack->GetFrameRate();
printf("\t\tVideo Rate\t\t: %f\n", rate);
}
if (trackType == mkvparser::Track::kAudio) {
const AudioTrack* const pAudioTrack =
static_cast<const AudioTrack*>(pTrack);
const long long channels = pAudioTrack->GetChannels();
printf("\t\tAudio Channels\t\t: %lld\n", channels);
const long long bitDepth = pAudioTrack->GetBitDepth();
printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);
const double sampleRate = pAudioTrack->GetSamplingRate();
printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
const long long codecDelay = pAudioTrack->GetCodecDelay();
printf("\t\tAudio Codec Delay\t\t: %lld\n", codecDelay);
const long long seekPreRoll = pAudioTrack->GetSeekPreRoll();
printf("\t\tAudio Seek Pre Roll\t\t: %lld\n", seekPreRoll);
}
}
printf("\n\n\t\t\t Cluster Info\n");
const unsigned long clusterCount = pSegment->GetCount();
printf("\t\tCluster Count\t: %ld\n\n", clusterCount);
if (clusterCount == 0) {
printf("\t\tSegment has no clusters.\n");
return -1;
}
const mkvparser::Cluster* pCluster = pSegment->GetFirst();
while ((pCluster != NULL) && !pCluster->EOS()) {
const long long timeCode = pCluster->GetTimeCode();
printf("\t\tCluster Time Code\t: %lld\n", timeCode);
const long long time_ns = pCluster->GetTime();
printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);
const BlockEntry* pBlockEntry;
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) // error
{
printf("\t\tError parsing first block of cluster\n");
fflush(stdout);
return -1;
}
while ((pBlockEntry != NULL) && !pBlockEntry->EOS()) {
const Block* const pBlock = pBlockEntry->GetBlock();
const long long trackNum = pBlock->GetTrackNumber();
const unsigned long tn = static_cast<unsigned long>(trackNum);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
printf("\t\t\tBlock\t\t:UNKNOWN TRACK TYPE\n");
else {
const long long trackType = pTrack->GetType();
const int frameCount = pBlock->GetFrameCount();
const long long time_ns = pBlock->GetTime(pCluster);
const long long discard_padding = pBlock->GetDiscardPadding();
printf("\t\t\tBlock\t\t:%s,%s,%15lld,%lld\n",
(trackType == mkvparser::Track::kVideo) ? "V" : "A",
pBlock->IsKey() ? "I" : "P", time_ns, discard_padding);
for (int i = 0; i < frameCount; ++i) {
const Block::Frame& theFrame = pBlock->GetFrame(i);
const long size = theFrame.len;
const long long offset = theFrame.pos;
printf("\t\t\t %15ld,%15llx\n", size, offset);
}
}
status = pCluster->GetNext(pBlockEntry, pBlockEntry);
if (status < 0) {
printf("\t\t\tError parsing next block of cluster\n");
fflush(stdout);
return -1;
}
}
pCluster = pSegment->GetNext(pCluster);
}
if (InputHasCues(pSegment.get())) {
// Walk them.
const mkvparser::Cues* const cues = pSegment->GetCues();
const mkvparser::CuePoint* cue = cues->GetFirst();
int cue_point_num = 1;
printf("\t\tCues\n");
do {
for (track_num = 1; track_num != num_tracks; ++track_num) {
const mkvparser::Track* const track =
pTracks->GetTrackByNumber(track_num);
const mkvparser::CuePoint::TrackPosition* const track_pos =
cue->Find(track);
if (track_pos != NULL) {
const char track_type =
(track->GetType() == mkvparser::Track::kVideo) ? 'V' : 'A';
printf(
"\t\t\tCue Point %4d Track %3lu(%c) Time %14lld "
"Block %4lld Pos %8llx\n",
cue_point_num, track_num, track_type,
cue->GetTime(pSegment.get()), track_pos->m_block,
track_pos->m_pos);
}
}
cue = cues->GetNext(cue);
++cue_point_num;
} while (cue != NULL);
}
fflush(stdout);
return 0;
} | 10,185 | 3,761 |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/plugin/poplar/driver/passes/io_tiles_placer.h"
#include <algorithm>
#include <map>
#include <queue>
#include <utility>
#include <vector>
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/remote_parameter.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/xla/service/call_graph.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_value.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace xla {
namespace poplarplugin {
Status SetIoTileset(HloInstruction* inst) {
TF_ASSIGN_OR_RETURN(auto backend_config,
inst->backend_config<PoplarBackendConfig>());
backend_config.set_tileset(TILESET_IO_TILES);
return inst->set_backend_config(backend_config);
}
Status AssignToIoTilesAndPropagateToGteUsers(HloInstruction* inst) {
VLOG(3) << "Placing on IO tiles: " << inst->ToShortString();
TF_RETURN_IF_ERROR(SetIoTileset(inst));
for (auto* gte : inst->users()) {
if (gte->opcode() == HloOpcode::kGetTupleElement) {
TF_RETURN_IF_ERROR(AssignToIoTilesAndPropagateToGteUsers(gte));
}
}
return Status::OK();
}
bool IsInSerialPipeline(const HloInstruction* inst,
const CallGraph& call_graph) {
const auto callers = call_graph.GetNode(inst->parent()).caller_callsites();
return callers.size() == 1 && IsPipelineOp(callers[0].instruction()) &&
IsBatchSerializedPipelineOp(callers[0].instruction());
}
static int64 GetMaxAvailableIoBytes(
const int64 num_io_tiles, const int64 bytes_per_io_tile,
const double available_io_tile_memory_proportion) {
return static_cast<int64>(num_io_tiles * bytes_per_io_tile *
available_io_tile_memory_proportion);
}
static int64 GetInstructionBufferSize(const HloInstruction* inst) {
const auto& shape = inst->shape();
// The host exchange instructions are either 1 to 1 or 1 to token so
// only need to look at either result of operand
if (shape.IsToken()) {
// if token sum up size of all operands
return absl::c_accumulate(inst->operands(), static_cast<int64>(0),
[](int64 sum, const HloInstruction* i) {
return sum + GetInstructionBufferSize(i);
});
}
return GetByteSizeOfTotalShape(shape);
}
int64 GetMaxLiveBytes(const HloInstructionSequence& potential_io_tile_insts) {
// Looks like the Heap simulator doesn't really work for this purpose
// as none of these instructions allocate. Use just accumulation of size
// until poplar specific liveness simulator is implemented
int64 ans = absl::c_accumulate(potential_io_tile_insts.instructions(),
static_cast<int64>(0),
[](int64 sum, const HloInstruction* inst) {
return sum + GetInstructionBufferSize(inst);
});
return ans;
}
bool ShouldBeOnIoTiles(const HloInstruction* inst,
const CallGraph& call_graph) {
switch (inst->opcode()) {
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
// Currently incompatible with batch serial pipeline lowering.
return !IsInSerialPipeline(inst, call_graph);
case HloOpcode::kCustomCall:
return IsPoplarInstruction(RemoteParameterLoad)(inst) ||
IsPoplarInstruction(RemoteParameterStore)(inst) ||
IsPoplarInstruction(BufferLoadSlice)(inst) ||
IsPoplarInstruction(BufferStoreSlice)(inst) ||
IsPoplarInstruction(RecvFromHost)(inst) ||
IsPoplarInstruction(SendToHost)(inst);
default:
return false;
}
}
StatusOr<bool> IoTilesPlacer::RunOnComputation(HloComputation* comp,
const CallGraph& call_graph) {
HloInstructionSequence potential_io_tile_insts;
for (auto* inst : comp->MakeInstructionPostOrder()) {
if (ShouldBeOnIoTiles(inst, call_graph)) {
potential_io_tile_insts.push_back(inst);
}
}
const int64 max_live_bytes = GetMaxLiveBytes(potential_io_tile_insts);
const int64 target_io_bytes = GetMaxAvailableIoBytes(
num_io_tiles, bytes_per_io_tile, AvailableMemoryProportion());
const bool insts_fit_on_io_tiles = max_live_bytes < target_io_bytes;
const bool change =
insts_fit_on_io_tiles && !potential_io_tile_insts.instructions().empty();
if (change) {
for (auto* inst : potential_io_tile_insts.instructions()) {
TF_RETURN_IF_ERROR(AssignToIoTilesAndPropagateToGteUsers(inst));
}
} else if (!insts_fit_on_io_tiles) {
LOG(INFO) << absl::StrCat(
"Computation too large to fit on IO tiles, ", max_live_bytes,
" >= ", target_io_bytes,
". Currently the number of IO tiles is set to ", num_io_tiles,
" with the available memory"
" proportion set to ",
AvailableMemoryProportion(),
". To try and fit all the data into IO tiles you either need to"
" increase the number of IO tiles or the available memory proportion"
" using the `ipu.config.IPUConfig.io_tiles` category.");
}
return change;
}
static bool PoplarInstructionUsesIOTiles(const HloInstruction* inst) {
// The call to should be on io tiles ensures this GetTileset will succeed
return GetTileset(inst).ValueOrDie() == TILESET_IO_TILES;
}
static bool UsesIOTiles(const HloInstruction* inst,
const CallGraph& call_graph) {
return ShouldBeOnIoTiles(inst, call_graph) &&
PoplarInstructionUsesIOTiles(inst);
}
static bool UsesIOTiles(const HloComputation* computation,
const CallGraph& call_graph) {
return absl::c_any_of(computation->instructions(),
[&](const HloInstruction* inst) {
return UsesIOTiles(inst, call_graph);
});
}
static bool UsesIOTiles(const std::vector<HloComputation*>& computations,
const CallGraph& call_graph) {
return absl::c_any_of(computations, [&](const HloComputation* comp) {
return UsesIOTiles(comp, call_graph);
});
}
static bool UpdateNumIoTiles(int64& resources_num_io_tiles_,
const std::vector<HloComputation*>& computations,
const CallGraph& call_graph) {
const bool any_instruction_on_io_tiles =
UsesIOTiles(computations, call_graph);
if (any_instruction_on_io_tiles || resources_num_io_tiles_ == 0) {
return false; // Haven't changed resources so return false
}
// Remove io tiles from resources/graph as no ops placed on them
resources_num_io_tiles_ = 0;
return true;
}
StatusOr<bool> IoTilesPlacer::Run(HloModule* module) {
if (!enabled_) {
return false;
}
VLOG(2) << "Before IoTilesPlacer:";
XLA_VLOG_LINES(2, module->ToString());
bool changed = false;
const auto call_graph = CallGraph::Build(module);
auto computations = module->MakeComputationPostOrder();
for (auto* comp : computations) {
if (IsPopOpsFusion(comp)) {
continue;
}
TF_ASSIGN_OR_RETURN(const bool computation_changed,
RunOnComputation(comp, *call_graph));
changed |= computation_changed;
}
changed |=
UpdateNumIoTiles(resources_num_io_tiles_, computations, *call_graph);
if (changed) {
VLOG(2) << "After IoTilesPlacer:";
XLA_VLOG_LINES(2, module->ToString());
} else {
VLOG(2) << "No changes were made.";
}
return changed;
}
} // namespace poplarplugin
} // namespace xla
| 8,617 | 2,762 |
/* Files
PIRL CVS ID: $Id: Files.hh,v 1.11 2012/07/20 00:25:53 castalia Exp $
Copyright (C) 2006-2010 Arizona Board of Regents on behalf of the
Planetary Image Research Laboratory, Lunar and Planetary Laboratory at
the University of Arizona.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _Files_
#define _Files_
#include <string>
#include <sys/types.h> // For off_t.
namespace PIRL
{
/*==============================================================================
Constants
*/
//! Module identification name with source code version and date.
extern const char
*Files_ID;
//! Host filesystem pathname delimiter ('/').
extern const char
FILE_PATHNAME_DELIMITER;
//! Filename extension delimiter ('.').
extern const char
FILE_EXTENSION_DELIMITER;
/*==============================================================================
Functions
*/
/** Test if a file exists at a pathname.
@param pathname The filesystem pathname to test.
@return true if the file exists; false otherwise.
*/
bool file_exists (const std::string& pathname);
/** Test if a file at a pathname is readable.
Readability is determined by the system's access method. The file
must be readable by the real ID of the process.
@param pathname The pathname to test.
@return true if the file is accessable and can be read; false otherwise.
@throws runtime_error If the file attributes can not be obtained
(MS/Windows only).
*/
bool file_is_readable (const std::string& pathname);
/** Test if a file at a pathname is writeable.
Writeability is determined by the system's access method. The file
must be writeable by the real ID of the process.
@param pathname The pathname to test.
@return true if the file is accessable and can be written; false
otherwise.
@throws runtime_error If the file attributes can not be obtained
(MS/Windows only).
*/
bool file_is_writeable (const std::string& pathname);
/** Test if a file at a pathname is a normal file.
@param pathname The pathname to test.
@return true if the file is accessable and is a normal type of file;
false otherwise.
*/
bool file_is_normal (const std::string& pathname);
/** Test if a file at a pathname is a directory.
@param pathname The pathname to test.
@return true if the file is accessable and is a directory; false
otherwise.
*/
bool file_is_directory (const std::string& pathname);
/** Test if a file at a pathname is a link file.
@param pathname The pathname to test.
@return true if the file is accessable and is a link; false
otherwise.
*/
bool file_is_link (const std::string& pathname);
/** Get the size of a file.
<b>N.B.</b>: For MS/Windows a directory always has a file size of
zero.
@param pathname The pathname to the file.
@return The size of the file in bytes. This will be -1 if the file
could not be accessed. The return data type is off_t, the natural
type for a file offset value for the host system.
*/
off_t file_size (const std::string& pathname);
/** Test if a pathname is an absolute pathname.
An absolute pathname begins with the #FILE_PATHNAME_DELIMITER character.
@param pathname The pathname to test.
@return true if the pathname is an absolute pathname; false otherwise.
*/
bool file_is_absolute (const std::string& pathname);
/** Clean a pathname of redundant segments.
All sequences of multiple #FILE_PATHNAME_DELIMITER characters are
replaced with a single delimiter. All sequences of
#FILE_PATHNAME_DELIMITER-'.'-#FILE_PATHNAME_DELIMITER characters are
replaced with a single delimiter. Any trailing #FILE_PATHNAME_DELIMITER
is removed.
@param pathname The pathname from which to obtain the extension.
@return The cleaned pathname. <b>N.B.</b>: The pathname string is
modified in place.
*/
std::string& clean_pathname (std::string& pathname);
/** Get the full pathname for a filename.
If the filename is relative the {@link #CWD() current working directory}
of the process is prepended.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param filename The filename for which to obtain an absolute
pathname.
@return The absolute pathname for the filename.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_pathname (const std::string& filename);
/** Get the full pathname for a filename.
If the filename is relative the directory is prepended. If the
directory is relative the {@link #CWD() current working directory}
of the process is prepended to it.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param directory The directory to prepend to the filename if
it is not an absolute pathname.
@param filename The filename for which to obtain an absolute
pathname.
@return The absolute pathname for the filename.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_pathname
(const std::string& directory, const std::string& filename);
/** Get the current working directory of the process.
This is a convenience function for the system getcwd function.
@return The absolute pathname for the current working directory
of the process.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string CWD ();
/** Get the leading directory portion of a pathname.
The leading directory portion of a pathname is that substring
preceding the last #FILE_PATHNAME_DELIMITER, or the empty string if
it does not contain the delimiter. <b>N.B.</b>: If the pathname contains
only one delimiter that is the first character, then the leading
directory pathname is the delimiter (i.e. the filesystem root).
@param pathname The pathname from which to obtain the directory
pathname.
@return The directory pathname from the pathname.
*/
std::string file_directory (const std::string& pathname);
/** Get the leading directory pathname portion of a pathname.
The {@link #file_directory(const std::string&) leading directory}
portion of the pathname is obtained. If it is not an {@link
file_is_absolute(const std::string&) absolute pathname} the {@link
#CWD() current working directory} of the process is prepended.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param pathname The pathname from which to obtain the directory
pathname.
@return The directory pathname from the pathname.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_directory_pathname (const std::string& pathname);
/** Get the final name portion of a pathname.
The final name portion of a pathname is that substring following the
last #FILE_PATHNAME_DELIMITER, or the entire string if it does not
contain the delimiter.
@param pathname The pathname from which to obtain the file's name.
@return The name of the file referenced by the pathname.
*/
std::string file_name (const std::string& pathname);
/** Get the basename of a file's pathname.
The basename is that portion of the path preceeding the last
#FILE_EXTENSION_DELIMITER; or the entire string if there
it does not contain the delimiter. <b>N.B.</b>: Any directory
segments of the pathname are retained in the basename; these
can be removed using the file_name method.
@param pathname The pathname from which to obtain the basename.
@return The basename of the pathname.
*/
std::string file_basename (const std::string& pathname);
/** Get a file's extension.
The extension is that portion of the path following the last
#FILE_EXTENSION_DELIMITER. This will be the empty string if no
extension is present or the pathname ends with the delimiter.
@param pathname The pathname from which to obtain the extension.
@return The extension of the file referenced by the pathname.
*/
std::string file_extension (const std::string& pathname);
/** Get the user's home directory pathname.
@return The pathname of the effective user home directory.
@throws runtime_error If the user info can not be obtained.
*/
std::string home_directory_pathname ();
/** Get the effective username.
@return The name of the effective user.
@throws runtime_error If the user info can not be obtained (UNIX
only).
*/
std::string username ();
/** Get the effective user ID.
@return The effective user ID value.
*/
unsigned int UID ();
/** Get the effective group ID.
@return The effective group ID value.
*/
unsigned int GID ();
/** Get the name of the host system.
@return The name of the host system.
*/
std::string hostname ();
} // PIRL namespace
#endif
| 9,180 | 2,772 |
/**
* @file ImageIOTest.cpp
* @brief ImageIO class tester.
* @author zer0
* @date 2017-06-10
* @date 2019-02-20 (Rename: Image -> ImageIO)
*/
#include <gtest/gtest.h>
#include <tester/DemoAsset.hpp>
#include <libtbag/graphic/ImageIO.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/filesystem/File.hpp>
using namespace libtbag;
using namespace libtbag::graphic;
TEST(ImageIOTest, ReadImage)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readImage(path.getString(), image));
ASSERT_EQ(3, image.dim(2));
ASSERT_EQ(512, image.dim(1));
ASSERT_EQ(512, image.dim(0));
// First RGB pixel.
ASSERT_EQ(226, image.offset<uint8_t>(0)); // r
ASSERT_EQ(137, image.offset<uint8_t>(1)); // g
ASSERT_EQ(125, image.offset<uint8_t>(2)); // b
// Last RGB pixel.
ASSERT_EQ(185, image.offset<uint8_t>(image.size() - 3)); // r
ASSERT_EQ( 74, image.offset<uint8_t>(image.size() - 2)); // g
ASSERT_EQ( 81, image.offset<uint8_t>(image.size() - 1)); // b
libtbag::util::Buffer buffer;
ASSERT_EQ(E_SUCCESS, writeImage(buffer, image, ImageFileFormat::IFF_PNG));
ASSERT_FALSE(buffer.empty());
// Save & Load.
tttDir_Automatic();
auto const SAVE_PATH = tttDir_Get() / "save.png";
ASSERT_EQ(E_SUCCESS, writeImage(SAVE_PATH.getString(), image));
ASSERT_EQ(buffer.size(), SAVE_PATH.getState().size);
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(SAVE_PATH.getString(), reload));
ASSERT_EQ(3, image.dim(2));
ASSERT_EQ(512, reload.dim(1));
ASSERT_EQ(512, reload.dim(0));
// First RGB pixel.
ASSERT_EQ(226, reload.offset<uint8_t>(0)); // r
ASSERT_EQ(137, reload.offset<uint8_t>(1)); // g
ASSERT_EQ(125, reload.offset<uint8_t>(2)); // b
// Last RGB pixel.
ASSERT_EQ(185, reload.offset<uint8_t>(reload.size() - 3)); // r
ASSERT_EQ( 74, reload.offset<uint8_t>(reload.size() - 2)); // g
ASSERT_EQ( 81, reload.offset<uint8_t>(reload.size() - 1)); // b
}
TEST(ImageIOTest, ReadRgbaImage)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readRgbaImage(path.getString(), image));
ASSERT_EQ(4, image.dim(2));
ASSERT_EQ(512, image.dim(1));
ASSERT_EQ(512, image.dim(0));
// First RGB pixel.
ASSERT_EQ(226, image.offset<uint8_t>(0)); // r
ASSERT_EQ(137, image.offset<uint8_t>(1)); // g
ASSERT_EQ(125, image.offset<uint8_t>(2)); // b
ASSERT_EQ(255, image.offset<uint8_t>(3)); // a
// Last RGB pixel.
ASSERT_EQ(185, image.offset<uint8_t>(image.size() - 4)); // r
ASSERT_EQ( 74, image.offset<uint8_t>(image.size() - 3)); // g
ASSERT_EQ( 81, image.offset<uint8_t>(image.size() - 2)); // b
ASSERT_EQ(255, image.offset<uint8_t>(image.size() - 1)); // a
tttDir_Automatic();
auto const SAVE_PATH = tttDir_Get() / "save.png";
ASSERT_EQ(E_SUCCESS, writeImage(SAVE_PATH.getString(), image));
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(SAVE_PATH.getString(), reload));
ASSERT_EQ(4, reload.dim(2));
ASSERT_EQ(512, reload.dim(1));
ASSERT_EQ(512, reload.dim(0));
}
TEST(ImageIOTest, UseJpeg)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readImage(path.getString(), image));
// Save & Load.
tttDir_Automatic();
auto const JPEG_PATH = tttDir_Get() / "save.jpg";
ASSERT_EQ(E_SUCCESS, writeImage(JPEG_PATH.getString(), image));
ASSERT_TRUE(JPEG_PATH.isRegularFile());
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(JPEG_PATH.getString(), reload));
auto const channels = reload.dim(2);
auto const width = reload.dim(1);
auto const height = reload.dim(0);
ASSERT_EQ(3, channels);
ASSERT_EQ(512, width);
ASSERT_EQ(512, height);
// Write To memory:
libtbag::util::Buffer buffer;
ASSERT_NE(0, writeJpg(width, height, channels, reload.data<char>(), DEFAULT_JPG_QUALITY, buffer));
ASSERT_FALSE(buffer.empty());
auto const JPEG_PATH_02 = tttDir_Get() / "save_02.jpg";
ASSERT_EQ(E_SUCCESS, libtbag::filesystem::writeFile(JPEG_PATH_02, buffer));
}
| 4,184 | 1,791 |
/*
* ShipManager.cpp
*
* Created on: 18/10/2013
* Author: victor
*/
#include "ShipManager.h"
#include "templates/manager/DataArchiveStore.h"
#include "templates/datatables/DataTableIff.h"
ShipManager::ShipManager() {
IffStream* iffStream = DataArchiveStore::instance()->openIffFile(
"datatables/space/ship_components.iff");
if (iffStream == nullptr) {
fatal("datatables/space/ship_components.iff could not be found.");
return;
}
DataTableIff dtiff;
dtiff.readObject(iffStream);
for (int i = 0; i < dtiff.getTotalRows(); ++i) {
DataTableRow* row = dtiff.getRow(i);
Reference<ShipComponent*> component = new ShipComponent();
component->readObject(row);
//info("loaded ship component " + component->getName() + " crc:0x" + String::hexvalueOf(int(component->getName().hashCode())), true);
shipComponents.put(component->getName().hashCode(), component);
}
delete iffStream;
}
| 917 | 338 |
// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/core/file/File.h"
#if LLBC_TARGET_PLATFORM_WIN32
#include "llbc/core/thread/FastLock.h"
#endif // LLBC_TARGET_PLATFORM_WIN32
#include "llbc/core/os/OS_Console.h"
#if LLBC_TARGET_PLATFORM_WIN32
__LLBC_INTERNAL_NS_BEGIN
static LLBC_NS LLBC_FastLock __g_consoleLock[2];
__LLBC_INTERNAL_NS_END
#endif // LLBC_TARGET_PLATFORM_WIN32
__LLBC_NS_BEGIN
int LLBC_GetConsoleColor(FILE *file)
{
#if LLBC_TARGET_PLATFORM_NON_WIN32
LLBC_SetLastError(LLBC_ERROR_NOT_IMPL);
return LLBC_FAILED;
#else
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
else if (UNLIKELY(fileNo != 1 && fileNo != 2))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
HANDLE handle = (fileNo == 1 ?
::GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE));
CONSOLE_SCREEN_BUFFER_INFO info;
if (::GetConsoleScreenBufferInfo(handle, &info) == 0)
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return info.wAttributes;
#endif
}
int LLBC_SetConsoleColor(FILE *file, int color)
{
#if LLBC_TARGET_PLATFORM_NON_WIN32
LLBC_SetLastError(LLBC_ERROR_NOT_IMPL);
return LLBC_FAILED;
#else
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
else if (UNLIKELY(fileNo != 1 && fileNo != 2))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
HANDLE handle = (fileNo == 1 ?
::GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE));
if (::SetConsoleTextAttribute(handle, color) == 0)
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return LLBC_OK;
#endif
}
int __LLBC_FilePrint(bool newline, FILE *file, const char *fmt, ...)
{
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
char *buf; int len;
LLBC_FormatArg(fmt, buf, len);
#if LLBC_TARGET_PLATFORM_NON_WIN32
flockfile(file);
fprintf(file, (newline?"%s\n":"%s"), buf);
fflush(file);
funlockfile(file);
#else
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
fprintf(file, newline?"%s\n":"%s", buf);
fflush(file);
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
#endif
LLBC_Free(buf);
return LLBC_OK;
}
int LLBC_FlushFile(FILE *file)
{
if (UNLIKELY(!file))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
#if LLBC_TARGET_PLATFORM_NON_WIN32
flockfile(file);
if (UNLIKELY(::fflush(file) != 0))
{
funlockfile(file);
LLBC_SetLastError(LLBC_ERROR_CLIB);
return LLBC_FAILED;
}
funlockfile(file);
return LLBC_OK;
#else // Win32
const int fileNo = LLBC_File::GetFileNo(file);
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
if (UNLIKELY(::fflush(file) != 0))
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_CLIB);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return LLBC_OK;
#endif
}
__LLBC_NS_END
#include "llbc/common/AfterIncl.h"
| 5,176 | 2,109 |
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "pin.h"
#include "level_zero/core/source/module/module.h"
#include "level_zero/source/inc/ze_intel_gpu.h"
namespace L0 {
static PinContext *PinContextInstance = nullptr;
void PinContext::init(ze_init_flag_t flag) {
if (!getenv_tobool("ZE_ENABLE_PROGRAM_INSTRUMENTATION")) {
return;
}
if (PinContextInstance == nullptr) {
PinContextInstance = new PinContext();
}
}
} // namespace L0
| 519 | 198 |
#include <fstream>
#include <iostream>
using namespace std;
const int maxn = 5005;
const int maxlg = 21;
int rmq[maxlg][maxn], a[maxn], n, lg[maxn];
inline int query(int st, int dr) {
int l = lg[dr - st + 1];
int ans = rmq[l][st];
if(a[ans] > a[rmq[l][dr - (1 << l) + 1]])
ans = rmq[l][dr - (1 << l) + 1];
return ans;
}
inline long long dei(int st, int dr, int h) {
if(st > dr)
return 0;
int minpos = query(st, dr);
return min((long long)(dr - st + 1), dei(st, minpos - 1, a[minpos]) + dei(minpos + 1, dr,a[minpos]) + a[minpos] - h);
}
int main() {
cin.sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("448c.in", "r", stdin);
freopen("448c.out", "w", stdout);
#endif
cin >> n;
for(int i = 1 ; i <= n ; ++ i) {
cin >> a[i];
rmq[0][i] = i;
}
for(int i = 2 ; i <= n ; ++ i)
lg[i] = lg[i >> 1] + 1;
for(int i = 1 ; (1 << i) <= n ; ++ i)
for(int j = 1 ; j + (1 << i) - 1 <= n ; ++ j) {
rmq[i][j] = rmq[i - 1][j];
if(a[rmq[i][j]] > a[rmq[i - 1][j + (1 << (i - 1))]])
rmq[i][j] = rmq[i - 1][j + (1 << (i - 1))];
}
cout << dei(1, n, 0) << '\n';
}
| 1,091 | 584 |
//
// Created by Administrator on 2021/1/5.
//
#include "Stack.h"
/*创建栈*/
Stack *createStack(){
Stack *p = (Stack*)malloc(sizeof(Stack));
p->top = NULL;
return p;
};
/*压栈*/
bool stackNodeIsInStack(Stack* head,stackNode* node){
stackNode* p = head->top;
while(p!=NULL){
if (p->data->ID == node->data->ID){
return true;
}
p = p->next;
}
return false;
}
Stack* pushStack(Stack* head,stackNode* node){
stackNode *p = node;
if(head->top == NULL){
head->top = p;
head->top->next = NULL;
}else{
p->next = head->top;
head->top = p;
}
return head;
}
/*弹栈*/
stackNode *popStack(Stack*head){
if (head == NULL)return NULL;
stackNode *p = head->top;
head->top = head->top->next;
p->next = NULL;
return p;
}
/*获取栈顶元素,不弹栈*/
stackNode *getTopStack(const Stack*head){
return head->top;
}
/*初始化栈元素(封装结点)*/
stackNode *initStackNode(Node*p){
stackNode *q =(stackNode*) malloc(sizeof(stackNode));
q->data = p;
q->next= nullptr;
return q;
}
/*栈判空*/
bool StackIsEmpty(Stack*head){
return head->top==NULL?true:false;
}
/*判断结点是否在栈里*/
bool NodeInStack(Stack* head,Node* p){
stackNode * t = head->top;
while (t!=NULL){
if(t->data->ID == p->ID || strcmp(t->data->name,p->name) == 0){
return true;
}
t = t->next;
}
return false;
}
/*判断栈是否满*/
bool StackIsFull(Stack* head,int MAXSIZE){
stackNode*p = getTopStack(head);
int num = 0;
while(p!=NULL){
num++;
p = p->next;
}
return num>=MAXSIZE;
}
/*反转栈*/
Stack* reverseStack(Stack* p){
Stack *temp = createStack();
while(!StackIsEmpty(p)){
pushStack(temp,popStack(p));
}
free(p);
return temp;
}
int getStackSize(Stack *t){
int num = 0;
stackNode *temp = getTopStack(t);
while (temp!=NULL){
++num;
temp = temp->next;
}
return num;
}
/*打印整个栈(不作任何操作)*/
void printStack(Stack*head){
stackNode * t = head->top;
Stack *temp = createStack();
while (t!=NULL){
pushStack(temp,initStackNode(t->data));
t = t->next;
}
while(!StackIsEmpty(temp)){
stackNode* p = popStack(temp);
printf("%s->",p->data->name);
free(p);
}
printf("\n");
}
| 2,319 | 914 |
#include "test.hpp"
namespace
{
char const* VERT_SHADER_SOURCE("gl-320/fbo-blit.vert");
char const* FRAG_SHADER_SOURCE("gl-320/fbo-blit.frag");
char const* TEXTURE_DIFFUSE("kueken7_rgba8_srgb.dds");
glm::ivec2 const FRAMEBUFFER_SIZE(512, 512);
struct vertex
{
vertex
(
glm::vec2 const & Position,
glm::vec2 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec2 Position;
glm::vec2 Texcoord;
};
// With DDS textures, v texture coordinate are reversed, from top to bottom
GLsizei const VertexCount(6);
GLsizeiptr const VertexSize = VertexCount * sizeof(vertex);
vertex const VertexData[VertexCount] =
{
vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f)),
vertex(glm::vec2( 1.5f,-1.5f), glm::vec2(1.0f, 0.0f)),
vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)),
vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)),
vertex(glm::vec2(-1.5f, 1.5f), glm::vec2(0.0f, 1.0f)),
vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f))
};
namespace framebuffer
{
enum type
{
RENDER,
RESOLVE,
MAX
};
}//namespace framebuffer
namespace texture
{
enum type
{
DIFFUSE,
COLORBUFFER,
MAX
};
}//namespace texture
}//namespace
class sample : public framework
{
public:
sample(int argc, char* argv[]) :
framework(argc, argv, "gl-320-fbo-blit", framework::CORE, 3, 2),
VertexArrayName(0),
BufferName(0),
ColorRenderbufferName(0),
ProgramName(0),
UniformMVP(-1),
UniformDiffuse(-1)
{}
private:
std::array<GLuint, texture::MAX> TextureName;
std::array<GLuint, framebuffer::MAX> FramebufferName;
GLuint VertexArrayName;
GLuint BufferName;
GLuint ColorRenderbufferName;
GLuint ProgramName;
GLint UniformMVP;
GLint UniformDiffuse;
bool initProgram()
{
bool Validated = true;
compiler Compiler;
// Create program
if(Validated)
{
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core");
ProgramName = glCreateProgram();
glAttachShader(ProgramName, VertShaderName);
glAttachShader(ProgramName, FragShaderName);
glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position");
glBindAttribLocation(ProgramName, semantic::attr::TEXCOORD, "Texcoord");
glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color");
glLinkProgram(ProgramName);
Validated = Validated && Compiler.check();
Validated = Validated && Compiler.check_program(ProgramName);
}
if(Validated)
{
UniformMVP = glGetUniformLocation(ProgramName, "MVP");
UniformDiffuse = glGetUniformLocation(ProgramName, "Diffuse");
}
return this->checkError("initProgram");
}
bool initBuffer()
{
glGenBuffers(1, &BufferName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return this->checkError("initBuffer");;
}
bool initTexture()
{
gli::texture2d Texture(gli::load_dds((getDataDirectory() + TEXTURE_DIFFUSE).c_str()));
gli::gl GL(gli::gl::PROFILE_GL32);
glGenTextures(texture::MAX, &TextureName[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(Texture.levels() - 1));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gli::gl::format const Format = GL.translate(Texture.format(), Texture.swizzles());
for(std::size_t Level = 0; Level < Texture.levels(); ++Level)
{
glTexImage2D(GL_TEXTURE_2D, GLint(Level),
Format.Internal,
GLsizei(Texture[Level].extent().x), GLsizei(Texture[Level].extent().y),
0,
Format.External, Format.Type,
Texture[Level].data());
}
glGenerateMipmap(GL_TEXTURE_2D); // Allocate all mipmaps memory
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return true;
}
bool initFramebuffer()
{
glGenFramebuffers(framebuffer::MAX, &FramebufferName[0]);
glGenRenderbuffers(1, &ColorRenderbufferName);
glBindRenderbuffer(GL_RENDERBUFFER, ColorRenderbufferName);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, ColorRenderbufferName);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return this->checkError("initFramebuffer");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureName[texture::COLORBUFFER], 0);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return this->checkError("initFramebuffer");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return this->checkError("initFramebuffer");
}
bool initVertexArray()
{
glGenVertexArrays(1, &VertexArrayName);
glBindVertexArray(VertexArrayName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(glm::vec2)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(semantic::attr::POSITION);
glEnableVertexAttribArray(semantic::attr::TEXCOORD);
glBindVertexArray(0);
return this->checkError("initVertexArray");
}
void renderFBO()
{
glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, float(FRAMEBUFFER_SIZE.y) / FRAMEBUFFER_SIZE.x, 0.1f, 100.0f);
glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f,-1.0f, 1.0f));
glm::mat4 MVP = Perspective * this->view() * Model;
glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1);
}
void renderFB()
{
glm::vec2 WindowSize(this->getWindowSize());
glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, WindowSize.x / WindowSize.y, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 MVP = Perspective * this->view() * Model;
glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1);
}
bool begin()
{
bool Validated = true;
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initTexture();
if(Validated)
Validated = initFramebuffer();
if(Validated)
Validated = initVertexArray();
return Validated && this->checkError("begin");
}
bool end()
{
glDeleteProgram(ProgramName);
glDeleteBuffers(1, &BufferName);
glDeleteTextures(texture::MAX, &TextureName[0]);
glDeleteRenderbuffers(1, &ColorRenderbufferName);
glDeleteFramebuffers(framebuffer::MAX, &FramebufferName[0]);
glDeleteVertexArrays(1, &VertexArrayName);
return true;
}
bool render()
{
glm::vec2 WindowSize(this->getWindowSize());
glUseProgram(ProgramName);
glUniform1i(UniformDiffuse, 0);
// Pass 1
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glViewport(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.0f, 0.5f, 1.0f, 1.0f)[0]);
renderFBO();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Generate FBO mipmaps
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
// Blit framebuffers
GLint const Border = 2;
int const Tile = 4;
glBindFramebuffer(GL_READ_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);
for(int j = 0; j < Tile; ++j)
for(int i = 0; i < Tile; ++i)
{
if((i + j) % 2)
continue;
glBlitFramebuffer(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y,
FRAMEBUFFER_SIZE.x / Tile * (i + 0) + Border,
FRAMEBUFFER_SIZE.x / Tile * (j + 0) + Border,
FRAMEBUFFER_SIZE.y / Tile * (i + 1) - Border,
FRAMEBUFFER_SIZE.y / Tile * (j + 1) - Border,
GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
// Pass 2
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, static_cast<GLsizei>(WindowSize.x), static_cast<GLsizei>(WindowSize.y));
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)[0]);
renderFB();
return true;
}
};
int main(int argc, char* argv[])
{
int Error = 0;
sample Sample(argc, argv);
Error += Sample();
return Error;
}
| 9,656 | 4,309 |
// Copyright 2020 Glyn Matthews.
// 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 SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
#define SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
namespace skyr::inline v2::unicode {
class sentinel {};
} // namespace skyr::inline v2::unicode
#endif // SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
| 424 | 191 |
// This program demonstrates the GradedActivity class.
#include <iostream>
#include "GradedActivity.h"
using namespace std;
int main()
{
double testScore; // To hold a test score
// Create a GradedActivity object for the test.
GradedActivity test;
// Get a numeric test score from the user.
cout << "Enter your numeric test score: ";
cin >> testScore;
// Store the numeric score in the test object.
test.setScore(testScore);
// Display the letter grade for the test.
cout << "The grade for that test is "
<< test.getLetterGrade() << endl;
return 0;
} | 614 | 182 |
// 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 "chrome/test/chromedriver/devtools_events_logger.h"
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "chrome/test/chromedriver/chrome/devtools_client.h"
#include "chrome/test/chromedriver/chrome/devtools_client_impl.h"
DevToolsEventsLogger::DevToolsEventsLogger(Log* log,
const base::ListValue* prefs)
: log_(log),
prefs_(prefs) {}
inline DevToolsEventsLogger::~DevToolsEventsLogger() {}
Status DevToolsEventsLogger::OnConnected(DevToolsClient* client) {
for (base::ListValue::const_iterator it = prefs_->begin();
it != prefs_->end();
++it) {
std::string event;
it->GetAsString(&event);
events_.insert(event);
}
return Status(kOk);
}
Status DevToolsEventsLogger::OnEvent(DevToolsClient* client,
const std::string& method,
const base::DictionaryValue& params) {
std::unordered_set<std::string>::iterator it = events_.find(method);
if (it != events_.end()) {
base::DictionaryValue log_message_dict;
log_message_dict.SetString("method", method);
log_message_dict.Set("params", base::MakeUnique<base::Value>(params));
std::string log_message_json;
base::JSONWriter::Write(log_message_dict, &log_message_json);
log_->AddEntry(Log::kInfo, log_message_json);
}
return Status(kOk);
}
| 1,602 | 501 |
//===-- ProcfsTests.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Procfs.h"
#include "lldb/Host/linux/Support.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace lldb_private;
using namespace process_linux;
using namespace llvm;
TEST(Perf, HardcodedLogicalCoreIDs) {
Expected<std::vector<lldb::core_id_t>> core_ids =
GetAvailableLogicalCoreIDs(R"(processor : 13
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2886.370
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 19
cpu cores : 20
apicid : 103
initial apicid : 103
fpu : yes
fpu_exception : yes
cpuid level : 22
power management:
processor : 24
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2768.494
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 20
cpu cores : 20
apicid : 105
power management:
processor : 35
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2884.703
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 24
cpu cores : 20
apicid : 113
processor : 79
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 3073.955
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 28
cpu cores : 20
apicid : 121
power management:
)");
ASSERT_TRUE((bool)core_ids);
ASSERT_THAT(*core_ids, ::testing::ElementsAre(13, 24, 35, 79));
}
TEST(Perf, RealLogicalCoreIDs) {
// We first check we can read /proc/cpuinfo
auto buffer_or_error = errorOrToExpected(getProcFile("cpuinfo"));
if (!buffer_or_error)
GTEST_SKIP() << toString(buffer_or_error.takeError());
// At this point we shouldn't fail parsing the core ids
Expected<ArrayRef<lldb::core_id_t>> core_ids = GetAvailableLogicalCoreIDs();
ASSERT_TRUE((bool)core_ids);
ASSERT_GT((int)core_ids->size(), 0) << "We must see at least one core";
}
| 2,851 | 1,122 |
#include "Voxelator_App.hpp"
int main(int argc, char** argv){
Voxelator_App app = Voxelator_App(argv[0], APP_OpenGL_4);
app.run();
return 0;
} | 160 | 72 |
#include "StdAfx.h"
#include "TCPEndpoint.h"
TCPEndpoint::TCPEndpoint(const DWORD dwPoolHeaderSize)
{
// initialize object name and tag
m_szObjName = "TCP_ENDPOINT";
m_dwTag = 0x45706354;
m_dwPoolHeaderSize = dwPoolHeaderSize;
// initialize default offset
SetDefaultOffsetsAndSizes();
}
TCPEndpoint::~TCPEndpoint(void)
{
}
void TCPEndpoint::SetDefaultOffsetsAndSizes( void )
{
// first obtain OS version
OSVERSIONINFO verInfo;
ZeroMemory(&verInfo, sizeof(OSVERSIONINFO));
verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&verInfo);
// THE CODE THAT FOLLOWS DOES NOT COVER ALL CASES
// FIX ME!!!
if(verInfo.dwMajorVersion == 5)
{
// using Windows XP x86
m_isPID = true;
m_dwConnectionOwnerOffset = 0x18;
}
else if(verInfo.dwMajorVersion == 6)
{
m_isPID = false;
// Vista/2008 have different offsets than Windows 7
if(verInfo.dwMinorVersion == 0)
{
#ifdef _WIN64
m_dwConnectionOwnerOffset = 0x210;
#else // _WIN32
m_dwConnectionOwnerOffset = 0x160;
#endif // _WIN64
}
else
{
// using Windows 7 x86 defaults
#ifdef _WIN64
m_dwConnectionOwnerOffset = 0x238;
#else // _WIN32
m_dwConnectionOwnerOffset = 0x174;
#endif // _WIN64
}
}
} | 1,270 | 558 |
#pragma once
#include "ProviderProxy.hpp"
namespace axis { namespace services { namespace management {
class UserModuleProxy : public ProviderProxy
{
public:
UserModuleProxy(Provider& provider, bool isNonVolatile);
virtual ~UserModuleProxy(void);
virtual bool IsBootstrapModule(void) const;
virtual bool IsNonVolatileUserModule(void) const;
virtual bool IsUserModule(void) const;
virtual Provider& GetProvider(void) const;
virtual bool IsCustomSystemModule( void ) const;
virtual bool IsSystemModule( void ) const;
private:
bool _isNonVolatile;
bool _isWeakModule;
Provider& _provider;
};
} } } // namespace axis::services::management
| 651 | 189 |
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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 AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "widget/Registry.hxx"
#include "widget/Widget.hxx"
#include "widget/Class.hxx"
#include "http/Address.hxx"
#include "translation/Service.hxx"
#include "translation/Handler.hxx"
#include "translation/Request.hxx"
#include "translation/Response.hxx"
#include "translation/Transformation.hxx"
#include "AllocatorPtr.hxx"
#include "pool/pool.hxx"
#include "pool/Ptr.hxx"
#include "PInstance.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"
#include <gtest/gtest.h>
#include <string.h>
class MyTranslationService final : public TranslationService, Cancellable {
public:
bool aborted = false;
/* virtual methods from class TranslationService */
void SendRequest(AllocatorPtr alloc,
const TranslateRequest &request,
const StopwatchPtr &parent_stopwatch,
TranslateHandler &handler,
CancellablePointer &cancel_ptr) noexcept override;
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
aborted = true;
}
};
struct Context : PInstance {
bool got_class = false;
const WidgetClass *cls = nullptr;
void RegistryCallback(const WidgetClass *_cls) noexcept {
got_class = true;
cls = _cls;
}
};
/*
* tstock.c emulation
*
*/
void
MyTranslationService::SendRequest(AllocatorPtr alloc,
const TranslateRequest &request,
const StopwatchPtr &,
TranslateHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
assert(request.remote_host == NULL);
assert(request.host == NULL);
assert(request.uri == NULL);
assert(request.widget_type != NULL);
assert(request.session.IsNull());
assert(request.param == NULL);
if (strcmp(request.widget_type, "sync") == 0) {
auto response = alloc.New<TranslateResponse>();
response->address = *http_address_parse(alloc, "http://foo/");
response->views = alloc.New<WidgetView>(nullptr);
response->views->address = {ShallowCopy(), response->address};
handler.OnTranslateResponse(*response);
} else if (strcmp(request.widget_type, "block") == 0) {
cancel_ptr = *this;
} else
assert(0);
}
/*
* tests
*
*/
TEST(WidgetRegistry, Normal)
{
MyTranslationService ts;
Context data;
WidgetRegistry registry(data.root_pool, ts);
CancellablePointer cancel_ptr;
auto pool = pool_new_linear(data.root_pool, "test", 8192);
registry.LookupWidgetClass(pool, pool, "sync",
BIND_METHOD(data, &Context::RegistryCallback),
cancel_ptr);
ASSERT_FALSE(ts.aborted);
ASSERT_TRUE(data.got_class);
ASSERT_NE(data.cls, nullptr);
ASSERT_EQ(data.cls->views.address.type, ResourceAddress::Type::HTTP);
ASSERT_STREQ(data.cls->views.address.GetHttp().host_and_port, "foo");
ASSERT_STREQ(data.cls->views.address.GetHttp().path, "/");
ASSERT_EQ(data.cls->views.next, nullptr);
ASSERT_TRUE(data.cls->views.transformations.empty());
pool.reset();
pool_commit();
}
/** caller aborts */
TEST(WidgetRegistry, Abort)
{
MyTranslationService ts;
Context data;
WidgetRegistry registry(data.root_pool, ts);
CancellablePointer cancel_ptr;
auto pool = pool_new_linear(data.root_pool, "test", 8192);
registry.LookupWidgetClass(pool, pool, "block",
BIND_METHOD(data, &Context::RegistryCallback),
cancel_ptr);
ASSERT_FALSE(data.got_class);
ASSERT_FALSE(ts.aborted);
cancel_ptr.Cancel();
ASSERT_TRUE(ts.aborted);
ASSERT_FALSE(data.got_class);
pool.reset();
pool_commit();
}
| 4,761 | 1,726 |
/*
// Copyright (c) 2016 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include "upsampling_inst.h"
#include "primitive_gpu_base.h"
#include "implementation_map.h"
#include "error_handler.h"
#include "kernel_selector_helper.h"
#include "upsampling/upsampling_kernel_selector.h"
#include "upsampling/upsampling_kernel_base.h"
namespace cldnn {
namespace gpu {
namespace {
inline kernel_selector::sample_type convert_to_sample_type(upsampling_sample_type type) {
switch (type) {
case upsampling_sample_type::nearest:
return kernel_selector::sample_type::NEAREST;
case upsampling_sample_type::bilinear:
return kernel_selector::sample_type::BILINEAR;
default:
return kernel_selector::sample_type::NEAREST;
}
}
} // namespace
struct upsampling_gpu : typed_primitive_gpu_impl<upsampling> {
using parent = typed_primitive_gpu_impl<upsampling>;
using parent::parent;
static primitive_impl* create(const upsampling_node& arg) {
auto us_params = get_default_params<kernel_selector::upsampling_params>(arg);
auto us_optional_params =
get_default_optional_params<kernel_selector::upsampling_optional_params>(arg.get_program());
const auto& primitive = arg.get_primitive();
if (primitive->with_activation)
convert_activation_func_params(primitive, us_params.activation);
us_params.num_filter = primitive->num_filter;
us_params.sampleType = convert_to_sample_type(primitive->sample_type);
auto& kernel_selector = kernel_selector::upsampling_kernel_selector::Instance();
auto best_kernels = kernel_selector.GetBestKernels(us_params, us_optional_params);
CLDNN_ERROR_BOOL(arg.id(),
"Best_kernel.empty()",
best_kernels.empty(),
"Cannot find a proper kernel with this arguments");
auto upsampling = new upsampling_gpu(arg, best_kernels[0]);
return upsampling;
}
};
namespace {
struct attach {
attach() {
implementation_map<upsampling>::add(
{{std::make_tuple(engine_types::ocl, data_types::f32, format::yxfb), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::yxfb), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f32, format::bfyx), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::bfyx), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f32, format::byxf), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::byxf), upsampling_gpu::create}});
}
~attach() {}
};
attach attach_impl;
} // namespace
} // namespace gpu
} // namespace cldnn
| 3,395 | 1,065 |
#include <boost/hana/ext/boost/fusion/deque.hpp>
| 49 | 22 |
/*
* StochasticBlockmodel.hpp
*
* Created on: 13.08.2014
* Author: Christian Staudt
*/
#ifndef NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
#define NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
#include <networkit/generators/StaticGraphGenerator.hpp>
namespace NetworKit {
/**
* @ingroup generators
*/
class StochasticBlockmodel final : public StaticGraphGenerator {
public:
/**
* Construct a undirected regular ring lattice.
*
* @param nNodes number of nodes in target graph
* @param n number of blocks (=k)
* @param membership maps node ids to block ids (consecutive, 0 <= i < nBlocks)
* @param affinity matrix of size k x k with edge probabilities between the blocks
*/
StochasticBlockmodel(count n, count nBlocks, const std::vector<index> &membership,
const std::vector<std::vector<double>> &affinity);
Graph generate() override;
private:
count n;
std::vector<index> membership;
const std::vector<std::vector<double>> &affinity;
};
} /* namespace NetworKit */
#endif // NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
| 1,145 | 385 |
#include "include/Country.hpp"
Country::Country(const Country &country) {
if (this == &country) return;
name.clear();
name.assign(country.getName());
}
Country &Country::operator=(const Country &country) {
if (this == &country) return *this;
name.clear();
name.assign(country.getName());
return *this;
}
bool operator==(const Country &c1, const Country &c2) {
return (c1.getName() == c2.getName());
}
bool operator!=(const Country &c1, const Country &c2) {
return !(c1 == c2);
}
bool operator<(const Country &c1, const Country &c2) {
return c1.getName() < c2.getName();
}
bool operator>(const Country &c1, const Country &c2) {
return c1.getName() > c2.getName();
}
bool operator<=(const Country &c1, const Country &c2) {
return c1.getName() <= c2.getName();
}
bool operator>=(const Country &c1, const Country &c2) {
return c1.getName() >= c2.getName();
}
std::ostream &operator<<(std::ostream &os, const Country &country) {
os << country.getName();
return os;
} | 1,030 | 345 |
#include "HttpdConf.hpp"
#include <iostream>
#include <sstream>
#include <algorithm>
HttpdConf::HttpdConf(std::string fileName) : ConfigurationReader(fileName) {
createDispatch();
}
void HttpdConf::load() {
while(hasMoreLines()) {
std::istringstream iss(nextLine());
std::vector<std::string> tokens((std::istream_iterator<std::string>(iss)),
std::istream_iterator<std::string>());
dispatcher[tokens[0]](tokens);
}
closeFile();
}
std::string HttpdConf::removeQuotes(std::string &str) {
str.erase(remove( str.begin(), str.end(), '\"' ),str.end());
return str;
}
void HttpdConf::createDispatch() {
dispatcher = {
{"ServerRoot", [&](std::vector<std::string> tokens) {
serverRoot = removeQuotes(tokens[1]);
}},
{"DocumentRoot", [&](std::vector<std::string> tokens) {
documentRoot = removeQuotes(tokens[1]);
}},
{"Listen", [&](std::vector<std::string> tokens) {
port = std::stoi(tokens[1]);
}},
{"LogFile", [&](std::vector<std::string> tokens) {
logFile = removeQuotes(tokens[1]);
}},
{"ScriptAlias", [&](std::vector<std::string> tokens) {
scriptAliases [tokens[1]] = removeQuotes(tokens[2]);
}},
{"Alias", [&](std::vector<std::string> tokens) {
aliases [tokens[1]] = removeQuotes(tokens[2]);
}},
{"AccessFile", [&](std::vector<std::string> tokens) {
accessFile = removeQuotes(tokens[1]);
}},
{"DirectoryIndex", [&](std::vector<std::string> tokens) {
directoryIndex = removeQuotes(tokens[1]);
}}
};
}
const std::unordered_map<std::string, std::string>& HttpdConf::getAliases() {
return aliases;
}
const std::unordered_map<std::string, std::string>& HttpdConf::getScriptAliases() {
return scriptAliases;
}
const std::string HttpdConf::getDocumentRoot() {
return documentRoot;
}
const std::string HttpdConf::getLog() {
return logFile;
}
const uint HttpdConf::getPort() {
return port;
}
| 2,130 | 689 |
// @@@LICENSE
//
// Copyright (c) 2009-2013 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LICENSE@@@
#include "commands/ScheduleRetryCommand.h"
#include "activity/ActivityBuilder.h"
#include "commands/DeleteActivitiesCommand.h"
#include "data/EmailAccountAdapter.h"
#include "PopClient.h"
#include "PopDefs.h"
int ScheduleRetryCommand::INITIAL_RETRY_SECONDS = 60;
int ScheduleRetryCommand::MAX_RETRY_SECONDS = 30 * 60;
float ScheduleRetryCommand::RETRY_MULTIPLIER = 1.5;
ScheduleRetryCommand::ScheduleRetryCommand(PopClient& client, const MojObject& folderId, EmailAccount::AccountError err)
: PopClientCommand(client, "Schedule Retry"),
m_folderId(folderId),
m_accntErr(err),
m_scheduleRetrySlot(this, &ScheduleRetryCommand::ScheduleRetryResponse),
m_deleteActivitiesSlot(this, &ScheduleRetryCommand::CancelActivitiesDone),
m_updateAccountSlot(this, &ScheduleRetryCommand::UpdateAccountResponse)
{
}
ScheduleRetryCommand::~ScheduleRetryCommand()
{
}
void ScheduleRetryCommand::RunImpl()
{
try {
if (!m_client.GetAccount().get()) {
MojString err;
err.format("Account is not loaded for '%s'", AsJsonString(
m_client.GetAccountId()).c_str());
throw MailException(err.data(), __FILE__, __LINE__);
}
ScheduleRetry();
} catch (const std::exception& ex) {
Failure(ex);
} catch (...) {
Failure(MailException("Unknown exception in scheduling POP account retry", __FILE__, __LINE__));
}
}
void ScheduleRetryCommand::ScheduleRetry()
{
ActivityBuilder ab;
// Get current retry interval from account
EmailAccount::RetryStatus retryStatus = m_client.GetAccount()->GetRetry();
int interval = retryStatus.GetInterval();
if(interval <= INITIAL_RETRY_SECONDS) {
interval = INITIAL_RETRY_SECONDS;
} else if(interval >= MAX_RETRY_SECONDS) {
interval = MAX_RETRY_SECONDS;
} else {
// TODO: only update this on actual retry?
interval *= RETRY_MULTIPLIER;
}
// Update account just in case it wasn't within the limit
retryStatus.SetInterval(interval);
m_client.GetAccount()->SetRetry(retryStatus);
m_client.GetActivityBuilderFactory()->BuildFolderRetrySync(ab, m_folderId, interval);
MojErr err;
MojObject payload;
err = payload.put("activity", ab.GetActivityObject());
ErrorToException(err);
err = payload.put("start", true);
ErrorToException(err);
err = payload.put("replace", true);
MojLogInfo(m_log, "Creating retry activity in activity manager: %s", AsJsonString(payload).c_str());
m_client.SendRequest(m_scheduleRetrySlot, "com.palm.activitymanager", "create", payload);
}
MojErr ScheduleRetryCommand::ScheduleRetryResponse(MojObject& response, MojErr err)
{
try {
MojLogInfo(m_log, "Retry activity creation: %s", AsJsonString(response).c_str());
ErrorToException(err);
CancelActivities();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in schedule retry response: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in schedule retry response");
Failure(MailException("Unknown exception in schedule retry response", __FILE__, __LINE__));
}
return MojErrNone;
}
void ScheduleRetryCommand::CancelActivities()
{
// Delete anything that includes the folderId in the name
MojString folderIdSubstring;
MojErr err = folderIdSubstring.format("folderId=%s", AsJsonString(m_folderId).c_str());
ErrorToException(err);
MojString retryActivityName;
m_client.GetActivityBuilderFactory()->GetFolderRetrySyncActivityName(retryActivityName, m_folderId);
m_deleteActivitiesCommand.reset(new DeleteActivitiesCommand(m_client));
m_deleteActivitiesCommand->SetIncludeNameFilter(folderIdSubstring);
m_deleteActivitiesCommand->SetExcludeNameFilter(retryActivityName);
m_deleteActivitiesCommand->Run(m_deleteActivitiesSlot);
}
MojErr ScheduleRetryCommand::CancelActivitiesDone()
{
try {
m_deleteActivitiesCommand->GetResult()->CheckException();
UpdateAccount();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in cancel activities done: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in cancel activities done");
Failure(MailException("Unknown exception in cancel activities done", __FILE__, __LINE__));
}
return MojErrNone;
}
void ScheduleRetryCommand::UpdateAccount()
{
MojObject accountObj;
EmailAccountAdapter::SerializeAccountRetryStatus(*m_client.GetAccount().get(), accountObj);
m_client.GetDatabaseInterface().UpdateAccountRetry(m_updateAccountSlot, m_client.GetAccountId(), accountObj);
}
MojErr ScheduleRetryCommand::UpdateAccountResponse(MojObject& response, MojErr err)
{
try {
ErrorToException(err);
Complete();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in update account response: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in update account response");
Failure(MailException("Unknown exception in update account response", __FILE__, __LINE__));
}
return MojErrNone;
}
| 5,516 | 1,860 |
#include "PID.h"
#include "iostream"
using namespace std;
/*
* TODO: Complete the PID class.
*/
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp, double Ki, double Kd) {
this->Kp=Kp;
this->Ki=Ki;
this->Kd=Kd;
p_error=-0.7598;
i_error=0;
d_error=0;
}
void PID::UpdateError(double cte) {
d_error=-cte-p_error;
i_error+=-cte;
p_error=-cte;
}
double PID::TotalError() {
double e=eval();
cout<<"e="<<e<<endl;
if(e> 1) e= 1;
if(e<-1) e=-1;
return e;
}
double PID::eval(){
return Kp*p_error+Ki*i_error+Kd*d_error;
}
| 539 | 268 |
//
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_ParamDecl__
#define __h3o_ParamDecl__
#include "Decl.hpp"
#include "TypeSpec.hpp"
#include "Expr.hpp"
#include "ParamSymbol.hpp"
namespace hydro
{
class ParamDecl : public Decl
{
private:
TypeSpec *_type;
Expr *_defaultValue;
public:
ParamDecl(Token *token, Modifier *mod, Name *name, TypeSpec *type, ParamSymbol *symbol, Expr *defaultValue = nullptr);
virtual ~ParamDecl();
TypeSpec *type() const { return _type; }
Expr *defaultValue() const { return _defaultValue; }
};
} // namespace hydro
#endif /* __h3o_ParamDecl__ */
| 935 | 324 |
#include <bits/stdc++.h>
using namespace std;
int main(){
string str,str1,str2,s; // zero based indexing
string sr (6,'0'); // create a string of "aaaaaa"
cout<<sr<<endl;
getline(cin,s); //input a string with spaces
cout<<s<<endl;
//append or add or concatenate 2 strings
str1 = "worry";
str2 = "about me";
str1.append(str2); // OR str1 = str1 + str2
cout<<str1+str2<<endl;//srt1 already contains worryabout me
//length() or size() is same
for(int i = 0; i<str1.length(); i++){
cout<<str1[i]<<" "; // we can treat string like arrays
}
cout<<endl;
str1.clear(); // empty string
str1 = "lost frequencies";
// cout<<str1<<" "<<str2<<endl;
//compare function -> return 0 if true or string equal
cout<<str1.compare(str2)<<endl;//return +ve number means that str1 is lexicographical greater than str2
cout<<str2.compare(str1)<<endl;// return -ve number means str2 is smaller
str2 = str1;
// self explanatory
if(!str1.compare(str2)){
cout<<"String equals";
}
else{
cout<<"strings not equal";
}
cout<<endl;
if(str.empty()){
cout<<"string is empty"<<endl;
}
str = "greatness";
str.erase(5,4);// it deletes the character starting from index 5 that is n to 5+4=9 ie s
cout<<str<<endl;//output "great" only
cout<<str.find("eat")<<endl;//found "eat" in "great" at index 2
cout<<str.insert(5,"ness")<<endl; // this is not zero based indexing
s = str.substr(2,5); // copy char from index 2 that is 'e' till 5 ie 'e' in word 'greatness'
cout<<s<<endl;
s = "3000";
int x = stoi(s); // convert string to int datatype
cout<<x/10<<endl;
x = 420;
s = to_string(x);
cout<<s + " samaj jao"<<endl; // convert int to string
cout<<endl;
str += str1 + str2 +s + "@#!$%&*($#@1356";
cout<<str<<endl;//adding all the strings or concatenating
cout<<endl;
//sorting string
sort(str.begin(),str.end());
cout<<str<<endl; // 2 spaces are sorted first because in the word "lost frequencies"
return 0;
} | 2,128 | 767 |
#include <OgreVector3.h>
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <rviz/ogre_helpers/shape.h>
#include <dwl_rviz_plugin/PointVisual.h>
namespace dwl_rviz_plugin
{
PointVisual::PointVisual(Ogre::SceneManager* scene_manager,
Ogre::SceneNode* parent_node) : radius_(0.)
{
scene_manager_ = scene_manager;
// Ogre::SceneNode s form a tree, with each node storing the transform (position and
// orientation) of itself relative to its parent. Ogre does the math of combining those
// transforms when it is time to render.
// Here we create a node to store the pose of the Point's header frame relative to the RViz
// fixed frame.
frame_node_ = parent_node->createChildSceneNode();
// We create the point object within the frame node so that we can set its position.
point_ = new rviz::Shape(rviz::Shape::Sphere, scene_manager_, frame_node_);
}
PointVisual::~PointVisual()
{
// Delete the point to make it disappear.
delete point_;
// Destroy the frame node since we don't need it anymore.
scene_manager_->destroySceneNode(frame_node_);
}
void PointVisual::setPoint(const Ogre::Vector3& point)
{
Ogre::Vector3 scale(radius_, radius_, radius_);
point_->setScale(scale);
// Set the orientation of the arrow to match the direction of the acceleration vector.
point_->setPosition(point);
}
void PointVisual::setFramePosition(const Ogre::Vector3& position)
{
frame_node_->setPosition(position);
}
void PointVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frame_node_->setOrientation(orientation);
}
void PointVisual::setColor(float r, float g, float b, float a)
{
point_->setColor(r, g, b, a);
}
void PointVisual::setRadius(float r)
{
radius_ = r;
}
} //@namespace dwl_rviz_plugin
| 1,761 | 583 |
//%Header {
/*****************************************************************************
*
* File: src/TestMushMesh/TestMushMeshApp.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
****************************************************************************/
//%Header } fLo4NYe7P7n7p3BjMIvqPA
/*
* $Id: TestMushMeshApp.cpp,v 1.11 2006/06/01 15:40:01 southa Exp $
* $Log: TestMushMeshApp.cpp,v $
* Revision 1.11 2006/06/01 15:40:01 southa
* DrawArray verification and fixes
*
* Revision 1.10 2005/05/19 13:02:22 southa
* Mac release work
*
* Revision 1.9 2004/01/02 21:13:16 southa
* Source conditioning
*
* Revision 1.8 2003/10/24 12:39:09 southa
* Triangular mesh work
*
* Revision 1.7 2003/10/23 20:03:58 southa
* End mesh work
*
* Revision 1.6 2003/10/20 13:02:54 southa
* Patch fixes and testing
*
* Revision 1.5 2003/10/17 12:27:20 southa
* Line end fixes and more mesh work
*
* Revision 1.4 2003/10/15 12:23:10 southa
* MushMeshArray neighbour testing and subdivision work
*
* Revision 1.3 2003/10/15 11:54:54 southa
* MushMeshArray neighbour testing and subdivision
*
* Revision 1.2 2003/10/15 07:08:29 southa
* MushMeshArray creation
*
* Revision 1.1 2003/10/14 13:07:26 southa
* MushMesh vector creation
*
*/
#include "TestMushMeshApp.h"
using namespace Mushware;
using namespace std;
MUSHCORE_SINGLETON_INSTANCE(TestMushMeshApp);
U32 TestMushMeshApp::m_passCount=0;
TestMushMeshApp::tFails TestMushMeshApp::m_fails;
void
TestMushMeshApp::EnterInstance(void)
{
cout << "Starting tests" << endl;
RunTest("testvector", "MushMeshVector");
RunTest("testbox", "MushMeshBox");
RunTest("testarray", "MushMeshArray");
RunTest("testtriangulararray", "MushMeshTriangularArray");
RunTest("testutils", "MushMeshUtils");
RunTest("testpatch", "MushMeshPatch");
RunTest("testsubdivide", "MushMeshSubdivide");
}
void
TestMushMeshApp::RunTest(const string& inCommandStr, const string& inNameStr)
{
cout << "Test " << inNameStr << "... ";
try
{
MushcoreInterpreter::Sgl().Execute(inCommandStr);
PassAdd(inNameStr);
cout << "passed";
}
catch (MushcoreFail& e)
{
cout << "FAILED";
FailureAdd(inNameStr+": "+e.what());
}
cout << endl;
}
void
TestMushMeshApp::Enter(void)
{
Sgl().EnterInstance();
}
void
TestMushMeshApp::FailureAdd(const std::string& inStr)
{
m_fails.push_back(inStr);
}
void
TestMushMeshApp::PassAdd(const std::string& inStr)
{
++m_passCount;
}
void
TestMushMeshApp::FailuresPrint(void)
{
if (m_fails.size() == 0)
{
cout << "All " << m_passCount << " tests passed" << endl;
}
else
{
cout << "****** " << m_fails.size() << " test failures" << endl;
cout << "Failure report:" << endl;
}
for (tFails::const_iterator p = m_fails.begin(); p != m_fails.end(); ++p)
{
cout << *p << endl;
}
}
| 4,038 | 1,589 |
/*
The Adventure Engine
Copyright (c) 2013, Joshua Scoggins
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Joshua Scoggins nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins 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.
*/
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include <System/Backends/Scummvm/AdventureEngine.h>
#include "common/events.h"
#include "common/system.h"
extern "C" {
#include <System/Input/KeyboardInput.h>
#include <System/Core/clips.h>
}
#define PullOutEngine(env) (AdventureEngine::AdventureEngineEngine*)GetEnvironmentContext(env)
#define NullMultifield(env, rVal) EnvSetMultifieldErrorValue(env, rVal)
extern "C" void GetCurrentlyPressedKeys(void* theEnv, DATA_OBJECT_PTR returnValue) {
void* multifield;
AdventureEngine::AdventureEngineEngine* engine = PullOutEngine(theEnv);
Common::EventManager* _eventMan = engine->getEventManager();
Common::Event keyEvent;
//this function does generate side effects if we assert facts
//However, if we return a multifield with all the contents then we need to
//parse it....hmmmmmm, doing the multifield is easier
//only check for a single key at this point
while(_eventMan->pollEvent(keyEvent))
{
//let's do a simple test
switch(keyEvent.type) {
case Common::EVENT_KEYDOWN:
switch(keyEvent.kbd.keycode) {
case Common::KEYCODE_ESCAPE:
multifield = EnvCreateMultifield(theEnv, 1);
SetMFType(multifield, 1, SYMBOL);
SetMFValue(multifield, 1, EnvAddSymbol(theEnv, (char*)"escape"));
SetpType(returnValue, MULTIFIELD);
SetpValue(returnValue, multifield);
SetpDOBegin(returnValue, 1);
SetpDOEnd(returnValue, 1);
return;
default:
multifield = EnvCreateMultifield(theEnv, 1);
SetMFType(multifield, 1, INTEGER);
SetMFValue(multifield, 1, EnvAddLong(theEnv, keyEvent.kbd.keycode));
SetpType(returnValue, MULTIFIELD);
SetpValue(returnValue, multifield);
SetpDOBegin(returnValue, 1);
SetpDOEnd(returnValue, 1);
return;
}
default:
NullMultifield(theEnv, returnValue);
return;
}
}
NullMultifield(theEnv, returnValue);
}
#undef PullOutEngine
#undef NullMultifield
| 3,753 | 1,215 |
/*
The Original EM/MPM algorithm was developed by Mary L. Comer and is distributed
under the BSD License.
Copyright (c) <2010>, <Mary L. Comer>
All rights reserved.
[1] Comer, Mary L., and Delp, Edward J., ÒThe EM/MPM Algorithm for Segmentation
of Textured Images: Analysis and Further Experimental Results,Ó IEEE Transactions
on Image Processing, Vol. 9, No. 10, October 2000, pp. 1731-1744.
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 <Mary L. Comer> nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* acvmpm.c */
/* Modified by Joel Dumke on 1/30/09 */
/* Heavily modified from the original by Michael A. Jackson for BlueQuartz Software
* and funded by the Air Force Research Laboratory, Wright-Patterson AFB.
*/
#include "MPMCalculation.h"
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#include "EMMPMLib/Core/EMMPM.h"
#include "EMMPMLib/Common/MSVCDefines.h"
#include "EMMPMLib/Common/EMMPM_Math.h"
#include "EMMPMLib/Common/EMTime.h"
#include "EMMPMLib/Core/EMMPMUtilities.h"
#define USE_TBB_TASK_GROUP 0
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
#include <tbb/task_scheduler_init.h>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range2d.h>
#include <tbb/partitioner.h>
#include <tbb/task_group.h>
#endif
#define COMPUTE_C_CLIQUE( C, x, y, ci, cj)\
if((x) < 0 || (x) >= colEnd || (y) < 0 || (y) >= rowEnd) {\
C[ci][cj] = classes;\
}\
else\
{\
ij = (cols * (y)) + (x);\
C[ci][cj] = xt[ij];\
}
/**
* @class ParallelCalcLoop ParallelCalcLoop.h EMMPM/Curvature/ParallelCalcLoop.h
* @brief This class can calculate the parts of the MPM loop in parallel
* @author Michael A. Jackson for BlueQuartz Software
* @date March 11, 2012
* @version 1.0
*/
class ParallelMPMLoop
{
public:
#if USE_TBB_TASK_GROUP
ParallelCalcLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd, int rowStart, int rowEnd,
int colStart, int colEnd) :
m_RowStart(rowStart),
m_RowEnd(rowEnd),
m_ColStart(colStart),
m_ColEnd(colEnd),
#else
ParallelMPMLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd) :
#endif
data(dPtr),
yk(ykPtr),
rnd(rnd)
{}
virtual ~ParallelMPMLoop(){}
void calc(int rowStart, int rowEnd,
int colStart, int colEnd) const
{
//uint64_t millis = EMMPM_getMilliSeconds();
// int l;
real_t prior;
int32_t ij, lij;
int rows = data->rows;
int cols = data->columns;
int classes = data->classes;
real_t xrnd, current;
real_t post[EMMPM_MAX_CLASSES], sum, edge;
size_t nsCols = data->columns - 1;
size_t ewCols = data->columns;
size_t swCols = data->columns - 1;
size_t nwCols = data->columns - 1;
unsigned char* xt = data->xt;
real_t* probs = data->probs;
real_t* ccost = data->ccost;
real_t* ns = data->ns;
real_t* ew = data->ew;
real_t* sw = data->sw;
real_t* nw = data->nw;
real_t curvature_value = (real_t)0.0;
int C[3][3]; // This is the Clique for the current Pixel
// --------- X -----
// | | 0 | 1 | 2 |
// -----------------
// Y | 0 | | | |
// -----------------
// | 1 | | P | |
// -----------------
// | 2 | | | |
//
// When we calculate the "C" matrix if the pixel value for the specific index of
// the clique would be off the image then a value = number of classes is
// used for the C[i][j]. That way we can figure out if we are off the image
std::stringstream ss;
unsigned int cSize = classes + 1;
real_t* coupling = data->couplingBeta;
for (int32_t y = rowStart; y < rowEnd; y++)
{
for (int32_t x = colStart; x < colEnd; x++)
{
/* ------------- */
COMPUTE_C_CLIQUE(C, x-1, y-1, 0, 0);
COMPUTE_C_CLIQUE(C, x, y-1, 1, 0);
COMPUTE_C_CLIQUE(C, x+1, y-1, 2, 0);
COMPUTE_C_CLIQUE(C, x-1, y, 0, 1);
COMPUTE_C_CLIQUE(C, x+1, y, 2, 1);
COMPUTE_C_CLIQUE(C, x-1, y+1, 0, 2);
COMPUTE_C_CLIQUE(C, x, y+1, 1, 2);
COMPUTE_C_CLIQUE(C, x+1, y+1, 2, 2);
#if 0
if (y == rowStart + 1 && x == colStart + 1)
{
ss << "------------------------------" << std::endl;
ss << "|" << C[0][0] << "\t" << C[1][0] << "\t" << C[2][0] << std::endl;
ss << "|" << C[0][1] << "\t" << C[1][1] << "\t" << C[2][1] << std::endl;
ss << "|" << C[0][2] << "\t" << C[1][2] << "\t" << C[2][2] << std::endl;
ss << "------------------------------" << std::endl;
std::cout << ss.str() << std::endl;
}
#endif
ij = (cols*y)+x;
sum = 0;
for (int l = 0; l < classes; ++l)
{
prior = 0;
edge = 0;
prior += coupling[(cSize*l)+ C[0][0]];
prior += coupling[(cSize*l)+ C[1][0]];
prior += coupling[(cSize*l)+ C[2][0]];
prior += coupling[(cSize*l)+ C[0][1]];
prior += coupling[(cSize*l)+ C[2][1]];
prior += coupling[(cSize*l)+ C[0][2]];
prior += coupling[(cSize*l)+ C[1][2]];
prior += coupling[(cSize*l)+ C[2][2]];
#if 0
if (y == rowStart + 1 && x == colStart + 1)
{
std::cout << "Class: " << l << "\t prior: " << prior << std::endl;
}
#endif
// now check for the gradient penalty. If our current class is NOT equal
// to the class at index[i][j] AND the value of C[i][j] does NOT equal
// to the Number of Classes then add in the gradient penalty.
if (data->useGradientPenalty)
{
if (C[0][0] != l && C[0][0] != classes) edge += sw[(swCols*(y-1))+x-1];
if (C[1][0] != l && C[1][0] != classes) edge += ew[(ewCols*(y-1))+x];
if (C[2][0] != l && C[2][0] != classes) edge += nw[(nwCols*(y-1))+x];
if (C[0][1] != l && C[0][1] != classes) edge += ns[(nsCols*y)+x-1];
if (C[2][1] != l && C[2][1] != classes) edge += ns[(nsCols*y)+x];
if (C[0][2] != l && C[0][2] != classes) edge += nw[(nwCols*y)+x-1];
if (C[1][2] != l && C[1][2] != classes) edge += ew[(ewCols*y)+x];
if (C[2][2] != l && C[2][2] != classes) edge += sw[(swCols*y)+x];
}
lij = (cols * rows * l) + (cols * y) + x;
curvature_value = 0.0;
if (data->useCurvaturePenalty)
{
curvature_value = data->beta_c * ccost[lij];
}
real_t arg = data->workingKappa * (yk[lij] - (prior) - (edge) - (curvature_value) - data->w_gamma[l]);
post[l] = expf(arg);
sum += post[l];
}
xrnd = rnd[ij];
current = 0.0;
for (int l = 0; l < classes; l++)
{
lij = (cols * rows * l) + ij;
real_t arg = post[l] / sum;
if ((xrnd >= current) && (xrnd <= (current + arg)))
{
xt[ij] = l;
probs[lij] += 1.0;
}
current += arg;
}
#if 0
Dont even THINK about using this code...
This classifys the pixel based on the largest
in magnitude probability
real_t max = 0.0;
int maxClass = 0;
for (int l = 0; l < classes; l++)
{
lij = (cols * rows * l) + ij;
//real_t arg = post[l] / sum;
if (probs[lij] > max)
{
max = probs[lij];
maxClass = l;
}
}
//Assign class based on Maximum probability
xt[ij] = maxClass;
#endif
}
}
// std::cout << " --" << EMMPM_getMilliSeconds() - millis << "--" << std::endl;
}
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
#if USE_TBB_TASK_GROUP
void operator()() const
{
calc(m_RowStart, m_RowEnd, m_ColStart, m_ColEnd);
}
#else
void operator()(const tbb::blocked_range2d<int> &r) const
{
calc(r.rows().begin(), r.rows().end(), r.cols().begin(), r.cols().end());
}
#endif
#endif
private:
#if USE_TBB_TASK_GROUP
int m_RowStart;
int m_RowEnd;
int m_ColStart;
int m_ColEnd;
#endif
const EMMPM_Data* data;
const real_t* yk;
const real_t* rnd;
};
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MPMCalculation::MPMCalculation() :
m_StatsDelegate(NULL)
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MPMCalculation::~MPMCalculation()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MPMCalculation::execute()
{
EMMPM_Data* data = m_Data.get();
real_t* yk;
real_t sqrt2pi, con[EMMPM_MAX_CLASSES];
real_t post[EMMPM_MAX_CLASSES];
// int k, l;
// unsigned int i, j, d;
size_t ld, ijd, lij;
unsigned int dims = data->dims;
unsigned int rows = data->rows;
unsigned int cols = data->columns;
unsigned int classes = data->classes;
// int rowEnd = rows/2;
unsigned char* y = data->y;
real_t* probs = data->probs;
real_t* m = data->mean;
real_t* v = data->variance;
char msgbuff[256];
float totalLoops;
int currentLoopCount;
// real_t curvature_value = (real_t)0.0;
memset(post, 0, EMMPM_MAX_CLASSES * sizeof(real_t));
memset(con, 0, EMMPM_MAX_CLASSES * sizeof(real_t));
totalLoops = (float)(data->emIterations * data->mpmIterations + data->mpmIterations);
memset(msgbuff, 0, 256);
data->progress++;
yk = (real_t*)malloc(cols * rows * classes * sizeof(real_t));
sqrt2pi = sqrt(2.0 * M_PI);
for (uint32_t l = 0; l < classes; l++)
{
con[l] = 0;
for (uint32_t d = 0; d < dims; d++)
{
ld = dims * l + d;
con[l] += -log(sqrt2pi * sqrt(v[ld]));
}
}
for (uint32_t i = 0; i < rows; i++)
{
for (uint32_t j = 0; j < cols; j++)
{
for (uint32_t l = 0; l < classes; l++)
{
lij = (cols * rows * l) + (cols * i) + j;
probs[lij] = 0;
yk[lij] = con[l];
for (uint32_t d = 0; d < dims; d++)
{
ld = dims * l + d;
ijd = (dims * cols * i) + (dims * j) + d;
yk[lij] += ((y[ijd] - m[ld]) * (y[ijd] - m[ld]) / (-2.0 * v[ld]));
}
}
}
}
const float rangeMin = 0;
const float rangeMax = 1.0f;
typedef boost::uniform_real<real_t> NumberDistribution;
typedef boost::mt19937 RandomNumberGenerator;
typedef boost::variate_generator<RandomNumberGenerator&,
NumberDistribution> Generator;
NumberDistribution distribution(rangeMin, rangeMax);
RandomNumberGenerator generator;
Generator numberGenerator(generator, distribution);
generator.seed(EMMPM_getMilliSeconds()); // seed with the current time
// Generate all the numbers up front
size_t total = rows * cols;
std::vector<real_t> rndNumbers(total);
real_t* rndNumbersPtr = &(rndNumbers.front());
for(size_t i = 0; i < total; ++i)
{
rndNumbersPtr[i] = numberGenerator(); // Work directly with the pointer for speed.
}
//unsigned long long int millis = EMMPM_getMilliSeconds();
//std::cout << "------------------------------------------------" << std::endl;
/* Perform the MPM loops */
for (int32_t k = 0; k < data->mpmIterations; k++)
{
data->currentMPMLoop = k;
if (data->cancel) { data->progress = 100.0; break; }
data->inside_mpm_loop = 1;
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
tbb::task_scheduler_init init;
int threads = init.default_num_threads();
#if USE_TBB_TASK_GROUP
tbb::task_group* g = new tbb::task_group;
unsigned int rowIncrement = rows/threads;
unsigned int rowStop = 0 + rowIncrement;
unsigned int rowStart = 0;
for (int t = 0; t < threads; ++t)
{
g->run(ParallelCalcLoop(data, yk, &(rndNumbers.front()), rowStart, rowStop, 0, cols) );
rowStart = rowStop;
rowStop = rowStop + rowIncrement;
if (rowStop >= rows)
{
rowStop = rows;
}
}
g->wait();
delete g;
#else
tbb::parallel_for(tbb::blocked_range2d<int>(0, rows, rows/threads, 0, cols, cols),
ParallelMPMLoop(data, yk, &(rndNumbers.front())),
tbb::simple_partitioner());
#endif
#else
ParallelMPMLoop pcl(data, yk, &(rndNumbers.front()));
pcl.calc(0, rows, 0, cols);
#endif
//std::cout << "Counter: " << counter << std::endl;
EMMPMUtilities::ConvertXtToOutputImage(getData());
data->currentMPMLoop = k;
// snprintf(msgbuff, 256, "MPM Loop %d", data->currentMPMLoop);
// notify(msgbuff, 0, UpdateProgressMessage);
currentLoopCount = data->mpmIterations * data->currentEMLoop + data->currentMPMLoop;
data->progress = currentLoopCount / totalLoops * 100.0;
// notify("", data->progress, UpdateProgressValue);
if (m_StatsDelegate != NULL)
{
m_StatsDelegate->reportProgress(m_Data);
}
}
#if 0
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
std::cout << "Parrallel MPM Loop Time to Complete:";
#else
std::cout << "Serial MPM Loop Time To Complete: ";
#endif
std::cout << (EMMPM_getMilliSeconds() - millis) << std::endl;
#endif
data->inside_mpm_loop = 0;
if (!data->cancel)
{
/* Normalize probabilities */
for (uint32_t i = 0; i < data->rows; i++)
{
for (uint32_t j = 0; j < data->columns; j++)
{
for (uint32_t l = 0; l < classes; l++)
{
lij = (cols * rows * l) + (cols * i) + j;
data->probs[lij] = data->probs[lij] / (real_t)data->mpmIterations;
}
}
}
}
/* Clean Up Memory */
free(yk);
}
| 15,499 | 5,725 |
// clang-format off
#include "Window.h"
#include "Events/KeyEvents.h"
#include "Events/WindowEvents.h"
#include "Events/MouseEvents.h"
#include <utility>
// clang-format on
namespace Engine {
Window::Window(WindowProps props)
: m_data(std::move(props))
{
glfwSetErrorCallback(
[](int code, const char* msg) { ENGINE_ERROR("[GLFW] Error {}: {}", code, msg); });
glfwInit();
m_context =
glfwCreateWindow(m_data.width, m_data.height, m_data.title.data(), nullptr, nullptr);
glfwMakeContextCurrent(m_context);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
ENGINE_ERROR("[GLAD] Could not load GLAD!");
glfwSetWindowUserPointer(m_context, reinterpret_cast<void*>(&m_data));
glfwSetWindowCloseCallback(m_context, [](GLFWwindow* window) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowClosedEvent event;
data.callback(event);
});
glfwSetWindowPosCallback(m_context, [](GLFWwindow* window, int x, int y) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowMovedEvent event(x, y);
data.callback(event);
});
glfwSetWindowSizeCallback(m_context, [](GLFWwindow* window, int width, int height) {
// TODO: Should framebuffer be resized here?
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowResizedEvent event(width, height);
data.callback(event);
});
glfwSetWindowFocusCallback(m_context, [](GLFWwindow* window, int focus) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch (focus)
{
case 1: {
WindowFocusedEvent event;
data.callback(event);
break;
}
case 0: {
WindowLostFocusEvent event;
data.callback(event);
break;
}
}
});
glfwSetCursorPosCallback(m_context, [](GLFWwindow* window, double x, double y) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
MouseMovedEvent event(x, y);
data.callback(event);
});
glfwSetMouseButtonCallback(m_context, [](GLFWwindow* window, int button, int action, int mods) {
(void)mods;
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch (action)
{
case GLFW_PRESS: {
MouseButtonPressedEvent event(button);
data.callback(event);
break;
}
case GLFW_RELEASE: {
MouseButtonReleasedEvent event(button);
data.callback(event);
break;
}
}
});
glfwSetScrollCallback(m_context, [](GLFWwindow* window, double xOffset, double yOffset) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
MouseScrolledEvent event(xOffset, yOffset);
data.callback(event);
});
glfwSetKeyCallback(m_context, [](GLFWwindow* window, int key, int scancode, int action, int mod) {
(void)scancode;
(void)action;
(void)mod;
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch(action) {
case GLFW_PRESS:
{
KeyPressedEvent event(key);
data.callback(event);
break;
}
case GLFW_RELEASE:
{
KeyReleasedEvent event(key);
data.callback(event);
break;
}
}
});
// TODO callbacks: key pressed, key
// released
}
Window::~Window()
{
glfwDestroyWindow(m_context);
glfwTerminate();
}
void Window::update()
{
glfwSwapBuffers(m_context);
glfwPollEvents();
}
void Window::setCallbackFunction(const CallbackFn& fn) { m_data.callback = fn; }
} // namespace Engine
| 4,011 | 1,242 |
#include "CCRubyEngine.h"
#include "RubyBridge.h"
#include "ruby_cocos2dx_auto.hpp"
#include "ruby_cocos2dx_audioengine_auto.hpp"
#include "ManualImplement.h"
#include "RubyValueMap.h"
NS_CC_BEGIN
RubyEngine* RubyEngine::_defaultEngine = nullptr;
RubyEngine* RubyEngine::getInstance(void)
{
if (!_defaultEngine)
{
_defaultEngine = new (std::nothrow) RubyEngine();
//_defaultEngine->init();
}
return _defaultEngine;
}
RubyEngine::RubyEngine(void)
{
_init_Ruby_VM();
register_all_cocos2dx();
register_all_cocos2dx_audioengine();
manual_implement();
}
RubyEngine::~RubyEngine(void)
{
_defaultEngine=nullptr;
}
int RubyEngine::handleMenuClickedEvent(void* data)
{
if (NULL == data)
return 0;
BasicScriptData* basicScriptData = (BasicScriptData*)data;
if (NULL == basicScriptData->nativeObject)
return 0;
MenuItem* menuItem = static_cast<MenuItem*>(basicScriptData->nativeObject);
RBVAL menuItemValue=rbb_get_or_create_value<cocos2d::MenuItem>(menuItem);
RBVAL onClicked=rb_ivar_get_bridge(menuItemValue,ATID_onClicked());
if (onClicked!=RBNil()){
RBVAL resultVal=rb_proc_call_protected(onClicked);
int result=0;
rb_value_to_int(resultVal,&result);
return result;
}
return 0;
}
int RubyEngine::sendEvent(ScriptEvent* evt){
if (NULL == evt)
return 0;
switch (evt->type)
{
case kMenuClickedEvent:
{
return handleMenuClickedEvent(evt->data);
}
break;
default:
break;
}
return 0;
}
int RubyEngine::executeString(const char* codes) {
return _ruby_executeString(codes);
}
int RubyEngine::executeScriptFile(const char* filename) {
std::string cmd("eval_script \"");
cmd.append(filename);
cmd.append("\"");
return executeString(cmd.c_str());
}
NS_CC_END | 1,885 | 682 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* makeBST(vector<int>& nums,int start,int end) {
if(start>end) return NULL;
TreeNode* t;
if(start==end) {
t=new TreeNode(nums[start]);
} else {
int m=(start+end)/2;
t=new TreeNode(nums[m]);
t->left=makeBST(nums,start,m-1);
t->right=makeBST(nums,m+1,end);
}
return t;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return makeBST(nums,0,nums.size()-1);
}
}; | 747 | 265 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkMimeTypes.h"
const QString QmitkMimeTypes::DataNodePtrs = "application/x-qmitk-datanode-ptrs";
const QString QmitkMimeTypes::DataStorageTreeItemPtrs = "application/x-qmitk-datastorage-treeitem-ptrs";
#include <iostream>
QList<mitk::DataNode *> QmitkMimeTypes::ToDataNodePtrList(const QByteArray &ba)
{
QDataStream ds(ba);
QList<mitk::DataNode*> result;
while(!ds.atEnd())
{
quintptr dataNodePtr;
ds >> dataNodePtr;
result.push_back(reinterpret_cast<mitk::DataNode*>(dataNodePtr));
}
return result;
}
QList<mitk::DataNode *> QmitkMimeTypes::ToDataNodePtrList(const QMimeData *mimeData)
{
if (mimeData == nullptr || !mimeData->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
return QList<mitk::DataNode*>();
}
return ToDataNodePtrList(mimeData->data(QmitkMimeTypes::DataNodePtrs));
}
| 1,332 | 462 |
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <folly/logging/xlog.h>
#include "fboss/agent/hw/bcm/BcmBstStatsMgr.h"
#include "fboss/agent/hw/bcm/BcmControlPlane.h"
#include "fboss/agent/hw/bcm/BcmCosManager.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmPlatform.h"
#include "fboss/agent/hw/bcm/BcmPortTable.h"
#include "fboss/agent/hw/switch_asics/HwAsic.h"
extern "C" {
#include <bcm/field.h>
}
namespace facebook::fboss {
bool BcmBstStatsMgr::startBufferStatCollection() {
if (!isBufferStatCollectionEnabled()) {
hw_->getCosMgr()->enableBst();
bufferStatsEnabled_ = true;
}
return bufferStatsEnabled_;
}
bool BcmBstStatsMgr::stopBufferStatCollection() {
if (isBufferStatCollectionEnabled()) {
hw_->getCosMgr()->disableBst();
bufferStatsEnabled_ = false;
}
return !bufferStatsEnabled_;
}
void BcmBstStatsMgr::syncStats() const {
auto rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdUcast);
bcmCheckError(rv, "Failed to sync bcmBstStatIdUcast stat");
if (hw_->getPlatform()->getAsic()->isSupported(HwAsic::Feature::PFC)) {
// All the below are PG related and available on platforms supporting PFC
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdPriGroupHeadroom);
bcmCheckError(rv, "Failed to sync bcmBstStatIdPriGroupHeadroom stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdPriGroupShared);
bcmCheckError(rv, "Failed to sync bcmBstStatIdPriGroupShared stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdHeadroomPool);
bcmCheckError(rv, "Failed to sync bcmBstStatIdHeadroomPool stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdIngPool);
bcmCheckError(rv, "Failed to sync bcmBstStatIdIngPool stat");
}
}
void BcmBstStatsMgr::getAndPublishDeviceWatermark() {
auto peakUsage = hw_->getCosMgr()->deviceStatGet(bcmBstStatIdDevice);
auto peakBytes = peakUsage * hw_->getMMUCellBytes();
if (peakBytes > hw_->getMMUBufferBytes()) {
// First value read immediately after enabling BST, gives
// a abnormally high usage value (over 1B bytes), which is
// obviously bogus. Warn, but skip writing that value.
XLOG(WARNING)
<< " Got a bogus switch MMU buffer utilization value, peak cells: "
<< peakUsage << " peak bytes: " << peakBytes << " skipping write";
return;
}
deviceWatermarkBytes_.store(peakBytes);
publishDeviceWatermark(peakBytes);
if (isFineGrainedBufferStatLoggingEnabled()) {
bufferStatsLogger_->logDeviceBufferStat(
peakBytes, hw_->getMMUBufferBytes());
}
}
void BcmBstStatsMgr::getAndPublishGlobalWatermarks(
const std::map<int, bcm_port_t>& itmToPortMap) const {
auto cosMgr = hw_->getCosMgr();
for (auto it = itmToPortMap.begin(); it != itmToPortMap.end(); it++) {
int itm = it->first;
bcm_port_t bcmPortId = it->second;
uint64_t maxGlobalHeadroomBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdHeadroomPool) *
hw_->getMMUCellBytes();
uint64_t maxGlobalSharedBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdIngPool) *
hw_->getMMUCellBytes();
publishGlobalWatermarks(itm, maxGlobalHeadroomBytes, maxGlobalSharedBytes);
}
}
void BcmBstStatsMgr::createItmToPortMap(
std::map<int, bcm_port_t>& itmToPortMap) const {
if (itmToPortMap.size() == 0) {
/*
* ITM to port map not available, need to populate it first!
* Global headroom/shared buffer stats are per ITM, but as
* the counters are to be read per port, we need to keep track
* of one port per ITM for which stats can be read. This mapping
* is static and doesnt change.
*/
for (const auto& entry : *hw_->getPortTable()) {
BcmPort* bcmPort = entry.second;
int itm = hw_->getPlatform()->getPortItm(bcmPort);
if (itmToPortMap.find(itm) == itmToPortMap.end()) {
itmToPortMap[itm] = bcmPort->getBcmPortId();
XLOG(DBG2) << "ITM" << itm << " mapped to bcmport "
<< itmToPortMap[itm];
}
}
}
}
void BcmBstStatsMgr::updateStats() {
syncStats();
// Track if PG is enabled on any port in the system
bool pgEnabled = false;
auto qosSupported =
hw_->getPlatform()->getAsic()->isSupported(HwAsic::Feature::L3_QOS);
for (const auto& entry : *hw_->getPortTable()) {
BcmPort* bcmPort = entry.second;
auto curPortStatsOptional = bcmPort->getPortStats();
if (!curPortStatsOptional) {
// ignore ports with no saved stats
continue;
}
auto cosMgr = hw_->getCosMgr();
std::map<int16_t, int64_t> queueId2WatermarkBytes;
auto maxQueueId = qosSupported
? bcmPort->getQueueManager()->getNumQueues(cfg::StreamType::UNICAST) - 1
: 0;
for (int queue = 0; queue <= maxQueueId; queue++) {
auto peakBytes = 0;
if (bcmPort->isUp()) {
auto peakCells = cosMgr->statGet(
PortID(bcmPort->getBcmPortId()), queue, bcmBstStatIdUcast);
peakBytes = peakCells * hw_->getMMUCellBytes();
}
queueId2WatermarkBytes[queue] = peakBytes;
publishQueueuWatermark(bcmPort->getPortName(), queue, peakBytes);
if (isFineGrainedBufferStatLoggingEnabled()) {
getBufferStatsLogger()->logPortBufferStat(
bcmPort->getPortName(),
BufferStatsLogger::Direction::Egress,
queue,
peakBytes,
curPortStatsOptional->queueOutDiscardBytes__ref()->at(queue),
bcmPort->getPlatformPort()->getEgressXPEs());
}
}
bcmPort->setQueueWaterMarks(std::move(queueId2WatermarkBytes));
// Get PG MAX headroom/shared stats
if (bcmPort->isPortPgConfigured()) {
bcm_port_t bcmPortId = bcmPort->getBcmPortId();
uint64_t maxHeadroomBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdPriGroupHeadroom) *
hw_->getMMUCellBytes();
uint64_t maxSharedBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdPriGroupShared) *
hw_->getMMUCellBytes();
publishPgWatermarks(
bcmPort->getPortName(), maxHeadroomBytes, maxSharedBytes);
pgEnabled = true;
}
}
if (pgEnabled) {
/*
* Ingress Traffic Manager(ITM) is part of the MMU. The ports in the
* system are split between multiple ITMs and the ITMs has buffers
* shared by all port which are part of the same ITM. The global
* ingress buffer statistics are tracked per ITM and hence needs
* to be fetched only once per ITM. This would mean we first find
* the port->ITM mapping and then read the statistics once per ITM.
*/
static std::map<int, bcm_port_t> itmToPortMap;
createItmToPortMap(itmToPortMap);
getAndPublishGlobalWatermarks(itmToPortMap);
}
// Get watermark stats for CPU queues
if (qosSupported) {
auto controlPlane = hw_->getControlPlane();
HwPortStats cpuStats;
controlPlane->updateQueueWatermarks(&cpuStats);
for (const auto& [cosQ, stats] : *cpuStats.queueWatermarkBytes__ref()) {
publishCpuQueueWatermark(cosQ, stats);
}
}
getAndPublishDeviceWatermark();
}
} // namespace facebook::fboss
| 7,595 | 2,723 |
#include "gepch.h"
#include "MouseReleasedEvent.h"
namespace GE
{
MouseReleasedEvent::MouseReleasedEvent(int code) :
MouseEvent(code)
{}
std::string MouseReleasedEvent::toString() const
{
return "MouseClickedReleased: button= " + toStringBut(keyPressed());
}
} | 271 | 99 |
/*
* Copyright (C) 2009-2012, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <cctype>
#include <libport/lexical-cast.hh>
#include <object/format-info.hh>
#include <urbi/object/global.hh>
#include <urbi/object/symbols.hh>
namespace urbi
{
namespace object
{
FormatInfo::FormatInfo()
: alignment_(Align::RIGHT)
, alt_(false)
, consistent_(true)
, group_("")
, pad_(" ")
, pattern_("%s")
, precision_(6)
, prefix_("")
, rank_(0)
, spec_("s")
, uppercase_(Case::UNDEFINED)
, width_(0)
{
proto_add(proto ? rObject(proto) : Object::proto);
}
FormatInfo::FormatInfo(rFormatInfo model)
: alignment_(model->alignment_)
, alt_(model->alt_)
, consistent_(model->consistent_)
, group_(model->group_)
, pad_(model->pad_)
, pattern_(model->pattern_)
, precision_(model->precision_)
, prefix_(model->prefix_)
, rank_(model->rank_)
, spec_(model->spec_)
, uppercase_(model->uppercase_)
, width_(model->width_)
{
proto_add(model);
}
URBI_CXX_OBJECT_INIT(FormatInfo)
: alignment_(Align::RIGHT)
, alt_(false)
, consistent_(true)
, group_("")
, pad_(" ")
, pattern_("%s")
, precision_(6)
, prefix_("")
, rank_(0)
, spec_("s")
, uppercase_(Case::UNDEFINED)
, width_(0)
{
BIND(init);
BIND(asString, as_string);
BINDG(pattern, pattern_get);
# define DECLARE(Name) \
bind(#Name, &FormatInfo::Name ##_get, &FormatInfo::Name ##_set);
DECLARE(alignment);
DECLARE(alt);
DECLARE(group);
DECLARE(pad);
DECLARE(precision);
DECLARE(prefix);
DECLARE(rank);
DECLARE(spec);
DECLARE(uppercase);
DECLARE(width);
# undef DECLARE
}
void
FormatInfo::init(const std::string& pattern)
{
init_(pattern, true);
}
void
FormatInfo::init_(const std::string& pattern, bool check_end)
{
if (pattern.empty())
RAISE("format: empty pattern");
if (pattern[0] != '%')
FRAISE("format: pattern does not begin with %%: %s", pattern);
if (pattern.size() == 1)
RAISE("format: trailing `%'");
const char* digits = "0123456789";
// Cursor inside pattern.
size_t cursor = 1;
// Whether between `|'.
bool piped = pattern[cursor] == '|';
if (piped)
++cursor;
// Whether a simple positional request: %<rank>%, in which case,
// no flags admitted.
bool percented = false;
// Whether there is a positional argument: <NUM>$, or if
// it's a %<rank>% (but then, no pipe accepted).
{
// First non digit.
size_t sep = pattern.find_first_not_of(digits, cursor);
// If there are digits, and then a $, then we have a
// positional argument.
if (sep != cursor
&& sep < pattern.size()
&& (pattern[sep] == '$'
|| (!piped && pattern[sep] == '%')))
{
percented = pattern[sep] == '%';
rank_ = lexical_cast<size_t>(pattern.substr(cursor, sep - cursor));
if (!rank_)
FRAISE("format: invalid positional argument: %s",
pattern.substr(cursor, sep - cursor));
cursor = sep + 1;
}
else
rank_ = 0;
}
// Parsing flags.
if (!percented)
{
std::string flags("-=+#0 '");
std::string excludes;
char current;
for (;
cursor < pattern.size()
&& libport::has(flags, current = pattern[cursor]);
++cursor)
if (libport::has(excludes, current))
FRAISE("format: '%s' conflicts with one of these flags: \"%s\"",
current, excludes);
else
switch (current)
{
case '-': alignment_ = Align::LEFT; excludes += "-="; break;
case '=': alignment_ = Align::CENTER; excludes += "-="; break;
case '+': prefix_ = "+"; excludes += " +"; break;
case ' ': prefix_ = " "; excludes += " +"; break;
case '0': pad_ = "0"; break;
case '#': alt_ = true; break;
case '\'': group_ = " "; break;
};
}
// Parsing width.
if (!percented)
if (size_t w = pattern.find_first_not_of(digits, cursor) - cursor)
{
width_ = lexical_cast<size_t>(pattern.substr(cursor, w));
cursor += w;
}
// Parsing precision.
if (!percented
&& cursor < pattern.size() && pattern[cursor] == '.')
{
++cursor;
if (size_t w = pattern.find_first_not_of(digits, cursor) - cursor)
{
precision_ = lexical_cast<size_t>(pattern.substr(cursor, w));
cursor += w;
}
else
FRAISE("format: invalid width after `.': %s", pattern[cursor]);
}
// Parsing spec. Optional if piped.
if (!percented
&& cursor < pattern.size()
&& (!piped || pattern[cursor] != '|'))
{
spec_ = tolower(pattern[cursor]);
if (!strchr("sdbxoef", spec_[0]))
FRAISE("format: invalid conversion type character: %s", spec_);
else if (spec_ != "s")
uppercase_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;
++cursor;
}
if (piped)
{
if (cursor < pattern.size())
++cursor;
else {
RAISE("format: missing closing '|'");
}
}
if (check_end && cursor < pattern.size())
FRAISE("format: spurious characters after format: %s",
pattern.substr(cursor));
pattern_ = pattern.substr(0, cursor);
}
std::string
FormatInfo::as_string() const
{
return pattern_get();
}
const std::string&
FormatInfo::pattern_get() const
{
if (!consistent_)
{
pattern_ = compute_pattern();
consistent_ = true;
}
return pattern_;
}
std::string
FormatInfo::compute_pattern(bool for_float) const
{
// To format floats, we rely on Boost.Format.
size_t rank = rank_;
char spec = spec_[0];
if (for_float)
{
rank = 0;
if (spec == 's' || spec == 'd') spec = 'g';
if (spec == 'D') spec = 'G';
}
return std::string("%|")
+ (rank == 0 ? "" : (string_cast(rank) + "$"))
+ ((alignment_ == Align::RIGHT) ? ""
: (alignment_ == Align::LEFT) ? "-"
: "=")
+ (alt_ ? "#" : "")
+ (group_ == "" ? "" : "'")
+ (pad_ == " " ? "" : "0")
+ prefix_
+ (width_ == 0 ? "" : string_cast(width_))
+ (precision_ == 6 ? "" : "." + string_cast(precision_))
+ (uppercase_ == Case::UPPER ? char(toupper(spec)) : spec)
+ '|';
}
void
FormatInfo::alignment_set(Align::position val)
{
alignment_ = val;
consistent_ = false;
}
void
FormatInfo::group_set(std::string v)
{
if (!v.empty() && v != " ")
FRAISE("expected \" \" or \"\": \"%s\"", v);
group_ = v;
consistent_ = false;
}
void
FormatInfo::pad_set(std::string v)
{
if (v != " " && v != "0")
FRAISE("expected \" \" or \"0\": \"%s\"", v);
pad_ = v;
consistent_ = false;
}
void
FormatInfo::prefix_set(std::string v)
{
if (v != " " && v != "+" && v != "")
FRAISE("expected \"\", \" \" or \"+\": \"%s\"", v);
prefix_ = v;
consistent_ = false;
}
void
FormatInfo::spec_set(std::string val_)
{
if (val_.size() != 1)
RAISE("expected one-character long string: " + val_);
if (!strchr("sdbxoefEDX", val_[0]))
RAISE("expected one character in \"sdbxoefEDX\": \"" + val_ + "\"");
spec_ = val_;
std::transform(spec_.begin(), spec_.end(), spec_.begin(), ::tolower);
uppercase_ = (spec_ == "s" ? Case::UNDEFINED
: islower(val_[0]) ? Case::LOWER
: Case::UPPER);
consistent_ = false;
}
void
FormatInfo::uppercase_set(int v)
{
switch (v)
{
#define CASE(In, Out, Spec) \
case In: uppercase_ = Case::Out; spec_ = Spec; break
CASE(-1, LOWER, "d");
CASE( 0, UNDEFINED, "s");
CASE( 1, UPPER, "D");
#undef CASE
default:
FRAISE("expected integer -1, 0 or 1: %s", v);
}
consistent_ = false;
}
void
FormatInfo::alt_set(bool v)
{
alt_ = v;
consistent_ = false;
}
void
FormatInfo::precision_set(size_t v)
{
precision_ = v;
consistent_ = false;
}
void
FormatInfo::rank_set(size_t v)
{
rank_ = v;
consistent_ = false;
}
void
FormatInfo::width_set(size_t v)
{
width_ = v;
consistent_ = false;
}
} // namespace object
}
| 9,424 | 3,049 |
#include <sfc/sfc.hpp>
namespace SuperFamicom {
#include "serialization.cpp"
SufamiTurboCartridge sufamiturboA;
SufamiTurboCartridge sufamiturboB;
auto SufamiTurboCartridge::unload() -> void {
rom.reset();
ram.reset();
}
auto SufamiTurboCartridge::power() -> void {
rom.writeProtect(true);
ram.writeProtect(false);
}
}
| 332 | 140 |
#include <stdio.h>
#include "log.h"
#include "config.h"
void print_config()
{
printf("config:\n");
#ifdef USE_NUMA_TP
xzl_show_define(USE_NUMA_TP);
#else
xzl_show_undefine(USE_NUMA_TP);
#endif
#ifdef USE_TBB_DS
xzl_show_define(USE_TBB_DS)
#else
xzl_show_undefine(USE_TBB_DS)
#endif
#ifdef USE_FOLLY_VECTOR
xzl_show_define(USE_FOLLY_VECTOR)
#else
xzl_show_undefine(USE_FOLLY_VECTOR)
#endif
#ifdef USE_FOLLY_STRING
xzl_show_define(USE_FOLLY_STRING)
#else
xzl_show_undefine(USE_FOLLY_STRING)
#endif
#ifdef USE_FOLLY_HASHMAP
xzl_show_define(USE_FOLLY_HASHMAP)
#else
xzl_show_undefine(USE_FOLLY_HASHMAP)
#endif
#ifdef USE_CUCKOO_HASHMAP
xzl_show_define(USE_CUCKOO_HASHMAP)
#else
xzl_show_undefine(USE_CUCKOO_HASHMAP)
#endif
#ifdef USE_TBB_HASHMAP
xzl_show_define(USE_TBB_HASHMAP)
#else
xzl_show_undefine(USE_TBB_HASHMAP)
#endif
#ifdef USE_NUMA_ALLOC
xzl_show_define(USE_NUMA_ALLOC)
#else
xzl_show_undefine(USE_NUMA_ALLOC)
#endif
#ifdef INPUT_ALWAYS_ON_NODE0
xzl_show_define(INPUT_ALWAYS_ON_NODE0)
#else
xzl_show_undefine(INPUT_ALWAYS_ON_NODE0)
#endif
#ifdef MEASURE_LATENCY
xzl_show_define(MEASURE_LATENCY)
#else
xzl_show_undefine(MEASURE_LATENCY)
#endif
#ifdef CONFIG_SOURCE_THREADS
xzl_show_define(CONFIG_SOURCE_THREADS)
#else
// xzl_show_undefine(CONFIG_SOURCE_THREADS)
#error
#endif
#ifdef CONFIG_MIN_PERNODE_BUFFER_SIZE_MB
xzl_show_define(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB)
#else
// xzl_show_undefine(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB)
#error
#endif
#ifdef CONFIG_MIN_EPOCHS_PERNODE_BUFFER
xzl_show_define(CONFIG_MIN_EPOCHS_PERNODE_BUFFER)
#else
// xzl_show_undefine(X)
#error
#endif
#ifdef CONFIG_NETMON_HT_PARTITIONS
xzl_show_define(CONFIG_NETMON_HT_PARTITIONS)
#else
#error
#endif
#ifdef CONFIG_JOIN_HT_PARTITIONS
xzl_show_define(CONFIG_JOIN_HT_PARTITIONS)
#else
#error
#endif
/* warn about workarounds */
#ifdef WORKAROUND_JOIN_JDD
EE("warning: WORKAROUND_JOIN_JDD = 1. Sure? (any key to continue)\n");
getchar();
#endif
#ifdef WORKAROUND_WINKEYREDUCER_RECORDBUNDLE
EE("warning: WORKAROUND_WINKEYREDUCER_RECORDBUNDLE = 1. Sure? (any key to continue)\n");
getchar();
#endif
/* todo: add more here */
}
// Copyright Vladimir Prus 2002-2004.
// 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)
/* The simplest usage of the library.
*
* http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/first.cpp
* http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/options_description.cpp
*/
#undef _GLIBCXX_DEBUG /* does not get along with program options lib */
#include <iostream>
#include <boost/program_options.hpp>
using namespace std;
namespace po = boost::program_options;
#include <thread>
#include "test-common.h"
void parse_options(int ac, char *av[], pipeline_config* config)
{
po::variables_map vm;
xzl_assert(config);
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("records", po::value<unsigned long>(), "records per wm interval")
("target_tput", po::value<unsigned long>(), "target throughput (krec/s)")
("record_size", po::value<unsigned long>(), "record (string_range) size (bytes)")
("cores", po::value<unsigned long>(), "# cores for worker threads")
("input_file", po::value<vector<string>>(), "input file path") /* must be vector */
;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(1);
}
if (vm.count("records")) {
config->records_per_interval = vm["records"].as<unsigned long>();
}
if (vm.count("target_tput")) {
config->target_tput = vm["target_tput"].as<unsigned long>() * 1000;
}
if (vm.count("record_size")) {
config->record_size = vm["record_size"].as<unsigned long>();
}
if (vm.count("cores")) {
config->cores = vm["cores"].as<unsigned long>();
} else { /* default value for # cores (save one for source) */
config->cores = std::thread::hardware_concurrency() - 1;
}
if (vm.count("input_file")) {
config->input_file = vm["input_file"].as<vector<string>>()[0];
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
abort();
}
catch(...) {
cerr << "Exception of unknown type!\n";
abort();
}
}
| 4,528 | 1,907 |
// Arquivo cmd_add_dolfini_locker_item.hpp
// Criado em 02/06/2018 as 23:20 por Acrisio
// Defini��o da classe CmdAddDolfiniLockerItem
#pragma once
#ifndef _STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
#define _STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
#include "../../Projeto IOCP/PANGYA_DB/pangya_db.h"
#include "../TYPE/pangya_game_st.h"
namespace stdA {
class CmdAddDolfiniLockerItem : public pangya_db {
public:
explicit CmdAddDolfiniLockerItem(bool _waiter = false);
CmdAddDolfiniLockerItem(uint32_t _uid, DolfiniLockerItem& _dli, bool _waiter = false);
virtual ~CmdAddDolfiniLockerItem();
uint32_t getUID();
void setUID(uint32_t _uid);
DolfiniLockerItem& getInfo();
void setInfo(DolfiniLockerItem& _dli);
protected:
void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override;
response* prepareConsulta(database& _db) override;
// get Class name
virtual std::string _getName() override { return "CmdAddDolfiniLockerItem"; };
virtual std::wstring _wgetName() override { return L"CmdAddDolfiniLockerItem"; };
private:
uint32_t m_uid;
DolfiniLockerItem m_dli;
const char* m_szConsulta = "pangya.ProcAddItemDolfiniLocker";
};
}
#endif // !_STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
| 1,249 | 553 |
//
// Created by Hamza El-Kebir on 12/23/21.
//
#ifndef LODESTAR_SWITCHBLOCK_HPP
#define LODESTAR_SWITCHBLOCK_HPP
#include "Lodestar/blocks/Block.hpp"
namespace ls {
namespace blocks {
namespace std {
enum class SwitchBlockParameter {
Parametric,
AdditionalInput
};
template<typename TType,
SwitchBlockParameter TPar = SwitchBlockParameter::Parametric>
class SwitchBlock {
static_assert(::std::is_same<TType, TType>::value,
"SwitchBlock not defined for this type.");
};
template<typename TType>
class SwitchBlock<TType, SwitchBlockParameter::Parametric> :
public Block<
::std::tuple<TType, TType>,
::std::tuple<TType>,
::std::tuple<bool>
> {
public:
using Base =
Block<
::std::tuple<TType, TType>,
::std::tuple<TType>,
::std::tuple<bool>
>;
using type = SwitchBlock<TType, SwitchBlockParameter::Parametric>;
SwitchBlock()
{
state(false);
bindEquation();
}
SwitchBlock(const bool switchState)
{
state(switchState);
bindEquation();
}
bool &state(bool setting)
{
this->template p<0>() = setting;
return this->template p<0>();
}
bool state() const
{
return this->template p<0>();
}
bool &state()
{
return this->template p<0>();
}
void toggle()
{
state(!state());
}
protected:
void bindEquation()
{
this->equation = ::std::bind(
&type::triggerFunction,
this,
::std::placeholders::_1
);
}
void triggerFunction(Base &b)
{
if (state())
this->template o<0>() = this->template i<1>();
else
this->template o<0>() = this->template i<0>();
}
};
template<typename TType>
class SwitchBlock<TType, SwitchBlockParameter::AdditionalInput> :
public Block<
::std::tuple<TType, TType, bool>,
::std::tuple<TType>,
BlockProto::empty
> {
public:
using Base =
Block<
::std::tuple<TType, TType, bool>,
::std::tuple<TType>,
BlockProto::empty
>;
using type = SwitchBlock<TType, SwitchBlockParameter::AdditionalInput>;
SwitchBlock()
{
state(false);
bindEquation();
}
SwitchBlock(const bool switchState)
{
state(switchState);
bindEquation();
}
Signal<bool> &state(bool setting)
{
this->template i<2>() = setting;
return this->template i<2>();
}
Signal<bool> &state(const Signal<bool> &setting)
{
this->template i<2>() = setting;
return this->template i<2>();
}
const Signal<bool> &state() const
{
return this->template i<2>();
}
Signal<bool> &state()
{
return this->template i<2>();
}
void toggle()
{
state(!state().object);
}
protected:
void bindEquation()
{
this->equation = ::std::bind(
&type::triggerFunction,
this,
::std::placeholders::_1
);
}
void triggerFunction(Base &b)
{
if (state().object)
this->template o<0>() = this->template i<1>();
else
this->template o<0>() = this->template i<0>();
}
};
}
template<typename TType, std::SwitchBlockParameter TPar>
class BlockTraits<std::SwitchBlock<TType, TPar>> {
public:
static constexpr const BlockType blockType = BlockType::SwitchBlock;
static constexpr const bool directFeedthrough = true;
using type = std::SwitchBlock<TType, TPar>;
using Base = typename type::Base;
static const constexpr int kIns = type::Base::kIns;
static const constexpr int kOuts = type::Base::kOuts;
static const constexpr int kPars = type::Base::kPars;
};
}
}
#endif //LODESTAR_SWITCHBLOCK_HPP
| 5,704 | 1,314 |
/*
* Copyright 2020 KT AI Lab.
*
* 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 "VLCPlayer.h"
void VLCPlayer::init()
{
/* Load the VLC engine */
inst = libvlc_new (0, NULL);
}
void VLCPlayer::finalize()
{
if(mp!=nullptr)
{
stop();
}
libvlc_release (inst);
}
VLCPlayer::VLCPlayer()
{
init();
}
VLCPlayer::~VLCPlayer()
{
finalize();
}
int VLCPlayer::stop()
{
if(mp==nullptr) return -1;
/* Stop playing */
libvlc_media_player_stop (mp);
/* Free the media_player */
libvlc_media_player_release (mp);
mp=nullptr;
/* No need to keep the media now */
libvlc_media_release (m);
m=nullptr;
play_end_time=std::chrono::steady_clock::now();
return 0;
}
int VLCPlayer::play(const std::string& play_url)
{
/* Create a new item */
m = libvlc_media_new_location (inst,play_url.c_str());
/* Create a media player playing environement */
mp = libvlc_media_player_new_from_media (m);
/* play the media_player */
libvlc_media_player_play (mp);
play_start_time=std::chrono::steady_clock::now();
return 0;
}
int VLCPlayer::pause()
{
if(mp==nullptr) return -1;
libvlc_media_player_set_pause(mp,1);
return 0;
}
int VLCPlayer::resume()
{
if(mp==nullptr) return -1;
libvlc_media_player_set_pause(mp,0);
return 0;
}
long VLCPlayer::getDuration()
{
//if(m==nullptr) return -1;
//return libvlc_media_get_duration (m);
return std::chrono::duration_cast<std::chrono::seconds>(play_end_time-play_start_time).count();
}
| 2,098 | 766 |
/*
**
** $Filename: b3BaseInclude.cc $
** $Release: Dortmund 2006 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Precompiled header file for base package
**
** (C) Copyright 2006 Steffen A. Mork
** All Rights Reserved
**
**
**
*/
/*************************************************************************
** **
** Blizzard III includes **
** **
*************************************************************************/
#include "b3BaseInclude.h"
| 684 | 182 |
// Copyright 2019 Xanadu Quantum Technologies Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file
* Contains functions for calculating the multidimensional
* Hermite polynomials, used for computation of batched hafnians.
*/
#pragma once
#include <stdafx.h>
#include <assert.h>
#include <algorithm>
#include <cstring>
typedef unsigned long long int ullint;
/**
* Returns the index of the one dimensional flattened vector corresponding to the multidimensional tensor
*
* @param pos
* @param cutoff
*
* @return index on flattened vector
*/
ullint vec2index(std::vector<int> &pos, int cutoff) {
int dim = pos.size();
ullint nextCoordinate = 0;
nextCoordinate = pos[0]-1;
for(int ii = 0; ii < dim-1; ii++) {
nextCoordinate = nextCoordinate*cutoff + (pos[ii+1]-1);
}
return nextCoordinate;
}
/**
* Updates the iterators needed for the calculation of the Hermite multidimensional functions
*
* @param nextPos a vector of integers
* @param jumpFrom a vector of integers
* @param jump integer specifying whether to jump to the next index
* @param cutoff integer specifying the cuotff
* @dim dimension of the R matrix
*
* @k index necessary for knowing which elements are needed from the input vector y and matrix R
*/
int update_iterator(std::vector<int> &nextPos, std::vector<int> &jumpFrom, int &jump, const int &cutoff, const int &dim) {
if (jump > 0) {
jumpFrom[jump] += 1;
jump = 0;
}
for (int ii = 0; ii < dim; ii++) {
if ( nextPos[ii] + 1 > cutoff) {
nextPos[ii] = 1;
jumpFrom[ii] = 1;
jump = ii+1;
}
else {
jumpFrom[ii] = nextPos[ii];
nextPos[ii] = nextPos[ii] + 1;
break;
}
}
int k=0;
for(; k < dim; k++) {
if(nextPos[k] != jumpFrom[k]) break;
}
return k;
}
namespace libwalrus {
/**
* Returns the multidimensional Hermite polynomials \f$H_k^{(R)}(y)\f$.
*
* This implementation is based on the MATLAB code available at
* https://github.com/clementsw/gaussian-optics
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param y a flattened vector of size \f$n\f$.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
H[nextCoordinate] = H[fromCoordinate] * y[k];
std::vector<int> tmpjump(dim, 0);
for (int ii = 0; ii < dim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - (static_cast<T>(jumpFrom[ii]-1))*(R[dim*k+ii])*H[prevCoordinate];
}
}
}
return H;
}
/**
* Returns the normalized multidimensional Hermite polynomials \f$\tilde{H}_k^{(R)}(y)\f$.
*
* This implementation is based on the MATLAB code available at
* https://github.com/clementsw/gaussian-optics
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param y a flattened vector of size \f$n\f$.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* renorm_hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<double> intsqrt(cutoff+1, 0);
for (int ii = 0; ii<=cutoff; ii++) {
intsqrt[ii] = std::sqrt((static_cast<double>(ii)));
}
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
H[nextCoordinate] = H[fromCoordinate] * y[k];
std::vector<int> tmpjump(dim, 0);
for (int ii = 0; ii < dim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - intsqrt[jumpFrom[ii]-1]*(R[k*dim+ii])*H[prevCoordinate];
}
}
H[nextCoordinate] = H[nextCoordinate]/intsqrt[nextPos[k]-1];
}
return H;
}
/**
* Returns the matrix elements of an interferometer parametrized in terms of its R matrix
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* interferometer_cpp(const std::vector<T> &R, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
assert(dim % 2 == 0);
int num_modes = dim/2;
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<double> intsqrt(cutoff+1, 0);
for (int ii = 0; ii<=cutoff; ii++) {
intsqrt[ii] = std::sqrt((static_cast<double>(ii)));
}
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
int bran = 0;
for (int ii=0; ii < num_modes; ii++) {
bran += nextPos[ii];
}
int ketn = 0;
for (int ii=num_modes; ii < dim; ii++) {
ketn += nextPos[ii];
}
if (bran == ketn) {
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
std::vector<int> tmpjump(dim, 0);
int low_lim;
int high_lim;
if (k > num_modes) {
low_lim = 0;
high_lim = num_modes;
}
else {
low_lim = num_modes;
high_lim = dim;
}
for (int ii = low_lim; ii < high_lim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - (intsqrt[jumpFrom[ii]-1])*(R[k*dim+ii])*H[prevCoordinate];
}
}
H[nextCoordinate] = H[nextCoordinate] /intsqrt[nextPos[k]-1];
}
}
return H;
}
}
| 8,476 | 2,956 |
class Solution {
public:
int nextGreaterElement(int n) {
auto digits = to_string(n);
next_permutation(digits.begin(), digits.end());
auto x = stoll(digits);
return (x > INT_MAX || x <= n) ? -1 : x;
}
}; | 242 | 83 |
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
TEST(ProbWelfordCovarEstimator, restart) {
const int n = 10;
Eigen::VectorXd q = Eigen::VectorXd::Ones(n);
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i)
estimator.add_sample(q);
estimator.restart();
EXPECT_EQ(0, estimator.num_samples());
Eigen::VectorXd mean(n);
estimator.sample_mean(mean);
for (int i = 0; i < n; ++i)
EXPECT_EQ(0, mean(i));
}
TEST(ProbWelfordCovarEstimator, num_samples) {
const int n = 10;
Eigen::VectorXd q = Eigen::VectorXd::Ones(n);
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i)
estimator.add_sample(q);
EXPECT_EQ(n_learn, estimator.num_samples());
}
TEST(ProbWelfordCovarEstimator, sample_mean) {
const int n = 10;
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i) {
Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i);
estimator.add_sample(q);
}
Eigen::VectorXd mean(n);
estimator.sample_mean(mean);
for (int i = 0; i < n; ++i)
EXPECT_EQ(9.0 / 2.0, mean(i));
}
TEST(ProbWelfordCovarEstimator, sample_covariance) {
const int n = 10;
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i) {
Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i);
estimator.add_sample(q);
}
Eigen::MatrixXd covar(n, n);
estimator.sample_covariance(covar);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
EXPECT_EQ(55.0 / 6.0, covar(i, j));
}
| 1,738 | 812 |
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <gst/gst.h>
#include <glib.h>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <sstream>
#include "gstnvdsmeta.h"
#include "nvds_analytics_meta.h"
/* parse_nvdsanalytics_meta_data
* and extract nvanalytics metadata etc. */
extern "C" void
parse_nvdsanalytics_meta_data (NvDsBatchMeta *batch_meta)
{
NvDsObjectMeta *obj_meta = NULL;
NvDsMetaList * l_frame = NULL;
NvDsMetaList * l_obj = NULL;
//NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);
for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
l_frame = l_frame->next) {
NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);
std::stringstream out_string;
/* Iterate user metadata in frames to search analytics metadata */
for (NvDsMetaList * l_user = frame_meta->frame_user_meta_list;
l_user != NULL; l_user = l_user->next) {
NvDsUserMeta *user_meta = (NvDsUserMeta *) l_user->data;
if (user_meta->base_meta.meta_type != NVDS_USER_FRAME_META_NVDSANALYTICS)
continue;
/* convert to metadata */
NvDsAnalyticsFrameMeta *meta =
(NvDsAnalyticsFrameMeta *) user_meta->user_meta_data;
/* Get the labels from nvdsanalytics config file */
for (std::pair<std::string, uint32_t> status : meta->objInROIcnt){
out_string << " Objs in ROI ";
out_string << status.first;
out_string << " = ";
out_string << status.second;
}
for (std::pair<std::string, uint32_t> status : meta->objLCCumCnt){
out_string << " LineCrossing Cumulative ";
out_string << status.first;
out_string << " = ";
out_string << status.second;
}
for (std::pair<std::string, uint32_t> status : meta->objLCCurrCnt){
out_string << " LineCrossing Current Frame ";
out_string << status.first;
out_string << " = ";
out_string << status.second;
}
for (std::pair<std::string, bool> status : meta->ocStatus){
out_string << " Overcrowding status ";
out_string << status.first;
out_string << " = ";
out_string << status.second;
}
}
for (l_obj = frame_meta->obj_meta_list; l_obj != NULL;
l_obj = l_obj->next) {
obj_meta = (NvDsObjectMeta *) (l_obj->data);
// Access attached user meta for each object
for (NvDsMetaList *l_user_meta = obj_meta->obj_user_meta_list; l_user_meta != NULL;
l_user_meta = l_user_meta->next) {
NvDsUserMeta *user_meta = (NvDsUserMeta *) (l_user_meta->data);
if(user_meta->base_meta.meta_type == NVDS_USER_OBJ_META_NVDSANALYTICS)
{
NvDsAnalyticsObjInfo * user_meta_data =
(NvDsAnalyticsObjInfo *)user_meta->user_meta_data;
if (user_meta_data->dirStatus.length()){
out_string << " object " << obj_meta->object_id <<
" is moving in " << user_meta_data->dirStatus;
}
}
}
}
if (out_string.str().size()){
g_print ("Frame Number = %d of Stream = %d, %s\n",
frame_meta->frame_num, frame_meta->pad_index,
out_string.str().c_str());
}
}
}
| 4,779 | 1,530 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Reliability;
using namespace Reliability::ReconfigurationAgentComponent;
using namespace ReliabilityUnitTest;
using namespace Infrastructure;
using namespace Common;
using namespace std;
class TestLocalFailoverUnitMap
{
protected:
TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestSetup()); }
TEST_METHOD_SETUP(TestSetup);
~TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestCleanup()); }
TEST_METHOD_CLEANUP(TestCleanup);
struct AddEntriesResult
{
LocalFailoverUnitMapEntrySPtr FMEntry;
LocalFailoverUnitMapEntrySPtr OtherFTEntry;
vector<EntityEntryBase*> CreateExpectation(bool fmEntry, bool otherEntry) const
{
vector<EntityEntryBase*> rv;
if (fmEntry)
{
rv.push_back(FMEntry.get());
}
if (otherEntry)
{
rv.push_back(OtherFTEntry.get());
}
return rv;
}
};
class EntryState
{
public:
enum Enum
{
NotExisting = 0,
NullFT = 1,
HasFTInitial = 2,
HasFTUpdated = 3,
Deleted = 4,
};
};
class PersistenceResult
{
public:
enum Enum
{
Success,
Failure
};
};
AddEntriesResult AddEntries(bool addFMEntry, bool addOtherEntry);
void ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult);
void ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult);
LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag);
LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag, std::wstring const & ftShortName);
InMemoryLocalStore & GetStore();
static FailoverUnitId GetFTId();
static FailoverUnitId GetFTId(std::wstring const & ftShortName);
static wstring GetFTShortName();
UnitTestContextUPtr utContext_;
};
bool TestLocalFailoverUnitMap::TestSetup()
{
utContext_ = UnitTestContext::Create(UnitTestContext::Option::None);
return true;
}
bool TestLocalFailoverUnitMap::TestCleanup()
{
return utContext_->Cleanup();
}
TestLocalFailoverUnitMap::AddEntriesResult TestLocalFailoverUnitMap::AddEntries(bool addFMEntry, bool addOtherEntry)
{
AddEntriesResult result;
if (addFMEntry)
{
result.FMEntry = GetOrCreate(true, L"FM");
}
if (addOtherEntry)
{
result.OtherFTEntry = GetOrCreate(true, L"SP1");
}
return result;
}
template<typename T>
vector<T*> ConvertVectorOfSharedPtrToVectorOfPtr(vector<std::shared_ptr<T>> const & result)
{
vector<T*> rv;
for (auto const & it : result)
{
rv.push_back(it.get());
}
return rv;
}
void TestLocalFailoverUnitMap::ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult)
{
auto expectedEntities = addEntryResult.CreateExpectation(fmExpected, otherExpected);
auto entryResultSPtr = utContext_->LFUM.GetAllFailoverUnitEntries(excludeFM);
// Do this to not define write to text writer for entity entry
auto entryResult = ConvertVectorOfSharedPtrToVectorOfPtr(entryResultSPtr);
Verify::Vector<EntityEntryBase*>(entryResult, entryResult);
}
void TestLocalFailoverUnitMap::ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult)
{
vector<EntityEntryBase*> expectedEntities = addEntryResult.CreateExpectation(expected, false);
auto result = utContext_->LFUM.GetFMFailoverUnitEntries();
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(result);
Verify::Vector(casted, expectedEntities);
}
FailoverUnitId TestLocalFailoverUnitMap::GetFTId()
{
return GetFTId(GetFTShortName());
}
FailoverUnitId TestLocalFailoverUnitMap::GetFTId(std::wstring const & shortName)
{
return StateManagement::Default::GetInstance().LookupFTContext(shortName).FUID;
}
wstring TestLocalFailoverUnitMap::GetFTShortName()
{
return L"SP1";
}
LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag)
{
return GetOrCreate(createFlag, GetFTShortName());
}
LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag, std::wstring const & ftShortName)
{
return dynamic_pointer_cast<LocalFailoverUnitMapEntry>(utContext_->LFUM.GetOrCreateEntityMapEntry(GetFTId(ftShortName), createFlag));
}
BOOST_AUTO_TEST_SUITE(Unit)
BOOST_FIXTURE_TEST_SUITE(TestLocalFailoverUnitMapSuite,TestLocalFailoverUnitMap)
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyFMEntries)
{
auto addResult = AddEntries(true, false);
ExecuteGetAllAndVerifyResult(true, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_NoEntries)
{
auto addResult = AddEntries(false, false);
ExecuteGetAllAndVerifyResult(true, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_BothEntries)
{
auto addResult = AddEntries(true, true);
ExecuteGetAllAndVerifyResult(true, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyNonFMEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetAllAndVerifyResult(true, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyFMEntries)
{
auto addResult = AddEntries(true, false);
ExecuteGetAllAndVerifyResult(false, true, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_NoEntries)
{
auto addResult = AddEntries(false, false);
ExecuteGetAllAndVerifyResult(false, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_BothEntries)
{
auto addResult = AddEntries(true, true);
ExecuteGetAllAndVerifyResult(false, true, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyNonFMEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetAllAndVerifyResult(false, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyFM)
{
auto addResult = AddEntries(true, false);
ExecuteGetFMEntriesAndVerifyResult(true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_Both)
{
auto addResult = AddEntries(true, true);
ExecuteGetFMEntriesAndVerifyResult(true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_None)
{
auto addResult = AddEntries(false, false);
ExecuteGetFMEntriesAndVerifyResult(false, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyOtherEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetFMEntriesAndVerifyResult(false, addResult);
}
BOOST_AUTO_TEST_CASE(GetByOwner_Fmm)
{
auto addResult = AddEntries(true, true);
auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fmm);
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries);
auto expected = addResult.CreateExpectation(true, false);
Verify::Vector(expected, casted);
}
BOOST_AUTO_TEST_CASE(GetByOwner_Fm)
{
auto addResult = AddEntries(true, true);
auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fm);
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries);
auto expected = addResult.CreateExpectation(false, true);
Verify::Vector(expected, casted);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 7,708 | 2,536 |
#include <walletaddrman.h>
#include <hash.h>
#include <logging.h>
#include <serialize.h>
#include <addrdb.h>
#include <string>
CWalletAddrMan::CWalletAddrMan()
{
}
bool CWalletAddrMan::Find(const std::string& walletAddress, const std::string& check_command)
{
if (CWalletAddrMan::walletAddressList.find(walletAddress) != std::string::npos)
return true;
else return false;
}
bool CWalletAddrMan::FindBlockedWallet(const std::string& walletAddress)
{
return CWalletAddrMan::Find(walletAddress, "isBlockedAddress");
}
bool CWalletAddrMan::FindTrustMiner(const std::string& walletAddress)
{
return CWalletAddrMan::Find(walletAddress, "isTrustMiner");
}
| 671 | 259 |
#include <iostream>
#include <fstream>
using namespace std;
int main(){
/***** ESTADO DEl ARCHIVO *****/
/**
bad() -> Cuando no tenemos permiso. Cuando no hay espacio. Cuando no existe el archivo
fail() -> Error de formato (tratas de leer int y solo encuentras un char).
eof() -> Fin de archivo End Of File
good() ->
**/
ifstream entrada;
char linea[80];
entrada.open("archivo.txt");
if(entrada.good()){
cout<<"Archivo en buen estado"<<endl;
}
else{
cout<<"Archivo en mal estado"<<endl;
}
return 0;
}
| 620 | 211 |
#include "addmagnetlinkdialog.hpp"
#include <regex>
#include <boost/log/trivial.hpp>
#include <libtorrent/magnet_uri.hpp>
#include <wx/clipbrd.h>
#include <wx/tokenzr.h>
#include "../translator.hpp"
namespace lt = libtorrent;
using pt::UI::Dialogs::AddMagnetLinkDialog;
AddMagnetLinkDialog::AddMagnetLinkDialog(wxWindow* parent, wxWindowID id)
: wxDialog(parent, id, i18n("add_magnet_link_s"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER),
m_links(new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxTE_MULTILINE))
{
auto buttonsSizer = new wxBoxSizer(wxHORIZONTAL);
wxButton* ok = new wxButton(this, wxID_OK);
ok->SetDefault();
buttonsSizer->Add(ok);
buttonsSizer->Add(new wxButton(this, wxID_CANCEL, i18n("cancel")), 0, wxLEFT, FromDIP(7));
auto mainSizer = new wxBoxSizer(wxVERTICAL);
mainSizer->AddSpacer(FromDIP(11));
mainSizer->Add(new wxStaticText(this, wxID_ANY, i18n("add_magnet_link_s_description")), 0, wxLEFT | wxRIGHT, FromDIP(11));
mainSizer->AddSpacer(FromDIP(5));
mainSizer->Add(m_links, 1, wxLEFT | wxRIGHT | wxEXPAND, FromDIP(11));
mainSizer->AddSpacer(FromDIP(7));
mainSizer->Add(buttonsSizer, 0, wxLEFT | wxRIGHT | wxBOTTOM | wxALIGN_RIGHT, FromDIP(11));
this->SetSizerAndFit(mainSizer);
this->SetSize(FromDIP(wxSize(400, 250)));
m_links->SetFocus();
m_links->SetFont(
wxFont(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Consolas")));
if (auto clipboard = wxClipboard::Get())
{
if (clipboard->Open())
{
wxTextDataObject data;
if (clipboard->GetData(data))
{
wxString d = data.GetText();
if (IsMagnetLinkOrInfoHash(d))
{
if (!d.EndsWith("\n"))
{
d = d + "\n";
}
m_links->SetValue(d);
m_links->SetInsertionPointEnd();
}
}
clipboard->Close();
}
}
}
AddMagnetLinkDialog::~AddMagnetLinkDialog()
{
}
std::vector<libtorrent::add_torrent_params> AddMagnetLinkDialog::GetParams()
{
std::vector<lt::add_torrent_params> result;
wxStringTokenizer tokenizer(m_links->GetValue());
while (tokenizer.HasMoreTokens())
{
std::string token = tokenizer.GetNextToken();
if (!IsMagnetLinkOrInfoHash(token)) { continue; }
switch (token.size())
{
case 40:
if (token.substr(0, 20) != "magnet:?xt=urn:btih:")
{
BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v1 info hash: " << token;
token = "magnet:?xt=urn:btih:" + token;
}
break;
case 68:
if (token.substr(0, 20) != "magnet:?xt=urn:btmh:")
{
BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v2 info hash: " << token;
token = "magnet:?xt=urn:btmh:" + token;
}
break;
}
lt::error_code ec;
lt::add_torrent_params params = lt::parse_magnet_uri(token, ec);
if (ec)
{
BOOST_LOG_TRIVIAL(warning) << "Failed to parse magnet uri: " << token << ", error: " << ec;
continue;
}
result.push_back(params);
}
return result;
}
bool AddMagnetLinkDialog::IsMagnetLinkOrInfoHash(wxString const& str)
{
std::regex infoHashV1("[a-fA-F\\d]{40}", std::regex_constants::icase);
std::regex infoHashV2("[a-fA-F\\d]{68}", std::regex_constants::icase);
if (std::regex_match(str.ToStdString(), infoHashV1)
|| std::regex_match(str.ToStdString(), infoHashV2))
{
return true;
}
if (str.StartsWith("magnet:?xt=urn:btih:")
|| str.StartsWith("magnet:?xt=urn:btmh:"))
{
return true;
}
return false;
}
| 4,000 | 1,470 |
#ifndef ARRAYS_MACRO_H
#define ARRAYS_MACRO_H
#define M_INLINE inline
#endif
| 80 | 41 |
#include "headers/mainwindow.h"
#include "headers/qtexedit.h"
#include <QString>
#include <QFile>
QStringList AWL;
void setupAWL(){
if(AWL.isEmpty()){
QFile file (":/AWL/awl.txt");
file.open(QIODevice::ReadOnly);
QString word = QString::fromUtf8(file.readLine());
while((!word.isEmpty())&& word !=" "){
if(word.contains("\n")){
word.replace("\n","");
}
AWL.append(word);
word = QString::fromUtf8(file.readLine());
}
file.close();
}
}
| 557 | 192 |
#include "Engine/ImageBasedLightingTechnique.hpp"
#include "Engine/Engine.hpp"
#include "Engine/DefaultResourceSlots.hpp"
#include "Core/Executor.hpp"
#include "Core/Profiling.hpp"
DeferredImageBasedLightingTechnique::DeferredImageBasedLightingTechnique(RenderEngine* eng, RenderGraph& graph) :
Technique("GlobalIBL", eng->getDevice()),
mPipelineDesc{Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(),
getDevice()->getSwapChain()->getSwapChainImageHeight()},
Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(),
getDevice()->getSwapChain()->getSwapChainImageHeight()} },
mIBLVertexShader(eng->getShader("./Shaders/FullScreenTriangle.vert")),
mIBLFragmentShader(eng->getShader("./Shaders/DeferredDFGIBL.frag"))
{
GraphicsTask task{ "GlobalIBL", mPipelineDesc };
task.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
task.addInput(kDFGLUT, AttachmentType::Texture2D);
task.addInput(kGBufferDepth, AttachmentType::Texture2D);
task.addInput(kGBufferNormals, AttachmentType::Texture2D);
task.addInput(kGBufferDiffuse, AttachmentType::Texture2D);
task.addInput(kGBufferSpecularRoughness, AttachmentType::Texture2D);
task.addInput(kGBufferEmissiveOcclusion, AttachmentType::Texture2D);
task.addInput(kConvolvedSpecularSkyBox, AttachmentType::CubeMap);
task.addInput(kConvolvedDiffuseSkyBox, AttachmentType::CubeMap);
task.addInput(kDefaultSampler, AttachmentType::Sampler);
if (eng->isPassRegistered(PassType::Shadow) || eng->isPassRegistered(PassType::CascadingShadow) || eng->isPassRegistered(PassType::RayTracedShadows))
task.addInput(kShadowMap, AttachmentType::Texture2D);
if(eng->isPassRegistered(PassType::SSR) || eng->isPassRegistered(PassType::RayTracedReflections))
task.addInput(kReflectionMap, AttachmentType::Texture2D);
task.addManagedOutput(kGlobalLighting, AttachmentType::RenderTarget2D, Format::RGBA16Float,
SizeClass::Swapchain, LoadOp::Clear_Black, StoreOp::Store, ImageUsage::ColourAttachment | ImageUsage::Sampled | ImageUsage::TransferSrc);
task.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("Defered IBL");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("Defered IBL");
const RenderTask& task = graph.getTask(taskIndex);
exec->setGraphicsShaders(static_cast<const GraphicsTask&>(task), graph, mIBLVertexShader, nullptr, nullptr, nullptr, mIBLFragmentShader);
exec->draw(0, 3);
}
);
mTaskID = graph.addTask(task);
}
| 2,742 | 899 |
#include "AnimationUtility.h"
#include <limits>
namespace AnimationUtility
{
const AnimationKeyTime Invalid_Time = std::numeric_limits<AnimationKeyTime>::lowest();
template <typename T>
T defaultInterpolateFunc(const AnimationKey<T> &a, const AnimationKey<T> &b, const AnimationKeyTime &targetTime)
{
if (targetTime <= a.time || a.time > b.time)
{
return a.value;
}
if (targetTime >= b.time)
{
return b.value;
}
return T(a.value + double(targetTime - a.time) / double(b.time - a.time) * (b.value - a.value));
}
float interpolateFuncFloat(const AnimationKey<float> &a, const AnimationKey<float> &b, const AnimationKeyTime &targetTime)
{
return defaultInterpolateFunc<float>(a, b, targetTime);
}
double interpolateFuncDouble(const AnimationKey<double> &a, const AnimationKey<double> &b, const AnimationKeyTime &targetTime)
{
return defaultInterpolateFunc<double>(a, b, targetTime);
}
} | 922 | 335 |
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "importmanager.h"
#include <util/sll/qtutil.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ipluginsmanager.h>
#include "interfaces/azoth/iaccount.h"
#include "interfaces/azoth/isupportimport.h"
#include "interfaces/azoth/ihistoryplugin.h"
#include "core.h"
#include "accounthandlerchooserdialog.h"
namespace LC
{
namespace Azoth
{
ImportManager::ImportManager (QObject *parent)
: QObject (parent)
{
}
void ImportManager::HandleAccountImport (Entity e)
{
const auto& map = e.Additional_ ["AccountData"].toMap ();
const auto& protoId = map ["Protocol"].toString ();
if (protoId.isEmpty ())
{
qWarning () << Q_FUNC_INFO
<< "empty protocol id"
<< map;
return;
}
for (const auto proto : Core::Instance ().GetProtocols ())
{
const auto isi = qobject_cast<ISupportImport*> (proto->GetQObject ());
if (!isi || isi->GetImportProtocolID () != protoId)
continue;
isi->ImportAccount (map);
break;
}
}
namespace
{
IMessage::Direction GetDirection (const QByteArray& dirStr)
{
if (dirStr == "out")
return IMessage::Direction::Out;
else if (dirStr == "in")
return IMessage::Direction::In;
qWarning () << Q_FUNC_INFO
<< "unknown direction"
<< dirStr;
return IMessage::Direction::In;
}
IMessage::Type GetMessageType (const QByteArray& typeStr)
{
if (typeStr == "chat")
return IMessage::Type::ChatMessage;
else if (typeStr == "muc")
return IMessage::Type::MUCMessage;
else if (typeStr == "event")
return IMessage::Type::EventMessage;
qWarning () << Q_FUNC_INFO
<< "unknown type"
<< typeStr;
return IMessage::Type::ChatMessage;
}
IMessage::EscapePolicy GetEscapePolicy (const QByteArray& polStr)
{
if (polStr.isEmpty ())
return IMessage::EscapePolicy::Escape;
else if (polStr == "escape")
return IMessage::EscapePolicy::Escape;
else if (polStr == "noEscape")
return IMessage::EscapePolicy::NoEscape;
qWarning () << Q_FUNC_INFO
<< "unknown escape policy"
<< polStr;
return IMessage::EscapePolicy::Escape;
}
}
void ImportManager::HandleHistoryImport (Entity e)
{
qDebug () << Q_FUNC_INFO;
const auto& histories = Core::Instance ().GetProxy ()->
GetPluginsManager ()->GetAllCastableTo<IHistoryPlugin*> ();
if (histories.isEmpty ())
{
qWarning () << Q_FUNC_INFO
<< "no history plugin is present, aborting";
return;
}
const auto acc = GetAccountID (e);
if (!acc)
return;
const auto isi = qobject_cast<ISupportImport*> (acc->GetParentProtocol ());
QHash<QString, QString> entryIDcache;
QVariantList history;
for (const auto& qe : EntityQueues_.take (e.Additional_ ["AccountID"].toString ()))
history.append (qe.Additional_ ["History"].toList ());
qDebug () << history.size ();
struct EntryInfo
{
QString VisibleName_;
QList<HistoryItem> Items_;
};
QHash<QString, QHash<QString, EntryInfo>> items;
for (const auto& lineVar : history)
{
const auto& histMap = lineVar.toMap ();
const auto& origId = histMap ["EntryID"].toString ();
QString entryId;
if (entryIDcache.contains (origId))
entryId = entryIDcache [origId];
else
{
const auto& realId = isi->GetEntryID (origId, acc->GetQObject ());
entryIDcache [origId] = realId;
entryId = realId;
}
auto visibleName = histMap ["VisibleName"].toString ();
if (visibleName.isEmpty ())
visibleName = origId;
const auto& accId = acc->GetAccountID ();
const HistoryItem item
{
histMap ["DateTime"].toDateTime (),
GetDirection (histMap ["Direction"].toByteArray ()),
histMap ["Body"].toString (),
histMap ["OtherVariant"].toString (),
GetMessageType (histMap ["Type"].toByteArray ()),
histMap ["RichBody"].toString (),
GetEscapePolicy (histMap ["EscapePolicy"].toByteArray ())
};
auto& info = items [accId] [entryId];
info.VisibleName_ = visibleName;
info.Items_ << item;
}
for (const auto& accPair : Util::Stlize (items))
for (const auto& entryPair : Util::Stlize (accPair.second))
{
const auto& info = entryPair.second;
for (const auto plugin : histories)
plugin->AddRawMessages (accPair.first,
entryPair.first, info.VisibleName_, info.Items_);
}
}
IAccount* ImportManager::GetAccountID (Entity e)
{
const auto& accName = e.Additional_ ["AccountName"].toString ();
const auto& accs = Core::Instance ().GetAccounts ([] (IProtocol *proto)
{ return qobject_cast<ISupportImport*> (proto->GetQObject ()); });
const auto pos = std::find_if (accs.begin (), accs.end (),
[&accName] (IAccount *acc) { return acc->GetAccountName () == accName; });
if (pos != accs.end ())
return *pos;
const auto& impId = e.Additional_ ["AccountID"].toString ();
EntityQueues_ [impId] << e;
if (EntityQueues_ [impId].size () > 1)
return nullptr;
if (AccID2OurID_.contains (impId))
return AccID2OurID_ [impId];
AccountHandlerChooserDialog dia (accs,
tr ("Select account to import history from %1 into:").arg (accName));
if (dia.exec () != QDialog::Accepted)
return 0;
const auto acc = dia.GetSelectedAccount ();
AccID2OurID_ [impId] = acc;
return acc;
}
}
}
| 5,636 | 2,192 |
/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/blas-like/level1/DiagonalScale.hpp"
#include "elemental/blas-like/level1/Scale.hpp"
#include "elemental/blas-like/level3/Gemm.hpp"
#include "elemental/blas-like/level3/Herk.hpp"
#include "elemental/lapack-like/SkewHermitianEig.hpp"
#include "elemental/lapack-like/Norm/Frobenius.hpp"
#include "elemental/lapack-like/HermitianEig/Sort.hpp"
#include "elemental/matrices/Identity.hpp"
using namespace std;
using namespace elem;
// Typedef our real and complex types to 'R' and 'C' for convenience
typedef double R;
typedef Complex<R> C;
int
main( int argc, char* argv[] )
{
// This detects whether or not you have already initialized MPI and
// does so if necessary. The full routine is elem::Initialize.
Initialize( argc, argv );
// Extract our MPI rank
mpi::Comm comm = mpi::COMM_WORLD;
const int commRank = mpi::CommRank( comm );
// Surround the Elemental calls with try/catch statements in order to
// safely handle any exceptions that were thrown during execution.
try
{
const int n = Input("--size","size of matrix",100);
const bool print = Input("--print","print matrices?",false);
ProcessInput();
PrintInputReport();
// Create a 2d process grid from a communicator. In our case, it is
// MPI_COMM_WORLD. There is another constructor that allows you to
// specify the grid dimensions, Grid g( comm, r, c ), which creates an
// r x c grid.
Grid g( comm );
// Create an n x n complex distributed matrix,
// We distribute the matrix using grid 'g'.
//
// There are quite a few available constructors, including ones that
// allow you to pass in your own local buffer and to specify the
// distribution alignments (i.e., which process row and column owns the
// top-left element)
DistMatrix<C> S( n, n, g );
// Fill the matrix since we did not pass in a buffer.
//
// We will fill entry (i,j) with the complex value (i-j,i+j) so that
// the global matrix is skew-Hermitian. However, only one triangle of
// the matrix actually needs to be filled, the symmetry can be implicit.
//
const int colShift = S.ColShift(); // first row we own
const int rowShift = S.RowShift(); // first col we own
const int colStride = S.ColStride();
const int rowStride = S.RowStride();
const int localHeight = S.LocalHeight();
const int localWidth = S.LocalWidth();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
for( int iLocal=0; iLocal<localHeight; ++iLocal )
{
// Our process owns the rows colShift:colStride:n,
// and the columns rowShift:rowStride:n
const int i = colShift + iLocal*colStride;
const int j = rowShift + jLocal*rowStride;
S.SetLocal( iLocal, jLocal, C(i-j,i+j) );
}
}
// Make a backup of S before we overwrite it within the eigensolver
DistMatrix<C> SCopy( S );
// Call the eigensolver. We first create an empty complex eigenvector
// matrix, X[MC,MR], and an eigenvalue column vector, w[VR,* ]
//
// Optional: set blocksizes and algorithmic choices here. See the
// 'Tuning' section of the README for details.
DistMatrix<R,VR,STAR> wImag( g );
DistMatrix<C> X( g );
SkewHermitianEig( LOWER, S, wImag, X ); // only use lower half of S
// Optional: sort the eigenpairs
hermitian_eig::Sort( wImag, X );
if( print )
{
SCopy.Print("S");
X.Print("X");
wImag.Print("wImag");
}
// Check the residual, || S X - Omega X ||_F
const R frobS = HermitianFrobeniusNorm( LOWER, SCopy );
DistMatrix<C> E( X );
Scale( C(0,1), E );
DiagonalScale( RIGHT, NORMAL, wImag, E );
Gemm( NORMAL, NORMAL, C(-1), SCopy, X, C(1), E );
const R frobResid = FrobeniusNorm( E );
// Check the orthogonality of X
Identity( E, n, n );
Herk( LOWER, NORMAL, C(-1), X, C(1), E );
const R frobOrthog = HermitianFrobeniusNorm( LOWER, E );
if( g.Rank() == 0 )
{
std::cout << "|| H ||_F = " << frobS << "\n"
<< "|| H X - X Omega ||_F / || A ||_F = "
<< frobResid / frobS << "\n"
<< "|| X X^H - I ||_F = " << frobOrthog / frobS
<< "\n" << std::endl;
}
}
catch( ArgException& e )
{
// There is nothing to do
}
catch( exception& e )
{
ostringstream os;
os << "Process " << commRank << " caught exception with message: "
<< e.what() << endl;
cerr << os.str();
#ifndef RELEASE
DumpCallStack();
#endif
}
Finalize();
return 0;
}
| 5,382 | 1,727 |
/*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GAZEBO_PLUGINS_SONARPLUGIN_HH_
#define GAZEBO_PLUGINS_SONARPLUGIN_HH_
#include "gazebo/common/Plugin.hh"
#include "gazebo/sensors/SensorTypes.hh"
#include "gazebo/sensors/SonarSensor.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
/// \brief A sonar sensor plugin
class GZ_PLUGIN_VISIBLE SonarPlugin : public SensorPlugin
{
/// \brief Constructor
public: SonarPlugin();
/// \brief Destructor
public: virtual ~SonarPlugin();
/// \brief Load the plugin
/// \param[in] _parent Pointer to the parent sensor.
/// \param[in] _sdf SDF element for the plugin.
public: void Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf);
/// \brief Update callback. Overload this function in a child class.
/// \param[in] _msg The sonar ping message.
protected: virtual void OnUpdate(msgs::SonarStamped _msg);
/// \brief The parent sensor
protected: sensors::SonarSensorPtr parentSensor;
/// \brief The connection tied to SonarSensor's update event
private: event::ConnectionPtr connection;
};
}
#endif
| 1,699 | 564 |
#include "orm/query/grammars/grammar.hpp"
#include "orm/databaseconnection.hpp"
#include "orm/macros/likely.hpp"
#include "orm/query/joinclause.hpp"
TINYORM_BEGIN_COMMON_NAMESPACE
namespace Orm::Query::Grammars
{
QString Grammar::compileSelect(QueryBuilder &query) const
{
/* If the query does not have any columns set, we'll set the columns to the
* character to just get all of the columns from the database. Then we
can build the query and concatenate all the pieces together as one. */
const auto original = query.getColumns();
if (original.isEmpty())
query.setColumns({ASTERISK});
/* To compile the query, we'll spin through each component of the query and
see if that component exists. If it does we'll just call the compiler
function for the component which is responsible for making the SQL. */
auto sql = concatenate(compileComponents(query));
// Restore original columns value
query.setColumns(original);
return sql;
}
QString Grammar::compileInsert(const QueryBuilder &query,
const QVector<QVariantMap> &values) const
{
const auto table = wrapTable(query.getFrom());
// FEATURE insert with empty values, this code will never be triggered, because check in the QueryBuilder::insert, even all other code works correctly and support empty values silverqx
if (values.isEmpty())
return QStringLiteral("insert into %1 default values").arg(table);
return QStringLiteral("insert into %1 (%2) values %3").arg(
table,
// Columns are obtained only from a first QMap
columnize(values.at(0).keys()),
compileInsertToVector(values).join(COMMA));
}
QString Grammar::compileInsertOrIgnore(const QueryBuilder &/*unused*/,
const QVector<QVariantMap> &/*unused*/) const
{
throw Exceptions::RuntimeError(
"This database engine does not support inserting while ignoring "
"errors.");
}
QString Grammar::compileUpdate(QueryBuilder &query,
const QVector<UpdateItem> &values) const
{
const auto table = wrapTable(query.getFrom());
const auto columns = compileUpdateColumns(values);
const auto wheres = compileWheres(query);
return query.getJoins().isEmpty()
? compileUpdateWithoutJoins(query, table, columns, wheres)
: compileUpdateWithJoins(query, table, columns, wheres);
}
QVector<QVariant>
Grammar::prepareBindingsForUpdate(const BindingsMap &bindings,
const QVector<UpdateItem> &values) const
{
QVector<QVariant> preparedBindings(bindings.find(BindingType::JOIN).value());
// Merge update values bindings
std::transform(values.cbegin(), values.cend(), std::back_inserter(preparedBindings),
[](const auto &updateItem)
{
return updateItem.value;
});
/* Flatten bindings map and exclude select and join bindings and than merge
all remaining bindings from flatten bindings map. */
const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT,
BindingType::JOIN});
// std::copy() is ok, 'flatten' contains vector of references
std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings));
return preparedBindings;
}
QString Grammar::compileDelete(QueryBuilder &query) const
{
const auto table = wrapTable(query.getFrom());
const auto wheres = compileWheres(query);
return query.getJoins().isEmpty() ? compileDeleteWithoutJoins(query, table, wheres)
: compileDeleteWithJoins(query, table, wheres);
}
QVector<QVariant> Grammar::prepareBindingsForDelete(const BindingsMap &bindings) const
{
QVector<QVariant> preparedBindings;
/* Flatten bindings map and exclude select bindings and than merge all remaining
bindings from flatten bindings map. */
const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT});
// std::copy() is ok, 'flatten' contains vector of references
std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings));
return preparedBindings;
}
std::unordered_map<QString, QVector<QVariant>>
Grammar::compileTruncate(const QueryBuilder &query) const
{
return {{QStringLiteral("truncate table %1").arg(wrapTable(query.getFrom())), {}}};
}
const QVector<QString> &Grammar::getOperators() const
{
/* I make it this way, I don't declare it as pure virtual intentionally, this gives
me oportunity to instantiate the Grammar class eg. in tests. */
static const QVector<QString> cachedOperators;
return cachedOperators;
}
bool Grammar::shouldCompileAggregate(const std::optional<AggregateItem> &aggregate) const
{
return aggregate.has_value() && !aggregate->function.isEmpty();
}
bool Grammar::shouldCompileColumns(const QueryBuilder &query) const
{
/* If the query is actually performing an aggregating select, we will let
compileAggregate() to handle the building of the select clauses, as it will need
some more syntax that is best handled by that function to keep things neat. */
return !query.getAggregate() && !query.getColumns().isEmpty();
}
bool Grammar::shouldCompileFrom(const FromClause &from) const
{
return !std::holds_alternative<std::monostate>(from) ||
(std::holds_alternative<QString>(from) &&
!std::get<QString>(from).isEmpty());
}
QStringList Grammar::compileComponents(const QueryBuilder &query) const
{
QStringList sql;
const auto &compileMap = getCompileMap();
for (const auto &component : compileMap)
if (component.isset)
if (component.isset(query))
sql.append(std::invoke(component.compileMethod, query));
return sql;
}
QString Grammar::compileAggregate(const QueryBuilder &query) const
{
const auto &aggregate = query.getAggregate();
const auto &distinct = query.getDistinct();
auto column = columnize(aggregate->columns);
/* If the query has a "distinct" constraint and we're not asking for all columns
we need to prepend "distinct" onto the column name so that the query takes
it into account when it performs the aggregating operations on the data. */
if (std::holds_alternative<bool>(distinct) && query.getDistinct<bool>() &&
column != ASTERISK
) T_LIKELY
column = QStringLiteral("distinct %1").arg(column);
else if (std::holds_alternative<QStringList>(distinct)) T_UNLIKELY
column = QStringLiteral("distinct %1")
.arg(columnize(std::get<QStringList>(distinct)));
return QStringLiteral("select %1(%2) as %3").arg(aggregate->function, column,
wrap(QStringLiteral("aggregate")));
}
QString Grammar::compileColumns(const QueryBuilder &query) const
{
QString select;
const auto &distinct = query.getDistinct();
if (!std::holds_alternative<bool>(distinct))
throw Exceptions::RuntimeError(
QStringLiteral("Connection '%1' doesn't support defining more distinct "
"columns.")
.arg(query.getConnection().getName()));
if (std::get<bool>(distinct))
select = QStringLiteral("select distinct %1");
else
select = QStringLiteral("select %1");
return select.arg(columnize(query.getColumns()));
}
QString Grammar::compileFrom(const QueryBuilder &query) const
{
return QStringLiteral("from %1").arg(wrapTable(query.getFrom()));
}
QString Grammar::compileWheres(const QueryBuilder &query) const
{
const auto sql = compileWheresToVector(query);
if (!sql.isEmpty())
return concatenateWhereClauses(query, sql);
return {};
}
QStringList Grammar::compileWheresToVector(const QueryBuilder &query) const
{
const auto &wheres = query.getWheres();
QStringList compiledWheres;
compiledWheres.reserve(wheres.size());
for (const auto &where : wheres)
compiledWheres << QStringLiteral("%1 %2")
.arg(where.condition,
std::invoke(getWhereMethod(where.type), where));
return compiledWheres;
}
QString Grammar::concatenateWhereClauses(const QueryBuilder &query,
const QStringList &sql) const
{
// Is it a query instance of the JoinClause?
const auto conjunction = dynamic_cast<const JoinClause *>(&query) == nullptr
? QStringLiteral("where")
: QStringLiteral("on");
return QStringLiteral("%1 %2").arg(conjunction,
removeLeadingBoolean(sql.join(SPACE)));
}
QString Grammar::compileJoins(const QueryBuilder &query) const
{
const auto &joins = query.getJoins();
QStringList sql;
sql.reserve(joins.size());
for (const auto &join : joins)
sql << QStringLiteral("%1 join %2 %3").arg(join->getType(),
wrapTable(join->getTable()),
compileWheres(*join));
return sql.join(SPACE);
}
QString Grammar::compileGroups(const QueryBuilder &query) const
{
return QStringLiteral("group by %1").arg(columnize(query.getGroups()));
}
QString Grammar::compileHavings(const QueryBuilder &query) const
{
const auto &havings = query.getHavings();
QStringList compiledHavings;
compiledHavings.reserve(havings.size());
for (const auto &having : havings)
compiledHavings << compileHaving(having);
return QStringLiteral("having %1").arg(
removeLeadingBoolean(compiledHavings.join(SPACE)));
}
QString Grammar::compileHaving(const HavingConditionItem &having) const
{
/* If the having clause is "raw", we can just return the clause straight away
without doing any more processing on it. Otherwise, we will compile the
clause into SQL based on the components that make it up from builder. */
switch (having.type) {
T_LIKELY
case HavingType::BASIC:
return compileBasicHaving(having);
T_UNLIKELY
case HavingType::RAW:
return QStringLiteral("%1 %2").arg(having.condition, having.sql);
T_UNLIKELY
default:
throw Exceptions::RuntimeError(QStringLiteral("Unknown HavingType (%1).")
.arg(static_cast<int>(having.type)));
}
}
QString Grammar::compileBasicHaving(const HavingConditionItem &having) const
{
return QStringLiteral("%1 %2 %3 %4").arg(having.condition, wrap(having.column),
having.comparison, parameter(having.value));
}
QString Grammar::compileOrders(const QueryBuilder &query) const
{
if (query.getOrders().isEmpty())
return QLatin1String("");
return QStringLiteral("order by %1").arg(compileOrdersToVector(query).join(COMMA));
}
QStringList Grammar::compileOrdersToVector(const QueryBuilder &query) const
{
const auto &orders = query.getOrders();
QStringList compiledOrders;
compiledOrders.reserve(orders.size());
for (const auto &order : orders)
if (order.sql.isEmpty()) T_LIKELY
compiledOrders << QStringLiteral("%1 %2")
.arg(wrap(order.column), order.direction.toLower());
else T_UNLIKELY
compiledOrders << order.sql;
return compiledOrders;
}
QString Grammar::compileLimit(const QueryBuilder &query) const
{
return QStringLiteral("limit %1").arg(query.getLimit());
}
QString Grammar::compileOffset(const QueryBuilder &query) const
{
return QStringLiteral("offset %1").arg(query.getOffset());
}
QString Grammar::compileLock(const QueryBuilder &query) const
{
const auto &lock = query.getLock();
if (std::holds_alternative<QString>(lock))
return std::get<QString>(lock);
return QLatin1String("");
}
QString Grammar::whereBasic(const WhereConditionItem &where) const
{
// FEATURE postgres, try operators with ? vs pdo str_replace(?, ??) https://wiki.php.net/rfc/pdo_escape_placeholders silverqx
return QStringLiteral("%1 %2 %3").arg(wrap(where.column),
where.comparison,
parameter(where.value));
}
QString Grammar::whereNested(const WhereConditionItem &where) const
{
/* Here we will calculate what portion of the string we need to remove. If this
is a join clause query, we need to remove the "on" portion of the SQL and
if it is a normal query we need to take the leading "where" of queries. */
auto compiled = compileWheres(*where.nestedQuery);
const auto offset = compiled.indexOf(SPACE) + 1;
return PARENTH_ONE.arg(compiled.remove(0, offset));
}
QString Grammar::whereColumn(const WhereConditionItem &where) const
{
/* In this where type where.column contains first column and where,value contains
second column. */
return QStringLiteral("%1 %2 %3").arg(wrap(where.column),
where.comparison,
wrap(where.columnTwo));
}
QString Grammar::whereIn(const WhereConditionItem &where) const
{
if (where.values.isEmpty())
return QStringLiteral("0 = 1");
return QStringLiteral("%1 in (%2)").arg(wrap(where.column),
parametrize(where.values));
}
QString Grammar::whereNotIn(const WhereConditionItem &where) const
{
if (where.values.isEmpty())
return QStringLiteral("1 = 1");
return QStringLiteral("%1 not in (%2)").arg(wrap(where.column),
parametrize(where.values));
}
QString Grammar::whereNull(const WhereConditionItem &where) const
{
return QStringLiteral("%1 is null").arg(wrap(where.column));
}
QString Grammar::whereNotNull(const WhereConditionItem &where) const
{
return QStringLiteral("%1 is not null").arg(wrap(where.column));
}
QString Grammar::whereRaw(const WhereConditionItem &where) const
{
return where.sql;
}
QString Grammar::whereExists(const WhereConditionItem &where) const
{
return QStringLiteral("exists (%1)").arg(compileSelect(*where.nestedQuery));
}
QString Grammar::whereNotExists(const WhereConditionItem &where) const
{
return QStringLiteral("not exists (%1)").arg(compileSelect(*where.nestedQuery));
}
QStringList
Grammar::compileInsertToVector(const QVector<QVariantMap> &values) const
{
/* We need to build a list of parameter place-holders of values that are bound
to the query. Each insert should have the exact same amount of parameter
bindings so we will loop through the record and parameterize them all. */
QStringList compiledParameters;
compiledParameters.reserve(values.size());
for (const auto &valuesMap : values)
compiledParameters << PARENTH_ONE.arg(parametrize(valuesMap));
return compiledParameters;
}
QString
Grammar::compileUpdateColumns(const QVector<UpdateItem> &values) const
{
QStringList compiledAssignments;
compiledAssignments.reserve(values.size());
for (const auto &assignment : values)
compiledAssignments << QStringLiteral("%1 = %2").arg(
wrap(assignment.column),
parameter(assignment.value));
return compiledAssignments.join(COMMA);
}
QString
Grammar::compileUpdateWithoutJoins(const QueryBuilder &/*unused*/, const QString &table,
const QString &columns, const QString &wheres) const
{
// The table argument is already wrapped
return QStringLiteral("update %1 set %2 %3").arg(table, columns, wheres);
}
QString
Grammar::compileUpdateWithJoins(const QueryBuilder &query, const QString &table,
const QString &columns, const QString &wheres) const
{
const auto joins = compileJoins(query);
// The table argument is already wrapped
return QStringLiteral("update %1 %2 set %3 %4").arg(table, joins, columns, wheres);
}
QString
Grammar::compileDeleteWithoutJoins(const QueryBuilder &/*unused*/, const QString &table,
const QString &wheres) const
{
// The table argument is already wrapped
return QStringLiteral("delete from %1 %2").arg(table, wheres);
}
QString Grammar::compileDeleteWithJoins(const QueryBuilder &query, const QString &table,
const QString &wheres) const
{
const auto alias = getAliasFromFrom(table);
const auto joins = compileJoins(query);
/* Alias has to be after the delete keyword and aliased table definition after the
from keyword. */
return QStringLiteral("delete %1 from %2 %3 %4").arg(alias, table, joins, wheres);
}
QString Grammar::concatenate(const QStringList &segments) const
{
QString result;
for (const auto &segment : segments) {
if (segment.isEmpty())
continue;
result += QStringLiteral("%1 ").arg(segment);
}
return result.trimmed();
}
QString Grammar::removeLeadingBoolean(QString statement) const
{
// Skip all whitespaces after and/or, to avoid trimmed() for performance reasons
const auto firstChar = [&statement](const auto from)
{
for (auto i = from; i < statement.size(); ++i)
if (statement.at(i) != SPACE)
return i;
// Return initial value if space has not been found, should never happen :/
return from;
};
// RegExp not used for performance reasons
/* Before and/or could not be whitespace, current implementation doesn't include
whitespaces before. */
if (statement.startsWith(QLatin1String("and ")))
return statement.mid(firstChar(4));
if (statement.startsWith(QLatin1String("or ")))
return statement.mid(firstChar(3));
return statement;
}
QVector<std::reference_wrapper<const QVariant>>
Grammar::flatBindingsForUpdateDelete(const BindingsMap &bindings,
const QVector<BindingType> &exclude) const
{
QVector<std::reference_wrapper<const QVariant>> cleanBindingsFlatten;
for (auto itBindingVector = bindings.constBegin();
itBindingVector != bindings.constEnd(); ++itBindingVector)
if (exclude.contains(itBindingVector.key()))
continue;
else
for (const auto &binding : itBindingVector.value())
cleanBindingsFlatten.append(std::cref(binding));
return cleanBindingsFlatten;
}
} // namespace Orm::Query::Grammars
TINYORM_END_COMMON_NAMESPACE
| 18,857 | 5,323 |
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</editor-fold> */
#include <vsg/vk/Sampler.h>
using namespace vsg;
Sampler::Sampler(VkSampler sampler, Device* device, AllocationCallbacks* allocator) :
_sampler(sampler),
_device(device),
_allocator(allocator)
{
}
Sampler::~Sampler()
{
if (_sampler)
{
vkDestroySampler(*_device, _sampler, _allocator);
}
}
Sampler::Result Sampler::create(Device* device, const VkSamplerCreateInfo& createSamplerInfo, AllocationCallbacks* allocator)
{
if (!device)
{
return Result("Error: vsg::Sampler::create(...) failed to create vkSampler, undefined Device.", VK_ERROR_INVALID_EXTERNAL_HANDLE);
}
VkSampler sampler;
VkResult result = vkCreateSampler(*device, &createSamplerInfo, allocator, &sampler);
if (result == VK_SUCCESS)
{
return Result(new Sampler(sampler, device, allocator));
}
else
{
return Result("Error: Failed to create vkSampler.", result);
}
}
Sampler::Result Sampler::create(Device* device, AllocationCallbacks* allocator)
{
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
#if 1
// requres Logical device to have deviceFeatures.samplerAnisotropy = VK_TRUE; set when creating the vsg::Deivce
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
#else
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.maxAnisotropy = 1;
#endif
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
return create(device, samplerInfo, allocator);
}
| 3,082 | 1,064 |
#include <happly.h>
#include "ply.h"
struct PlyWrapper {
happly::PLYData ply;
happly::Element& vertex_el;
PlyWrapper(const std::string& path) :
ply(path), vertex_el(ply.getElement("vertex")) {}
};
inline static PlyWrapper* cast(void* p) {
return static_cast<PlyWrapper*>(p);
}
inline static PlyWrapper& get(const std::shared_ptr<void>& s) {
return *cast(s.get());
}
Ply::Ply(const std::string& path) :
s(new PlyWrapper(path), [] (void* p) { delete cast(p); }) {}
std::vector<double> Ply::getVertexProperty(const std::string& name) const {
return get(s).vertex_el.getProperty<double>(name);
}
std::vector<std::vector<int>> Ply::getFaceIndices() const {
return get(s).ply.getFaceIndices<int>();
}
| 742 | 274 |
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/value.hpp>
#include <eve/constant/half.hpp>
#include <eve/constant/mhalf.hpp>
#include <eve/constant/one.hpp>
#include <eve/constant/sqrt_2.hpp>
#include <eve/constant/sqrt_2o_2.hpp>
#include <eve/constant/zero.hpp>
#include <eve/detail/apply_over.hpp>
#include <eve/detail/kumi.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/skeleton_calls.hpp>
#include <eve/function/abs.hpp>
#include <eve/function/all.hpp>
#include <eve/function/cospi.hpp>
#include <eve/function/erfc.hpp>
#include <eve/function/erfc_inv.hpp>
#include <eve/function/exp.hpp>
#include <eve/function/fma.hpp>
#include <eve/function/is_finite.hpp>
#include <eve/function/is_gtz.hpp>
#include <eve/function/log.hpp>
#include <eve/function/log1p.hpp>
#include <eve/function/raw.hpp>
#include <eve/function/rec.hpp>
#include <eve/function/sqr.hpp>
#include <eve/function/sqrt.hpp>
#include <eve/module/real/core/detail/generic/horn.hpp>
#include <eve/module/proba/detail/attributes.hpp>
#include <eve/module/proba/detail/urg01.hpp>
#include <eve/platform.hpp>
#include <concepts>
#include <type_traits>
namespace eve
{
namespace detail
{
template < typename G, typename R> EVE_FORCEINLINE
auto box_muller(G & gen, as<R> const & ) noexcept
{
auto x1 = detail::urg01(gen, as<R>());
auto x2 = detail::urg01(gen, as<R>());
auto rho = eve::sqrt(-2*eve::log1p(-x1));
return rho*half_circle(cospi)(2*x2);
}
}
template < typename T, typename U, typename Internal = T>
struct normal_distribution{};
template < floating_real_value T, floating_real_value U>
requires compatible_values<T, U>
struct normal_distribution<T, U>
{
using is_distribution_t = void;
using m_type = T;
using s_type = U;
using value_type = common_compatible_t<T, U>;
using parameters = struct { value_type m; value_type s; };
normal_distribution(T m_, U s_)
: m(m_), s(s_)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
normal_distribution(parameters const & p)
: m(p.m), s(p.s)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return fma(m, detail::box_muller(gen, as<R>()), s);
}
parameters params() const noexcept
{
return { .m = m, .s = s };
}
m_type m;
s_type s;
};
template < floating_real_value U>
struct normal_distribution<callable_zero_, U>
{
using is_distribution_t = void;
using m_type = callable_zero_;
using s_type = U;
using value_type = U;
using parameters = struct { callable_zero_ m; value_type s;};
normal_distribution(callable_zero_ const&, U s_)
: s(s_)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
}
normal_distribution(parameters const & p)
: s(p.s)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>())*s;
}
parameters params() noexcept
{
return { .m = zero, .s = s };
}
s_type s;
};
template < floating_real_value T>
struct normal_distribution<T, callable_one_>
{
using is_distribution_t = void;
using m_type = T;
using s_type = decltype(eve::one);
using value_type = T;
using parameters = struct { value_type m; callable_one_ s;};
normal_distribution(T m_, callable_one_ const &)
: m(m_)
{
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
normal_distribution(parameters const & p)
: m(p.m)
{
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>())+m;
}
parameters params() noexcept
{
return { .m = m, .s = one };
}
m_type m;
};
template<typename T, typename U> normal_distribution(T,U) -> normal_distribution<T,U>;
template < floating_real_value T>
struct normal_distribution<callable_zero_, callable_one_, T>
{
using is_distribution_t = void;
using m_type = callable_zero_;
using s_type = callable_one_;
using value_type = T;
using parameters = struct { callable_zero_ m; callable_one_ s;};
normal_distribution(parameters const & ) { }
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>());
}
parameters params() noexcept
{
return { .m = zero, .s = one };
}
constexpr normal_distribution( as<T> const&) {}
};
template<typename T> normal_distribution(as<T> const&) -> normal_distribution<callable_zero_, callable_one_, T>;
template<floating_real_value T>
inline constexpr auto normal_distribution_01 = normal_distribution<callable_zero_, callable_one_, T>(as<T>{});
namespace detail
{
//////////////////////////////////////////////////////
/// cdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
if constexpr(floating_value<T> && floating_value<U>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x)/d.s));
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x/d.s));
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x)));
else
return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x));
}
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_)
, raw_type const &
, normal_distribution<T, U, I> const &d
, V const &x ) noexcept
{
using elt_t = element_type_t<T>;
if constexpr(std::same_as<elt_t, float>)
{
auto eval = [](auto l)
{
auto al = eve::abs(l);
auto k = rec(fma(T(0.2316419f),al,one(as(l))));
auto w = horn<T
, 0x3ea385fa // 0.31938153f
, 0xbeb68f87 // -0.356563782f,
, 0x3fe40778 // 1.781477937f,
, 0xbfe91eea // -1.821255978f,
, 0x3faa466f // 1.330274429f,
>(k);
auto invsqrt_2pi = T(0.39894228040143267793994605993438186847585863116493);
w*=k*invsqrt_2pi*eve::exp(-sqr(l)*half(as(l)));
return if_else(is_gtz(l),oneminus(w),w);
};
if constexpr(floating_value<T> && floating_value<U>)
return eval((x-d.m)/d.s);
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
return eval(x/d.s);
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
return eval(x-d.m);
else
return eval(x);
}
else return cdf(d, x);
}
//////////////////////////////////////////////////////
/// pdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto pdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493);
if constexpr(floating_value<T> && floating_value<U>)
{
auto invsig = rec(d.s);
return eve::exp(mhalf(as(x))*sqr((x-d.m)*invsig))*invsqrt_2pi*invsig;
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
auto invsig = rec(d.s);
return eve::exp(mhalf(as(x))*sqr(x*invsig))*invsqrt_2pi*invsig;
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return eve::exp(mhalf(as(x))*sqr((x-d.m)))*invsqrt_2pi;
}
else
return eve::exp(mhalf(as(x))*sqr(x))*invsqrt_2pi;
}
//////////////////////////////////////////////////////
/// mgf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto mgf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493);
if constexpr(floating_value<T> && floating_value<U>)
{
return eve::exp(d.m*x+sqr(d.s*x)*half(as(x)));
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
return eve::exp(sqr(d.s*x)*half(as(x)));
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return eve::exp(d.m*x+sqr(x)*half(as(x)));
}
else
return eve::exp(sqr(d)*half(as(x)));
}
//////////////////////////////////////////////////////
/// invcdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto invcdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
if constexpr(floating_value<T> && floating_value<U>)
{
return fma(-sqrt_2(as(x))*erfc_inv( T(2)*x), d.s, d.m);
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
return -sqrt_2(as(x))*erfc_inv(2*x)*d.s;
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return -sqrt_2(as(x))*erfc_inv(2*x)+d.m;
}
else
return -sqrt_2(as(x))*erfc_inv(2*x);
}
//////////////////////////////////////////////////////
/// median
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto median_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<T>)
return d.m;
else if constexpr (floating_value<U>)
return zero(as<U>());
else
return zero(as<I>());
}
//////////////////////////////////////////////////////
/// mean
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mean_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const &d) noexcept
{
return median(d);
}
//////////////////////////////////////////////////////
/// mode
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mode_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
return median(d);
}
//////////////////////////////////////////////////////
/// entropy
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto entropy_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
auto twopie = T(17.0794684453471341309271017390931489900697770715304);
if constexpr (floating_value<U>)
return half(as<T>())*log(twopie*sqr(d.s));
else
return half(as<T>())*log(twopie);
}
//////////////////////////////////////////////////////
/// skewness
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto skewness_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & ) noexcept
{
return I(0);
}
//////////////////////////////////////////////////////
/// kurtosis
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto kurtosis_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & ) noexcept
{
return I(0);
}
//////////////////////////////////////////////////////
/// mad
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mad_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
auto sqrt_2o_pi = T(0.79788456080286535587989211986876373695171726232986);
if constexpr (floating_value<U>)
return d.s*sqrt_2o_pi;
else
return sqrt_2o_pi;
}
//////////////////////////////////////////////////////
/// var
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto var_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<U>)
return sqr(d.s);
else
return one(as<I>());
}
//////////////////////////////////////////////////////
/// stdev
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto stdev_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<U>)
return d.s;
else
return one(as<I>());
}
//////////////////////////////////////////////////////
/// kullback
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto kullback_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d1
, normal_distribution<T,U,I> const & d2 ) noexcept
{
if constexpr (floating_value<T> && floating_value<U>)
{
auto srap = d1.s/d2.s;
return half(as<T>())*(dec(sqr(srap)+sqr((d1.m-d2.m)/d2.s))+T(2)*eve::log(srap));
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
auto srap = d1.s/d2.s;
return half(as<T>())*(dec(sqr(srap))+T(2)*eve::log(srap));
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return half(as<T>())*dec(oneminus(sqr((d1.m-d2.m)/d2.s)));
}
else
return zero(as<I>());
}
//////////////////////////////////////////////////////
/// confidence
template<typename T, typename U, floating_real_value R
, floating_real_value V, floating_real_value A, typename I = T>
EVE_FORCEINLINE auto confidence_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d
, R const & x
, std::array<V, 4> const & cov
, A const & alpha ) noexcept
{
using v_t = typename normal_distribution<T,U,I>::value_type;
R z = x;
auto normz = -invcdf(normal_distribution_01<I>, alpha*v_t(0.5));
auto halfwidth = normz;
if constexpr(floating_real_value<T> && floating_real_value<U>)
z = (z-d.m)/d.s;
else if constexpr(floating_real_value<T>)
z -= d.m;
else if constexpr(floating_real_value<U>)
z /= d.s;
auto zvar = fma(fma(cov[3], z, 2*cov[1]), z, cov[0]);
halfwidth *= eve::sqrt(zvar);
if constexpr(floating_real_value<U>)
halfwidth /= d.s;
auto d01 = normal_distribution_01<I>;
return kumi::make_tuple(cdf(d01, z), cdf(d01, z-halfwidth), cdf(d01, z+halfwidth));
}
}
}
| 16,430 | 5,973 |
#include "person.h"
void Person::fight(Person &other)
{
_fight_once(other);
other._fight_once(*this);
}
void Person::_fight_once(Person &other)
{
cout << " - " << get_name() << " launching the attack: ";
shout();
cout << endl;
int dice = rand() % 6 + 1;
cout << " - dice: " << dice << endl;
if (dice <= get_skill())
{
cout << " - ATTACK" << endl;
other.loose_health(get_force());
}
else
{
cout << " - missed attack" << endl;
}
} | 546 | 192 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdb/v20170320/model/CreateCloneInstanceRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
CreateCloneInstanceRequest::CreateCloneInstanceRequest() :
m_instanceIdHasBeenSet(false),
m_specifiedRollbackTimeHasBeenSet(false),
m_specifiedBackupIdHasBeenSet(false),
m_uniqVpcIdHasBeenSet(false),
m_uniqSubnetIdHasBeenSet(false),
m_memoryHasBeenSet(false),
m_volumeHasBeenSet(false),
m_instanceNameHasBeenSet(false),
m_securityGroupHasBeenSet(false),
m_resourceTagsHasBeenSet(false),
m_cpuHasBeenSet(false),
m_protectModeHasBeenSet(false),
m_deployModeHasBeenSet(false),
m_slaveZoneHasBeenSet(false),
m_backupZoneHasBeenSet(false),
m_deviceTypeHasBeenSet(false),
m_instanceNodesHasBeenSet(false),
m_deployGroupIdHasBeenSet(false),
m_dryRunHasBeenSet(false),
m_cageIdHasBeenSet(false),
m_projectIdHasBeenSet(false)
{
}
string CreateCloneInstanceRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_specifiedRollbackTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SpecifiedRollbackTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_specifiedRollbackTime.c_str(), allocator).Move(), allocator);
}
if (m_specifiedBackupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SpecifiedBackupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_specifiedBackupId, allocator);
}
if (m_uniqVpcIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UniqVpcId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_uniqVpcId.c_str(), allocator).Move(), allocator);
}
if (m_uniqSubnetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UniqSubnetId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_uniqSubnetId.c_str(), allocator).Move(), allocator);
}
if (m_memoryHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Memory";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_memory, allocator);
}
if (m_volumeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Volume";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_volume, allocator);
}
if (m_instanceNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceName.c_str(), allocator).Move(), allocator);
}
if (m_securityGroupHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SecurityGroup";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_securityGroup.begin(); itr != m_securityGroup.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_resourceTagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ResourceTags";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_resourceTags.begin(); itr != m_resourceTags.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_cpuHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cpu";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_cpu, allocator);
}
if (m_protectModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProtectMode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_protectMode, allocator);
}
if (m_deployModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeployMode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_deployMode, allocator);
}
if (m_slaveZoneHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SlaveZone";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_slaveZone.c_str(), allocator).Move(), allocator);
}
if (m_backupZoneHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupZone";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_backupZone.c_str(), allocator).Move(), allocator);
}
if (m_deviceTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeviceType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_deviceType.c_str(), allocator).Move(), allocator);
}
if (m_instanceNodesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceNodes";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_instanceNodes, allocator);
}
if (m_deployGroupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeployGroupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_deployGroupId.c_str(), allocator).Move(), allocator);
}
if (m_dryRunHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DryRun";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_dryRun, allocator);
}
if (m_cageIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CageId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_cageId.c_str(), allocator).Move(), allocator);
}
if (m_projectIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_projectId, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateCloneInstanceRequest::GetInstanceId() const
{
return m_instanceId;
}
void CreateCloneInstanceRequest::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetSpecifiedRollbackTime() const
{
return m_specifiedRollbackTime;
}
void CreateCloneInstanceRequest::SetSpecifiedRollbackTime(const string& _specifiedRollbackTime)
{
m_specifiedRollbackTime = _specifiedRollbackTime;
m_specifiedRollbackTimeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SpecifiedRollbackTimeHasBeenSet() const
{
return m_specifiedRollbackTimeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetSpecifiedBackupId() const
{
return m_specifiedBackupId;
}
void CreateCloneInstanceRequest::SetSpecifiedBackupId(const int64_t& _specifiedBackupId)
{
m_specifiedBackupId = _specifiedBackupId;
m_specifiedBackupIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SpecifiedBackupIdHasBeenSet() const
{
return m_specifiedBackupIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetUniqVpcId() const
{
return m_uniqVpcId;
}
void CreateCloneInstanceRequest::SetUniqVpcId(const string& _uniqVpcId)
{
m_uniqVpcId = _uniqVpcId;
m_uniqVpcIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::UniqVpcIdHasBeenSet() const
{
return m_uniqVpcIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetUniqSubnetId() const
{
return m_uniqSubnetId;
}
void CreateCloneInstanceRequest::SetUniqSubnetId(const string& _uniqSubnetId)
{
m_uniqSubnetId = _uniqSubnetId;
m_uniqSubnetIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::UniqSubnetIdHasBeenSet() const
{
return m_uniqSubnetIdHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetMemory() const
{
return m_memory;
}
void CreateCloneInstanceRequest::SetMemory(const int64_t& _memory)
{
m_memory = _memory;
m_memoryHasBeenSet = true;
}
bool CreateCloneInstanceRequest::MemoryHasBeenSet() const
{
return m_memoryHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetVolume() const
{
return m_volume;
}
void CreateCloneInstanceRequest::SetVolume(const int64_t& _volume)
{
m_volume = _volume;
m_volumeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::VolumeHasBeenSet() const
{
return m_volumeHasBeenSet;
}
string CreateCloneInstanceRequest::GetInstanceName() const
{
return m_instanceName;
}
void CreateCloneInstanceRequest::SetInstanceName(const string& _instanceName)
{
m_instanceName = _instanceName;
m_instanceNameHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceNameHasBeenSet() const
{
return m_instanceNameHasBeenSet;
}
vector<string> CreateCloneInstanceRequest::GetSecurityGroup() const
{
return m_securityGroup;
}
void CreateCloneInstanceRequest::SetSecurityGroup(const vector<string>& _securityGroup)
{
m_securityGroup = _securityGroup;
m_securityGroupHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SecurityGroupHasBeenSet() const
{
return m_securityGroupHasBeenSet;
}
vector<TagInfo> CreateCloneInstanceRequest::GetResourceTags() const
{
return m_resourceTags;
}
void CreateCloneInstanceRequest::SetResourceTags(const vector<TagInfo>& _resourceTags)
{
m_resourceTags = _resourceTags;
m_resourceTagsHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ResourceTagsHasBeenSet() const
{
return m_resourceTagsHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetCpu() const
{
return m_cpu;
}
void CreateCloneInstanceRequest::SetCpu(const int64_t& _cpu)
{
m_cpu = _cpu;
m_cpuHasBeenSet = true;
}
bool CreateCloneInstanceRequest::CpuHasBeenSet() const
{
return m_cpuHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetProtectMode() const
{
return m_protectMode;
}
void CreateCloneInstanceRequest::SetProtectMode(const int64_t& _protectMode)
{
m_protectMode = _protectMode;
m_protectModeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ProtectModeHasBeenSet() const
{
return m_protectModeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetDeployMode() const
{
return m_deployMode;
}
void CreateCloneInstanceRequest::SetDeployMode(const int64_t& _deployMode)
{
m_deployMode = _deployMode;
m_deployModeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeployModeHasBeenSet() const
{
return m_deployModeHasBeenSet;
}
string CreateCloneInstanceRequest::GetSlaveZone() const
{
return m_slaveZone;
}
void CreateCloneInstanceRequest::SetSlaveZone(const string& _slaveZone)
{
m_slaveZone = _slaveZone;
m_slaveZoneHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SlaveZoneHasBeenSet() const
{
return m_slaveZoneHasBeenSet;
}
string CreateCloneInstanceRequest::GetBackupZone() const
{
return m_backupZone;
}
void CreateCloneInstanceRequest::SetBackupZone(const string& _backupZone)
{
m_backupZone = _backupZone;
m_backupZoneHasBeenSet = true;
}
bool CreateCloneInstanceRequest::BackupZoneHasBeenSet() const
{
return m_backupZoneHasBeenSet;
}
string CreateCloneInstanceRequest::GetDeviceType() const
{
return m_deviceType;
}
void CreateCloneInstanceRequest::SetDeviceType(const string& _deviceType)
{
m_deviceType = _deviceType;
m_deviceTypeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeviceTypeHasBeenSet() const
{
return m_deviceTypeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetInstanceNodes() const
{
return m_instanceNodes;
}
void CreateCloneInstanceRequest::SetInstanceNodes(const int64_t& _instanceNodes)
{
m_instanceNodes = _instanceNodes;
m_instanceNodesHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceNodesHasBeenSet() const
{
return m_instanceNodesHasBeenSet;
}
string CreateCloneInstanceRequest::GetDeployGroupId() const
{
return m_deployGroupId;
}
void CreateCloneInstanceRequest::SetDeployGroupId(const string& _deployGroupId)
{
m_deployGroupId = _deployGroupId;
m_deployGroupIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeployGroupIdHasBeenSet() const
{
return m_deployGroupIdHasBeenSet;
}
bool CreateCloneInstanceRequest::GetDryRun() const
{
return m_dryRun;
}
void CreateCloneInstanceRequest::SetDryRun(const bool& _dryRun)
{
m_dryRun = _dryRun;
m_dryRunHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DryRunHasBeenSet() const
{
return m_dryRunHasBeenSet;
}
string CreateCloneInstanceRequest::GetCageId() const
{
return m_cageId;
}
void CreateCloneInstanceRequest::SetCageId(const string& _cageId)
{
m_cageId = _cageId;
m_cageIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::CageIdHasBeenSet() const
{
return m_cageIdHasBeenSet;
}
uint64_t CreateCloneInstanceRequest::GetProjectId() const
{
return m_projectId;
}
void CreateCloneInstanceRequest::SetProjectId(const uint64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
| 15,224 | 5,295 |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/engine_impl/sync_encryption_handler_impl.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/base64.h"
#include "base/bind.h"
#include "base/containers/queue.h"
#include "base/feature_list.h"
#include "base/json/json_string_value_serializer.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "components/sync/base/encryptor.h"
#include "components/sync/base/passphrase_enums.h"
#include "components/sync/base/sync_base_switches.h"
#include "components/sync/base/time.h"
#include "components/sync/engine/sync_engine_switches.h"
#include "components/sync/engine/sync_string_conversions.h"
#include "components/sync/protocol/encryption.pb.h"
#include "components/sync/protocol/nigori_specifics.pb.h"
#include "components/sync/protocol/sync.pb.h"
#include "components/sync/syncable/directory.h"
#include "components/sync/syncable/entry.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/nigori_util.h"
#include "components/sync/syncable/read_node.h"
#include "components/sync/syncable/read_transaction.h"
#include "components/sync/syncable/syncable_base_transaction.h"
#include "components/sync/syncable/syncable_model_neutral_write_transaction.h"
#include "components/sync/syncable/syncable_read_transaction.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/syncable/user_share.h"
#include "components/sync/syncable/write_node.h"
#include "components/sync/syncable/write_transaction.h"
namespace syncer {
namespace {
// The maximum number of times we will automatically overwrite the nigori node
// because the encryption keys don't match (per chrome instantiation).
// We protect ourselves against nigori rollbacks, but it's possible two
// different clients might have contrasting view of what the nigori node state
// should be, in which case they might ping pong (see crbug.com/119207).
static const int kNigoriOverwriteLimit = 10;
// Enumeration of nigori keystore migration results (for use in UMA stats).
enum NigoriMigrationResult {
FAILED_TO_SET_DEFAULT_KEYSTORE,
FAILED_TO_SET_NONDEFAULT_KEYSTORE,
FAILED_TO_EXTRACT_DECRYPTOR,
FAILED_TO_EXTRACT_KEYBAG,
MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
MIGRATION_SUCCESS_FROZEN_IMPLICIT,
MIGRATION_SUCCESS_CUSTOM,
MIGRATION_RESULT_SIZE,
};
enum NigoriMigrationState {
MIGRATED,
NOT_MIGRATED_CRYPTO_NOT_READY,
NOT_MIGRATED_NO_KEYSTORE_KEY,
NOT_MIGRATED_UNKNOWN_REASON,
MIGRATION_STATE_SIZE,
};
// The new passphrase state is sufficient to determine whether a nigori node
// is migrated to support keystore encryption. In addition though, we also
// want to verify the conditions for proper keystore encryption functionality.
// 1. Passphrase type is set.
// 2. Frozen keybag is true
// 3. If passphrase state is keystore, keystore_decryptor_token is set.
bool IsNigoriMigratedToKeystore(const sync_pb::NigoriSpecifics& nigori) {
// |passphrase_type| is always populated by modern clients, but may be missing
// in coming from an ancient client, from data that was never upgraded, or
// from the uninitialized NigoriSpecifics (e.g. sync was just enabled for this
// account).
if (!nigori.has_passphrase_type())
return false;
if (!nigori.keybag_is_frozen())
return false;
if (nigori.passphrase_type() == sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE)
return false;
if (nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE &&
nigori.keystore_decryptor_token().blob().empty())
return false;
return true;
}
// Keystore Bootstrap Token helper methods.
// The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
// strings, with the current keystore key as the last value in the list.
std::string PackKeystoreBootstrapToken(
const std::vector<std::string>& old_keystore_keys,
const std::string& current_keystore_key,
const Encryptor& encryptor) {
if (current_keystore_key.empty())
return std::string();
base::ListValue keystore_key_values;
for (size_t i = 0; i < old_keystore_keys.size(); ++i)
keystore_key_values.AppendString(old_keystore_keys[i]);
keystore_key_values.AppendString(current_keystore_key);
// Update the bootstrap token.
// The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
// strings, with the current keystore key as the last value in the list.
std::string serialized_keystores;
JSONStringValueSerializer json(&serialized_keystores);
json.Serialize(keystore_key_values);
std::string encrypted_keystores;
encryptor.EncryptString(serialized_keystores, &encrypted_keystores);
std::string keystore_bootstrap;
base::Base64Encode(encrypted_keystores, &keystore_bootstrap);
return keystore_bootstrap;
}
bool UnpackKeystoreBootstrapToken(const std::string& keystore_bootstrap_token,
const Encryptor& encryptor,
std::vector<std::string>* old_keystore_keys,
std::string* current_keystore_key) {
if (keystore_bootstrap_token.empty())
return false;
std::string base64_decoded_keystore_bootstrap;
if (!base::Base64Decode(keystore_bootstrap_token,
&base64_decoded_keystore_bootstrap)) {
return false;
}
std::string decrypted_keystore_bootstrap;
if (!encryptor.DecryptString(base64_decoded_keystore_bootstrap,
&decrypted_keystore_bootstrap)) {
return false;
}
JSONStringValueDeserializer json(decrypted_keystore_bootstrap);
std::unique_ptr<base::Value> deserialized_keystore_keys(
json.Deserialize(nullptr, nullptr));
if (!deserialized_keystore_keys)
return false;
base::ListValue* internal_list_value = nullptr;
if (!deserialized_keystore_keys->GetAsList(&internal_list_value))
return false;
int number_of_keystore_keys = internal_list_value->GetSize();
if (!internal_list_value->GetString(number_of_keystore_keys - 1,
current_keystore_key)) {
return false;
}
old_keystore_keys->resize(number_of_keystore_keys - 1);
for (int i = 0; i < number_of_keystore_keys - 1; ++i)
internal_list_value->GetString(i, &(*old_keystore_keys)[i]);
return true;
}
// Returns the key derivation method to be used when a user sets a new
// custom passphrase.
KeyDerivationMethod GetDefaultKeyDerivationMethodForCustomPassphrase() {
if (base::FeatureList::IsEnabled(
switches::kSyncUseScryptForNewCustomPassphrases) &&
!base::FeatureList::IsEnabled(
switches::kSyncForceDisableScryptForCustomPassphrase)) {
return KeyDerivationMethod::SCRYPT_8192_8_11;
}
return KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003;
}
KeyDerivationParams CreateKeyDerivationParamsForCustomPassphrase(
const base::RepeatingCallback<std::string()>& random_salt_generator) {
KeyDerivationMethod method =
GetDefaultKeyDerivationMethodForCustomPassphrase();
switch (method) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationParams::CreateForPbkdf2();
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationParams::CreateForScrypt(random_salt_generator.Run());
case KeyDerivationMethod::UNSUPPORTED:
break;
}
NOTREACHED();
return KeyDerivationParams::CreateWithUnsupportedMethod();
}
KeyDerivationMethod GetKeyDerivationMethodFromNigori(
const sync_pb::NigoriSpecifics& nigori) {
::google::protobuf::int32 proto_key_derivation_method =
nigori.custom_passphrase_key_derivation_method();
KeyDerivationMethod key_derivation_method =
ProtoKeyDerivationMethodToEnum(proto_key_derivation_method);
if (key_derivation_method == KeyDerivationMethod::SCRYPT_8192_8_11 &&
base::FeatureList::IsEnabled(
switches::kSyncForceDisableScryptForCustomPassphrase)) {
// Because scrypt is explicitly disabled, just behave as if it is an
// unsupported method.
key_derivation_method = KeyDerivationMethod::UNSUPPORTED;
}
if (key_derivation_method == KeyDerivationMethod::UNSUPPORTED) {
DLOG(WARNING) << "Unsupported key derivation method encountered: "
<< proto_key_derivation_method;
}
return key_derivation_method;
}
std::string GetScryptSaltFromNigori(const sync_pb::NigoriSpecifics& nigori) {
DCHECK_EQ(nigori.custom_passphrase_key_derivation_method(),
sync_pb::NigoriSpecifics::SCRYPT_8192_8_11);
std::string decoded_salt;
bool result = base::Base64Decode(
nigori.custom_passphrase_key_derivation_salt(), &decoded_salt);
DCHECK(result);
return decoded_salt;
}
KeyDerivationParams GetKeyDerivationParamsFromNigori(
const sync_pb::NigoriSpecifics& nigori) {
KeyDerivationMethod method = GetKeyDerivationMethodFromNigori(nigori);
switch (method) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationParams::CreateForPbkdf2();
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationParams::CreateForScrypt(
GetScryptSaltFromNigori(nigori));
case KeyDerivationMethod::UNSUPPORTED:
break;
}
return KeyDerivationParams::CreateWithUnsupportedMethod();
}
void UpdateNigoriSpecificsKeyDerivationParams(
const KeyDerivationParams& params,
sync_pb::NigoriSpecifics* nigori) {
DCHECK_EQ(nigori->passphrase_type(),
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
DCHECK_NE(params.method(), KeyDerivationMethod::UNSUPPORTED);
nigori->set_custom_passphrase_key_derivation_method(
EnumKeyDerivationMethodToProto(params.method()));
if (params.method() == KeyDerivationMethod::SCRYPT_8192_8_11) {
// Persist the salt used for key derivation in Nigori if we're using scrypt.
std::string encoded_salt;
base::Base64Encode(params.scrypt_salt(), &encoded_salt);
nigori->set_custom_passphrase_key_derivation_salt(encoded_salt);
}
}
KeyDerivationMethodStateForMetrics GetKeyDerivationMethodStateForMetrics(
const base::Optional<KeyDerivationParams>& key_derivation_params) {
if (!key_derivation_params.has_value()) {
return KeyDerivationMethodStateForMetrics::NOT_SET;
}
switch (key_derivation_params.value().method()) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationMethodStateForMetrics::PBKDF2_HMAC_SHA1_1003;
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationMethodStateForMetrics::SCRYPT_8192_8_11;
case KeyDerivationMethod::UNSUPPORTED:
return KeyDerivationMethodStateForMetrics::UNSUPPORTED;
}
NOTREACHED();
return KeyDerivationMethodStateForMetrics::UNSUPPORTED;
}
// The custom passphrase key derivation method in Nigori can be unspecified
// (which means that PBKDF2 was implicitly used). In those cases, we want to set
// it explicitly to PBKDF2. This function checks whether this needs to be done.
bool ShouldSetExplicitCustomPassphraseKeyDerivationMethod(
const sync_pb::NigoriSpecifics& nigori) {
return nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE &&
nigori.custom_passphrase_key_derivation_method() ==
sync_pb::NigoriSpecifics::UNSPECIFIED;
}
} // namespace
SyncEncryptionHandlerImpl::Vault::Vault(ModelTypeSet encrypted_types,
PassphraseType passphrase_type)
: encrypted_types(encrypted_types), passphrase_type(passphrase_type) {}
SyncEncryptionHandlerImpl::Vault::~Vault() {}
SyncEncryptionHandlerImpl::SyncEncryptionHandlerImpl(
UserShare* user_share,
const Encryptor* encryptor,
const std::string& restored_key_for_bootstrapping,
const std::string& restored_keystore_key_for_bootstrapping,
const base::RepeatingCallback<std::string()>& random_salt_generator)
: user_share_(user_share),
encryptor_(encryptor),
vault_unsafe_(AlwaysEncryptedUserTypes(), kInitialPassphraseType),
encrypt_everything_(false),
nigori_overwrite_count_(0),
random_salt_generator_(random_salt_generator),
migration_attempted_(false) {
DCHECK(encryptor);
// Restore the cryptographer's previous keys. Note that we don't add the
// keystore keys into the cryptographer here, in case a migration was pending.
vault_unsafe_.cryptographer.Bootstrap(*encryptor,
restored_key_for_bootstrapping);
// If this fails, we won't have a valid keystore key, and will simply request
// new ones from the server on the next DownloadUpdates.
UnpackKeystoreBootstrapToken(restored_keystore_key_for_bootstrapping,
*encryptor, &old_keystore_keys_, &keystore_key_);
}
SyncEncryptionHandlerImpl::~SyncEncryptionHandlerImpl() {}
void SyncEncryptionHandlerImpl::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!observers_.HasObserver(observer));
observers_.AddObserver(observer);
}
void SyncEncryptionHandlerImpl::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(observers_.HasObserver(observer));
observers_.RemoveObserver(observer);
}
bool SyncEncryptionHandlerImpl::Init() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
// TODO(mastiz): This should be treated as error because it's a protocol
// violation if the server doesn't return the NIGORI root.
return true;
}
switch (ApplyNigoriUpdateImpl(node.GetNigoriSpecifics(),
trans.GetWrappedTrans())) {
case ApplyNigoriUpdateResult::kSuccess:
// If we have successfully updated, we also need to replace an UNSPECIFIED
// key derivation method in Nigori with PBKDF2. (If the update fails,
// WriteEncryptionStateToNigori will do this for us.)
ReplaceImplicitKeyDerivationMethodInNigori(&trans);
break;
case ApplyNigoriUpdateResult::kUnsupportedRemoteState:
return false;
case ApplyNigoriUpdateResult::kRemoteMustBeCorrected:
WriteEncryptionStateToNigori(&trans, NigoriMigrationTrigger::kInit);
break;
}
PassphraseType passphrase_type = GetPassphraseType(trans.GetWrappedTrans());
UMA_HISTOGRAM_ENUMERATION("Sync.PassphraseType", passphrase_type);
if (passphrase_type == PassphraseType::kCustomPassphrase) {
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto.CustomPassphraseKeyDerivationMethodStateOnStartup",
GetKeyDerivationMethodStateForMetrics(
custom_passphrase_key_derivation_params_));
}
bool has_pending_keys =
UnlockVault(trans.GetWrappedTrans()).cryptographer.has_pending_keys();
bool is_ready =
UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt();
// Log the state of the cryptographer regardless of migration state.
UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerReady", is_ready);
UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerPendingKeys", has_pending_keys);
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
// This account has a nigori node that has been migrated to support
// keystore.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState", MIGRATED,
MIGRATION_STATE_SIZE);
if (has_pending_keys && GetPassphraseType(trans.GetWrappedTrans()) ==
PassphraseType::kKeystorePassphrase) {
// If this is happening, it means the keystore decryptor is either
// undecryptable with the available keystore keys or does not match the
// nigori keybag's encryption key. Otherwise we're simply missing the
// keystore key.
UMA_HISTOGRAM_BOOLEAN("Sync.KeystoreDecryptionFailed",
!keystore_key_.empty());
}
} else if (!is_ready) {
// Migration cannot occur until the cryptographer is ready (initialized
// with GAIA password and any pending keys resolved).
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_CRYPTO_NOT_READY,
MIGRATION_STATE_SIZE);
} else if (keystore_key_.empty()) {
// The client has no keystore key, either because it is not yet enabled or
// the server is not sending a valid keystore key.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_NO_KEYSTORE_KEY,
MIGRATION_STATE_SIZE);
} else {
// If the above conditions have been met and the nigori node is still not
// migrated, something failed in the migration process.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_UNKNOWN_REASON,
MIGRATION_STATE_SIZE);
}
// Always trigger an encrypted types and cryptographer state change event at
// init time so observers get the initial values.
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(
UnlockVault(trans.GetWrappedTrans()).encrypted_types,
encrypt_everything_);
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer,
UnlockVault(trans.GetWrappedTrans()).cryptographer.has_pending_keys());
}
// If the cryptographer is not ready (either it has pending keys or we
// failed to initialize it), we don't want to try and re-encrypt the data.
// If we had encrypted types, the DataTypeManager will block, preventing
// sync from happening until the the passphrase is provided.
if (UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt())
ReEncryptEverything(&trans);
return true;
}
void SyncEncryptionHandlerImpl::SetEncryptionPassphrase(
const std::string& passphrase) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We do not accept empty passphrases.
if (passphrase.empty()) {
NOTREACHED() << "Cannot encrypt with an empty passphrase.";
return;
}
// All accesses to the cryptographer are protected by a transaction.
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
NOTREACHED();
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
// Once we've migrated to keystore, the only way to set a passphrase for
// encryption is to set a custom passphrase.
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
// Will fail if we already have an explicit passphrase or we have pending
// keys.
SetCustomPassphrase(passphrase, &trans, &node);
// When keystore migration occurs, the "CustomEncryption" UMA stat must be
// logged as true.
UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
return;
}
std::string bootstrap_token;
sync_pb::EncryptedData pending_keys;
if (cryptographer->has_pending_keys())
pending_keys = cryptographer->GetPendingKeys();
bool success = false;
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans.GetWrappedTrans())->passphrase_type;
// There are six cases to handle here:
// 1. The user has no pending keys and is setting their current GAIA password
// as the encryption passphrase. This happens either during first time sync
// with a clean profile, or after re-authenticating on a profile that was
// already signed in with the cryptographer ready.
// 2. The user has no pending keys, and is overwriting an (already provided)
// implicit passphrase with an explicit (custom) passphrase.
// 3. The user has pending keys for an explicit passphrase that is somehow set
// to their current GAIA passphrase.
// 4. The user has pending keys encrypted with their current GAIA passphrase
// and the caller passes in the current GAIA passphrase.
// 5. The user has pending keys encrypted with an older GAIA passphrase
// and the caller passes in the current GAIA passphrase.
// 6. The user has previously done encryption with an explicit passphrase.
// Furthermore, we enforce the fact that the bootstrap encryption token will
// always be derived from the newest GAIA password if the account is using
// an implicit passphrase (even if the data is encrypted with an old GAIA
// password). If the account is using an explicit (custom) passphrase, the
// bootstrap token will be derived from the most recently provided explicit
// passphrase (that was able to decrypt the data).
if (!IsExplicitPassphrase(*passphrase_type)) {
if (!cryptographer->has_pending_keys()) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
passphrase};
if (cryptographer->AddKey(key_params)) {
// Case 1 and 2. We set a new GAIA passphrase when there are no pending
// keys (1), or overwriting an implicit passphrase with a new explicit
// one (2) when there are no pending keys.
DVLOG(1) << "Setting explicit passphrase for encryption.";
*passphrase_type = PassphraseType::kCustomPassphrase;
custom_passphrase_time_ = base::Time::Now();
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
success = true;
} else {
NOTREACHED() << "Failed to add key to cryptographer.";
success = false;
}
} else { // cryptographer->has_pending_keys() == true
// This can only happen if the nigori node is updated with a new
// implicit passphrase while a client is attempting to set a new custom
// passphrase (race condition).
DVLOG(1) << "Failing because an implicit passphrase is already set.";
success = false;
} // cryptographer->has_pending_keys()
} else { // IsExplicitPassphrase(passphrase_type) == true.
// Case 6. We do not want to override a previously set explicit passphrase,
// so we return a failure.
DVLOG(1) << "Failing because an explicit passphrase is already set.";
success = false;
}
DVLOG_IF(1, !success)
<< "Failure in SetEncryptionPassphrase; notifying and returning.";
DVLOG_IF(1, success)
<< "Successfully set encryption passphrase; updating nigori and "
"reencrypting.";
FinishSetPassphrase(success, bootstrap_token, &trans, &node);
}
void SyncEncryptionHandlerImpl::SetDecryptionPassphrase(
const std::string& passphrase) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We do not accept empty passphrases.
if (passphrase.empty()) {
NOTREACHED() << "Cannot decrypt with an empty passphrase.";
return;
}
// All accesses to the cryptographer are protected by a transaction.
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
NOTREACHED();
return;
}
// Once we've migrated to keystore, we're only ever decrypting keys derived
// from an explicit passphrase. But, for clients without a keystore key yet
// (either not on by default or failed to download one), we still support
// decrypting with a gaia passphrase, and therefore bypass the
// DecryptPendingKeysWithExplicitPassphrase logic.
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics()) &&
IsExplicitPassphrase(GetPassphraseType(trans.GetWrappedTrans()))) {
// We have completely migrated and are using an explicit passphrase (either
// FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE). In the
// CUSTOM_PASSPHRASE case, custom_passphrase_key_derivation_method_ was set
// previously (when reading the Nigori node), and we will use it for key
// derivation in DecryptPendingKeysWithExplicitPassphrase.
PassphraseType passphrase_type = GetPassphraseType(trans.GetWrappedTrans());
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
if (custom_passphrase_key_derivation_params_.value().method() ==
KeyDerivationMethod::UNSUPPORTED) {
// For now we will just refuse the passphrase. In the future, we may
// notify the user about the reason and ask them to update Chrome.
DLOG(ERROR) << "Setting decryption passphrase failed because the key "
"derivation method is unsupported.";
FinishSetPassphrase(/*success=*/false,
/*bootstrap_token=*/std::string(), &trans, &node);
return;
}
DVLOG(1)
<< "Setting passphrase of type "
<< PassphraseTypeToString(PassphraseType::kCustomPassphrase)
<< " for decryption with key derivation method "
<< KeyDerivationMethodToString(
custom_passphrase_key_derivation_params_.value().method());
} else {
DVLOG(1) << "Setting passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " for decryption, implicitly using old key derivation method";
}
DecryptPendingKeysWithExplicitPassphrase(passphrase, &trans, &node);
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
if (!cryptographer->has_pending_keys()) {
// Note that this *can* happen in a rare situation where data is
// re-encrypted on another client while a SetDecryptionPassphrase() call is
// in-flight on this client. It is rare enough that we choose to do nothing.
NOTREACHED() << "Attempt to set decryption passphrase failed because there "
<< "were no pending keys.";
return;
}
std::string bootstrap_token;
sync_pb::EncryptedData pending_keys;
pending_keys = cryptographer->GetPendingKeys();
bool success = false;
// There are three cases to handle here:
// 7. We're using the current GAIA password to decrypt the pending keys. This
// happens when signing in to an account with a previously set implicit
// passphrase, where the data is already encrypted with the newest GAIA
// password.
// 8. The user is providing an old GAIA password to decrypt the pending keys.
// In this case, the user is using an implicit passphrase, but has changed
// their password since they last encrypted their data, and therefore
// their current GAIA password was unable to decrypt the data. This will
// happen when the user is setting up a new profile with a previously
// encrypted account (after changing passwords).
// 9. The user is providing a previously set explicit passphrase to decrypt
// the pending keys.
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), passphrase};
if (!IsExplicitPassphrase(GetPassphraseType(trans.GetWrappedTrans()))) {
if (cryptographer->is_initialized()) {
// We only want to change the default encryption key to the pending
// one if the pending keybag already contains the current default.
// This covers the case where a different client re-encrypted
// everything with a newer gaia passphrase (and hence the keybag
// contains keys from all previously used gaia passphrases).
// Otherwise, we're in a situation where the pending keys are
// encrypted with an old gaia passphrase, while the default is the
// current gaia passphrase. In that case, we preserve the default.
DirectoryCryptographer temp_cryptographer;
temp_cryptographer.SetPendingKeys(cryptographer->GetPendingKeys());
if (temp_cryptographer.DecryptPendingKeys(key_params)) {
// Check to see if the pending bag of keys contains the current
// default key.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
if (temp_cryptographer.CanDecrypt(encrypted)) {
DVLOG(1) << "Implicit user provided passphrase accepted for "
<< "decryption, overwriting default.";
// Case 7. The pending keybag contains the current default. Go ahead
// and update the cryptographer, letting the default change.
cryptographer->DecryptPendingKeys(key_params);
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
} else {
// Case 8. The pending keybag does not contain the current default
// encryption key. We decrypt the pending keys here, and in
// FinishSetPassphrase, re-encrypt everything with the current GAIA
// passphrase instead of the passphrase just provided by the user.
DVLOG(1) << "Implicit user provided passphrase accepted for "
<< "decryption, restoring implicit internal passphrase "
<< "as default.";
std::string bootstrap_token_from_current_key;
cryptographer->GetBootstrapToken(*encryptor_,
&bootstrap_token_from_current_key);
cryptographer->DecryptPendingKeys(key_params);
// Overwrite the default from the pending keys.
cryptographer->AddKeyFromBootstrapToken(
*encryptor_, bootstrap_token_from_current_key);
success = true;
}
} else { // !temp_cryptographer.DecryptPendingKeys(..)
DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
success = false;
} // temp_cryptographer.DecryptPendingKeys(...)
} else { // cryptographer->is_initialized() == false
if (cryptographer->DecryptPendingKeys(key_params)) {
// This can happpen in two cases:
// - First time sync on android, where we'll never have a
// !user_provided passphrase.
// - This is a restart for a client that lost their bootstrap token.
// In both cases, we should go ahead and initialize the cryptographer
// and persist the new bootstrap token.
//
// Note: at this point, we cannot distinguish between cases 7 and 8
// above. This user provided passphrase could be the current or the
// old. But, as long as we persist the token, there's nothing more
// we can do.
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
<< " cryptographer.";
success = true;
} else {
DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
success = false;
}
} // cryptographer->is_initialized()
} else { // nigori_has_explicit_passphrase == true
// Case 9. Encryption was done with an explicit passphrase, and we decrypt
// with the passphrase provided by the user.
if (cryptographer->DecryptPendingKeys(key_params)) {
DVLOG(1) << "Explicit passphrase accepted for decryption.";
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
} else {
DVLOG(1) << "Explicit passphrase failed to decrypt.";
success = false;
}
} // nigori_has_explicit_passphrase
DVLOG_IF(1, !success)
<< "Failure in SetDecryptionPassphrase; notifying and returning.";
DVLOG_IF(1, success)
<< "Successfully set decryption passphrase; updating nigori and "
"reencrypting.";
FinishSetPassphrase(success, bootstrap_token, &trans, &node);
}
void SyncEncryptionHandlerImpl::AddTrustedVaultDecryptionKeys(
const std::vector<std::vector<uint8_t>>& keys) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
NOTIMPLEMENTED();
}
void SyncEncryptionHandlerImpl::EnableEncryptEverything() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
DVLOG(1) << "Enabling encrypt everything.";
if (encrypt_everything_)
return;
EnableEncryptEverythingImpl(trans.GetWrappedTrans());
WriteEncryptionStateToNigori(
&trans, NigoriMigrationTrigger::kEnableEncryptEverything);
if (UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt())
ReEncryptEverything(&trans);
}
bool SyncEncryptionHandlerImpl::IsEncryptEverythingEnabled() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return encrypt_everything_;
}
base::Time SyncEncryptionHandlerImpl::GetKeystoreMigrationTime() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return keystore_migration_time_;
}
KeystoreKeysHandler* SyncEncryptionHandlerImpl::GetKeystoreKeysHandler() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return this;
}
std::string SyncEncryptionHandlerImpl::GetLastKeystoreKey() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
return keystore_key_;
}
// Note: this is called from within a syncable transaction, so we need to post
// tasks if we want to do any work that creates a new sync_api transaction.
bool SyncEncryptionHandlerImpl::ApplyNigoriUpdate(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(trans);
switch (ApplyNigoriUpdateImpl(nigori, trans)) {
case ApplyNigoriUpdateResult::kSuccess:
// If we have successfully updated, we also need to replace an UNSPECIFIED
// key derivation method in Nigori with PBKDF2, for which we post a task.
// (If the update fails, RewriteNigori will do this for us.) Note that
// this check is redundant, but it is used to avoid the overhead of
// posting a task which will just do nothing.
if (ShouldSetExplicitCustomPassphraseKeyDerivationMethod(nigori)) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&SyncEncryptionHandlerImpl::
ReplaceImplicitKeyDerivationMethodInNigoriWithTransaction,
weak_ptr_factory_.GetWeakPtr()));
}
break;
case ApplyNigoriUpdateResult::kUnsupportedRemoteState:
return false;
case ApplyNigoriUpdateResult::kRemoteMustBeCorrected:
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&SyncEncryptionHandlerImpl::RewriteNigori,
weak_ptr_factory_.GetWeakPtr(),
NigoriMigrationTrigger::kApplyNigoriUpdate));
break;
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans)->cryptographer,
UnlockVault(trans).cryptographer.has_pending_keys());
}
return true;
}
void SyncEncryptionHandlerImpl::UpdateNigoriFromEncryptedTypes(
sync_pb::NigoriSpecifics* nigori,
const syncable::BaseTransaction* const trans) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::UpdateNigoriFromEncryptedTypes(UnlockVault(trans).encrypted_types,
encrypt_everything_, nigori);
}
bool SyncEncryptionHandlerImpl::NeedKeystoreKey() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
return keystore_key_.empty();
}
bool SyncEncryptionHandlerImpl::SetKeystoreKeys(
const std::vector<std::vector<uint8_t>>& keys) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
if (keys.empty())
return false;
// The last key in the vector is the current keystore key. The others are kept
// around for decryption only.
const std::vector<uint8_t>& raw_keystore_key = keys.back();
if (raw_keystore_key.empty())
return false;
// Note: in order to Pack the keys, they must all be base64 encoded (else
// JSON serialization fails).
keystore_key_ = base::Base64Encode(raw_keystore_key);
// Go through and save the old keystore keys. We always persist all keystore
// keys the server sends us.
old_keystore_keys_.resize(keys.size() - 1);
for (size_t i = 0; i < keys.size() - 1; ++i)
old_keystore_keys_[i] = base::Base64Encode(keys[i]);
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(&trans)->cryptographer;
// Update the bootstrap token. If this fails, we persist an empty string,
// which will force us to download the keystore keys again on the next
// restart.
std::string keystore_bootstrap = PackKeystoreBootstrapToken(
old_keystore_keys_, keystore_key_, *encryptor_);
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(keystore_bootstrap,
KEYSTORE_BOOTSTRAP_TOKEN);
}
DVLOG(1) << "Keystore bootstrap token updated.";
// If this is a first time sync, we get the encryption keys before we process
// the nigori node. Just return for now, ApplyNigoriUpdate will be invoked
// once we have the nigori node.
syncable::Entry entry(&trans, syncable::GET_TYPE_ROOT, NIGORI);
if (!entry.good())
return true;
const sync_pb::NigoriSpecifics& nigori = entry.GetSpecifics().nigori();
if (cryptographer->has_pending_keys() && IsNigoriMigratedToKeystore(nigori) &&
!nigori.keystore_decryptor_token().blob().empty()) {
// If the nigori is already migrated and we have pending keys, we might
// be able to decrypt them using either the keystore decryptor token
// or the existing keystore keys.
DecryptPendingKeysWithKeystoreKey(nigori.keystore_decryptor_token(),
cryptographer);
}
// Note that triggering migration will have no effect if we're already
// properly migrated with the newest keystore keys.
if (GetMigrationReason(nigori, *cryptographer, GetPassphraseType(&trans)) !=
NigoriMigrationReason::kNoReason) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&SyncEncryptionHandlerImpl::RewriteNigori,
weak_ptr_factory_.GetWeakPtr(),
NigoriMigrationTrigger::kSetKeystoreKeys));
}
return true;
}
const Cryptographer* SyncEncryptionHandlerImpl::GetCryptographer(
const syncable::BaseTransaction* const trans) const {
return &UnlockVault(trans).cryptographer;
}
const DirectoryCryptographer*
SyncEncryptionHandlerImpl::GetDirectoryCryptographer(
const syncable::BaseTransaction* const trans) const {
return &UnlockVault(trans).cryptographer;
}
ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypes(
const syncable::BaseTransaction* const trans) const {
return UnlockVault(trans).encrypted_types;
}
PassphraseType SyncEncryptionHandlerImpl::GetPassphraseType(
const syncable::BaseTransaction* const trans) const {
return UnlockVault(trans).passphrase_type;
}
ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypesUnsafe() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return vault_unsafe_.encrypted_types;
}
bool SyncEncryptionHandlerImpl::MigratedToKeystore() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ReadTransaction trans(FROM_HERE, user_share_);
ReadNode nigori_node(&trans);
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return false;
return IsNigoriMigratedToKeystore(nigori_node.GetNigoriSpecifics());
}
base::Time SyncEncryptionHandlerImpl::custom_passphrase_time() const {
return custom_passphrase_time_;
}
void SyncEncryptionHandlerImpl::RestoreNigoriForTesting(
const sync_pb::NigoriSpecifics& nigori_specifics) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
// Verify we don't already have a nigori node.
WriteNode nigori_node(&trans);
BaseNode::InitByLookupResult init_result = nigori_node.InitTypeRoot(NIGORI);
DCHECK(init_result == BaseNode::INIT_FAILED_ENTRY_NOT_GOOD);
// Create one.
syncable::ModelNeutralMutableEntry model_neutral_mutable_entry(
trans.GetWrappedWriteTrans(), syncable::CREATE_NEW_TYPE_ROOT, NIGORI);
DCHECK(model_neutral_mutable_entry.good());
model_neutral_mutable_entry.PutServerIsDir(true);
model_neutral_mutable_entry.PutUniqueServerTag(ModelTypeToRootTag(NIGORI));
model_neutral_mutable_entry.PutIsUnsynced(true);
// Update it with the saved nigori specifics.
syncable::MutableEntry mutable_entry(trans.GetWrappedWriteTrans(),
syncable::GET_TYPE_ROOT, NIGORI);
DCHECK(mutable_entry.good());
sync_pb::EntitySpecifics specifics;
*specifics.mutable_nigori() = nigori_specifics;
mutable_entry.PutSpecifics(specifics);
// Update our state based on the saved nigori node.
ApplyNigoriUpdate(nigori_specifics, trans.GetWrappedTrans());
}
DirectoryCryptographer*
SyncEncryptionHandlerImpl::GetMutableCryptographerForTesting() {
return &vault_unsafe_.cryptographer;
}
// This function iterates over all encrypted types. There are many scenarios in
// which data for some or all types is not currently available. In that case,
// the lookup of the root node will fail and we will skip encryption for that
// type.
void SyncEncryptionHandlerImpl::ReEncryptEverything(WriteTransaction* trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(UnlockVault(trans->GetWrappedTrans()).cryptographer.CanEncrypt());
for (ModelType type : UnlockVault(trans->GetWrappedTrans()).encrypted_types) {
if (type == PASSWORDS || IsControlType(type))
continue; // These types handle encryption differently.
ReadNode type_root(trans);
if (type_root.InitTypeRoot(type) != BaseNode::INIT_OK)
continue; // Don't try to reencrypt if the type's data is unavailable.
// Iterate through all children of this datatype.
base::queue<int64_t> to_visit;
int64_t child_id = type_root.GetFirstChildId();
to_visit.push(child_id);
while (!to_visit.empty()) {
child_id = to_visit.front();
to_visit.pop();
if (child_id == kInvalidId)
continue;
WriteNode child(trans);
if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
continue; // Possible for locally deleted items.
if (child.GetIsFolder()) {
to_visit.push(child.GetFirstChildId());
}
if (!child.GetIsPermanentFolder()) {
// Rewrite the specifics of the node with encrypted data if necessary
// (only rewrite the non-unique folders).
child.ResetFromSpecifics();
}
to_visit.push(child.GetSuccessorId());
}
}
// Passwords are encrypted with their own legacy scheme. Passwords are always
// encrypted so we don't need to check GetEncryptedTypes() here.
ReadNode passwords_root(trans);
if (passwords_root.InitTypeRoot(PASSWORDS) == BaseNode::INIT_OK) {
int64_t child_id = passwords_root.GetFirstChildId();
while (child_id != kInvalidId) {
WriteNode child(trans);
if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
break; // Possible if we failed to decrypt the data for some reason.
child.SetPasswordSpecifics(child.GetPasswordSpecifics());
child_id = child.GetSuccessorId();
}
}
DVLOG(1) << "Re-encrypt everything complete.";
// NOTE: We notify from within a transaction.
for (auto& observer : observers_) {
observer.OnEncryptionComplete();
}
}
SyncEncryptionHandlerImpl::ApplyNigoriUpdateResult
SyncEncryptionHandlerImpl::ApplyNigoriUpdateImpl(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const base::Optional<PassphraseType> nigori_passphrase_type_optional =
ProtoPassphraseInt32ToEnum(nigori.passphrase_type());
if (!nigori_passphrase_type_optional) {
DVLOG(1) << "Ignoring nigori node update with unknown passphrase type.";
return ApplyNigoriUpdateResult::kUnsupportedRemoteState;
}
const PassphraseType nigori_passphrase_type =
*nigori_passphrase_type_optional;
if (nigori_passphrase_type == PassphraseType::kTrustedVaultPassphrase) {
NOTIMPLEMENTED();
return ApplyNigoriUpdateResult::kUnsupportedRemoteState;
}
DVLOG(1) << "Applying nigori node update.";
bool nigori_types_need_update =
!UpdateEncryptedTypesFromNigori(nigori, trans);
if (nigori.custom_passphrase_time() != 0) {
custom_passphrase_time_ = ProtoTimeToTime(nigori.custom_passphrase_time());
}
bool is_nigori_migrated = IsNigoriMigratedToKeystore(nigori);
PassphraseType* passphrase_type = &UnlockVaultMutable(trans)->passphrase_type;
if (is_nigori_migrated) {
keystore_migration_time_ =
ProtoTimeToTime(nigori.keystore_migration_time());
// Only update the local passphrase state if it's a valid transition:
// - implicit -> keystore
// - implicit -> frozen implicit
// - implicit -> custom
// - keystore -> custom
// Note: frozen implicit -> custom is not technically a valid transition,
// but we let it through here as well in case future versions do add support
// for this transition.
if (*passphrase_type != nigori_passphrase_type &&
nigori_passphrase_type != PassphraseType::kImplicitPassphrase &&
(*passphrase_type == PassphraseType::kImplicitPassphrase ||
nigori_passphrase_type == PassphraseType::kCustomPassphrase)) {
DVLOG(1) << "Changing passphrase state from "
<< PassphraseTypeToString(*passphrase_type) << " to "
<< PassphraseTypeToString(nigori_passphrase_type);
*passphrase_type = nigori_passphrase_type;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
if (*passphrase_type == PassphraseType::kKeystorePassphrase &&
encrypt_everything_) {
// This is the case where another client that didn't support keystore
// encryption attempted to enable full encryption. We detect it
// and switch the passphrase type to frozen implicit passphrase instead
// due to full encryption not being compatible with keystore passphrase.
// Because the local passphrase type will not match the nigori passphrase
// type, we will trigger a rewrite and subsequently a re-migration.
DVLOG(1) << "Changing passphrase state to FROZEN_IMPLICIT_PASSPHRASE "
<< "due to full encryption.";
*passphrase_type = PassphraseType::kFrozenImplicitPassphrase;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
} else {
// It's possible that while we're waiting for migration a client that does
// not have keystore encryption enabled switches to a custom passphrase.
if (nigori.keybag_is_frozen() &&
*passphrase_type != PassphraseType::kCustomPassphrase) {
*passphrase_type = PassphraseType::kCustomPassphrase;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans)->cryptographer;
bool nigori_needs_new_keys = false;
if (!nigori.encryption_keybag().blob().empty()) {
// We only update the default key if this was a new explicit passphrase.
// Else, since it was decryptable, it must not have been a new key.
bool need_new_default_key = false;
if (is_nigori_migrated) {
need_new_default_key = IsExplicitPassphrase(nigori_passphrase_type);
} else {
need_new_default_key = nigori.keybag_is_frozen();
}
if (!AttemptToInstallKeybag(nigori.encryption_keybag(),
need_new_default_key, cryptographer)) {
// Check to see if we can decrypt the keybag using the keystore decryptor
// token.
cryptographer->SetPendingKeys(nigori.encryption_keybag());
if (!nigori.keystore_decryptor_token().blob().empty() &&
!keystore_key_.empty()) {
if (DecryptPendingKeysWithKeystoreKey(nigori.keystore_decryptor_token(),
cryptographer)) {
nigori_needs_new_keys =
cryptographer->KeybagIsStale(nigori.encryption_keybag());
} else {
LOG(ERROR) << "Failed to decrypt pending keys using keystore "
<< "bootstrap key.";
}
}
} else {
// Keybag was installed. We write back our local keybag into the nigori
// node if the nigori node's keybag either contains less keys or
// has a different default key.
nigori_needs_new_keys =
cryptographer->KeybagIsStale(nigori.encryption_keybag());
}
} else {
// The nigori node has an empty encryption keybag. Attempt to write our
// local encryption keys into it.
LOG(WARNING) << "Nigori had empty encryption keybag.";
nigori_needs_new_keys = true;
}
// If the method is not CUSTOM_PASSPHRASE, we will fall back to PBKDF2 to be
// backwards compatible.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (*passphrase_type == PassphraseType::kCustomPassphrase) {
key_derivation_params = GetKeyDerivationParamsFromNigori(nigori);
if (key_derivation_params.method() == KeyDerivationMethod::UNSUPPORTED) {
DLOG(WARNING) << "Updating from a Nigori node with an unsupported key "
"derivation method.";
}
custom_passphrase_key_derivation_params_ = key_derivation_params;
}
// If we've completed a sync cycle and the cryptographer isn't ready
// yet or has pending keys, prompt the user for a passphrase.
if (cryptographer->has_pending_keys()) {
DVLOG(1) << "OnPassphraseRequired Sent";
sync_pb::EncryptedData pending_keys = cryptographer->GetPendingKeys();
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_DECRYPTION, key_derivation_params,
pending_keys);
}
} else if (!cryptographer->CanEncrypt()) {
DVLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
<< "ready";
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_ENCRYPTION, key_derivation_params,
sync_pb::EncryptedData());
}
}
// Check if the current local encryption state is stricter/newer than the
// nigori state. If so, we need to overwrite the nigori node with the local
// state.
bool passphrase_type_matches = true;
if (!is_nigori_migrated) {
DCHECK(*passphrase_type == PassphraseType::kCustomPassphrase ||
*passphrase_type == PassphraseType::kImplicitPassphrase);
passphrase_type_matches =
nigori.keybag_is_frozen() == IsExplicitPassphrase(*passphrase_type);
} else {
passphrase_type_matches = (nigori_passphrase_type == *passphrase_type);
}
if (!passphrase_type_matches ||
nigori.encrypt_everything() != encrypt_everything_ ||
nigori_types_need_update || nigori_needs_new_keys) {
DVLOG(1) << "Triggering nigori rewrite.";
return ApplyNigoriUpdateResult::kRemoteMustBeCorrected;
}
return ApplyNigoriUpdateResult::kSuccess;
}
void SyncEncryptionHandlerImpl::RewriteNigori(
NigoriMigrationTrigger migration_trigger) {
DVLOG(1) << "Writing local encryption state into nigori.";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
WriteEncryptionStateToNigori(&trans, migration_trigger);
}
void SyncEncryptionHandlerImpl::WriteEncryptionStateToNigori(
WriteTransaction* trans,
NigoriMigrationTrigger migration_trigger) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteNode nigori_node(trans);
// This can happen in tests that don't have nigori nodes.
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return;
sync_pb::NigoriSpecifics nigori = nigori_node.GetNigoriSpecifics();
const DirectoryCryptographer& cryptographer =
UnlockVault(trans->GetWrappedTrans()).cryptographer;
// Will not do anything if we shouldn't or can't migrate. Otherwise
// migrates, writing the full encryption state as it does.
if (!AttemptToMigrateNigoriToKeystore(trans, &nigori_node,
migration_trigger)) {
if (cryptographer.CanEncrypt() &&
nigori_overwrite_count_ < kNigoriOverwriteLimit) {
// Does not modify the encrypted blob if the unencrypted data already
// matches what is about to be written.
sync_pb::EncryptedData original_keys = nigori.encryption_keybag();
if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
NOTREACHED();
if (nigori.encryption_keybag().SerializeAsString() !=
original_keys.SerializeAsString()) {
// We've updated the nigori node's encryption keys. In order to prevent
// a possible looping of two clients constantly overwriting each other,
// we limit the absolute number of overwrites per client instantiation.
nigori_overwrite_count_++;
UMA_HISTOGRAM_COUNTS_1M("Sync.AutoNigoriOverwrites",
nigori_overwrite_count_);
}
// Note: we don't try to set keybag_is_frozen here since if that
// is lost the user can always set it again (and we don't want to clobber
// any migration state). The main goal at this point is to preserve
// the encryption keys so all data remains decryptable.
}
syncable::UpdateNigoriFromEncryptedTypes(
UnlockVault(trans->GetWrappedTrans()).encrypted_types,
encrypt_everything_, &nigori);
if (!custom_passphrase_time_.is_null()) {
nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
// If nothing has changed, this is a no-op.
nigori_node.SetNigoriSpecifics(nigori);
}
}
bool SyncEncryptionHandlerImpl::UpdateEncryptedTypesFromNigori(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (nigori.encrypt_everything()) {
EnableEncryptEverythingImpl(trans);
DCHECK(*encrypted_types == EncryptableUserTypes());
return true;
} else if (encrypt_everything_) {
DCHECK(*encrypted_types == EncryptableUserTypes());
return false;
}
ModelTypeSet nigori_encrypted_types;
nigori_encrypted_types = syncable::GetEncryptedTypesFromNigori(nigori);
nigori_encrypted_types.PutAll(AlwaysEncryptedUserTypes());
// If anything more than the sensitive types were encrypted, and
// encrypt_everything is not explicitly set to false, we assume it means
// a client intended to enable encrypt everything.
if (!nigori.has_encrypt_everything() &&
!Difference(nigori_encrypted_types, AlwaysEncryptedUserTypes()).Empty()) {
if (!encrypt_everything_) {
encrypt_everything_ = true;
*encrypted_types = EncryptableUserTypes();
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
DCHECK(*encrypted_types == EncryptableUserTypes());
return false;
}
MergeEncryptedTypes(nigori_encrypted_types, trans);
return *encrypted_types == nigori_encrypted_types;
}
void SyncEncryptionHandlerImpl::
ReplaceImplicitKeyDerivationMethodInNigoriWithTransaction() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
ReplaceImplicitKeyDerivationMethodInNigori(&trans);
}
void SyncEncryptionHandlerImpl::ReplaceImplicitKeyDerivationMethodInNigori(
WriteTransaction* trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(trans);
WriteNode nigori_node(trans);
// This can happen in tests that don't have nigori nodes.
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return;
if (!ShouldSetExplicitCustomPassphraseKeyDerivationMethod(
nigori_node.GetNigoriSpecifics())) {
// Nothing to do; an explicit method is already set.
return;
}
DVLOG(1) << "Writing explicit custom passphrase key derivation method to "
"Nigori node, since none was set.";
// UNSPECIFIED as custom_passphrase_key_derivation_method in Nigori implies
// PBKDF2.
sync_pb::NigoriSpecifics specifics = nigori_node.GetNigoriSpecifics();
UpdateNigoriSpecificsKeyDerivationParams(
KeyDerivationParams::CreateForPbkdf2(), &specifics);
nigori_node.SetNigoriSpecifics(specifics);
}
void SyncEncryptionHandlerImpl::SetCustomPassphrase(
const std::string& passphrase,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(IsNigoriMigratedToKeystore(nigori_node->GetNigoriSpecifics()));
KeyDerivationParams key_derivation_params =
CreateKeyDerivationParamsForCustomPassphrase(random_salt_generator_);
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto.CustomPassphraseKeyDerivationMethodOnNewPassphrase",
GetKeyDerivationMethodStateForMetrics(key_derivation_params));
KeyParams key_params = {key_derivation_params, passphrase};
if (GetPassphraseType(trans->GetWrappedTrans()) !=
PassphraseType::kKeystorePassphrase) {
DVLOG(1) << "Failing to set a custom passphrase because one has already "
<< "been set.";
FinishSetPassphrase(false, std::string(), trans, nigori_node);
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
if (cryptographer->has_pending_keys()) {
// This theoretically shouldn't happen, because the only way to have pending
// keys after migrating to keystore support is if a custom passphrase was
// set, which should update passpshrase_state_ and should be caught by the
// if statement above. For the sake of safety though, we check for it in
// case a client is misbehaving.
LOG(ERROR) << "Failing to set custom passphrase because of pending keys.";
FinishSetPassphrase(false, std::string(), trans, nigori_node);
return;
}
std::string bootstrap_token;
if (!cryptographer->AddKey(key_params)) {
NOTREACHED() << "Failed to add key to cryptographer.";
return;
}
DVLOG(1) << "Setting custom passphrase with key derivation method "
<< KeyDerivationMethodToString(key_derivation_params.method());
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans->GetWrappedTrans())->passphrase_type;
*passphrase_type = PassphraseType::kCustomPassphrase;
custom_passphrase_key_derivation_params_ = key_derivation_params;
custom_passphrase_time_ = base::Time::Now();
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
FinishSetPassphrase(true, bootstrap_token, trans, nigori_node);
}
void SyncEncryptionHandlerImpl::NotifyObserversOfLocalCustomPassphrase(
WriteTransaction* trans) {
WriteNode nigori_node(trans);
BaseNode::InitByLookupResult init_result = nigori_node.InitTypeRoot(NIGORI);
DCHECK_EQ(init_result, BaseNode::INIT_OK);
sync_pb::NigoriSpecifics nigori_specifics = nigori_node.GetNigoriSpecifics();
DCHECK(nigori_specifics.passphrase_type() ==
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE ||
nigori_specifics.passphrase_type() ==
sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE);
for (auto& observer : observers_) {
observer.OnLocalSetPassphraseEncryption(nigori_specifics);
}
}
void SyncEncryptionHandlerImpl::DecryptPendingKeysWithExplicitPassphrase(
const std::string& passphrase,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
PassphraseType passphrase_type = GetPassphraseType(trans->GetWrappedTrans());
DCHECK(IsExplicitPassphrase(passphrase_type));
// If the method is not CUSTOM_PASSPHRASE, we will fall back to PBKDF2 to be
// backwards compatible.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
DCHECK_NE(custom_passphrase_key_derivation_params_->method(),
KeyDerivationMethod::UNSUPPORTED);
key_derivation_params = custom_passphrase_key_derivation_params_.value();
}
KeyParams key_params = {key_derivation_params, passphrase};
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
if (!cryptographer->has_pending_keys()) {
// Note that this *can* happen in a rare situation where data is
// re-encrypted on another client while a SetDecryptionPassphrase() call is
// in-flight on this client. It is rare enough that we choose to do nothing.
NOTREACHED() << "Attempt to set decryption passphrase failed because there "
<< "were no pending keys.";
return;
}
bool success = false;
std::string bootstrap_token;
if (cryptographer->DecryptPendingKeys(key_params)) {
DVLOG(1) << "Explicit passphrase accepted for decryption.";
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto."
"CustomPassphraseKeyDerivationMethodOnSuccessfulDecryption",
GetKeyDerivationMethodStateForMetrics(
custom_passphrase_key_derivation_params_));
}
} else {
DVLOG(1) << "Explicit passphrase failed to decrypt.";
success = false;
}
if (success && !keystore_key_.empty()) {
// Should already be part of the encryption keybag, but we add it just
// in case. Note that, since this is a keystore key, we always use PBKDF2
// for key derivation.
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
cryptographer->AddNonDefaultKey(key_params);
}
FinishSetPassphrase(success, bootstrap_token, trans, nigori_node);
}
void SyncEncryptionHandlerImpl::FinishSetPassphrase(
bool success,
const std::string& bootstrap_token,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer,
UnlockVault(trans->GetWrappedTrans()).cryptographer.has_pending_keys());
}
// It's possible we need to change the bootstrap token even if we failed to
// set the passphrase (for example if we need to preserve the new GAIA
// passphrase).
if (!bootstrap_token.empty()) {
DVLOG(1) << "Passphrase bootstrap token updated.";
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(bootstrap_token,
PASSPHRASE_BOOTSTRAP_TOKEN);
}
}
const DirectoryCryptographer& cryptographer =
UnlockVault(trans->GetWrappedTrans()).cryptographer;
if (!success) {
// If we have not set an explicit method, fall back to PBKDF2 to ensure
// backwards compatibility.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (custom_passphrase_key_derivation_params_.has_value()) {
DCHECK_EQ(GetPassphraseType(trans->GetWrappedTrans()),
PassphraseType::kCustomPassphrase);
key_derivation_params = custom_passphrase_key_derivation_params_.value();
}
if (cryptographer.CanEncrypt()) {
LOG(ERROR) << "Attempt to change passphrase failed while cryptographer "
<< "was ready.";
} else if (cryptographer.has_pending_keys()) {
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_DECRYPTION, key_derivation_params,
cryptographer.GetPendingKeys());
}
} else {
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_ENCRYPTION, key_derivation_params,
sync_pb::EncryptedData());
}
}
return;
}
DCHECK(success);
DCHECK(cryptographer.CanEncrypt());
// Will do nothing if we're already properly migrated or unable to migrate
// (in otherwords, if GetMigrationReason returns kNoReason).
// Otherwise will update the nigori node with the current migrated state,
// writing all encryption state as it does.
if (!AttemptToMigrateNigoriToKeystore(
trans, nigori_node, NigoriMigrationTrigger::kFinishSetPassphrase)) {
sync_pb::NigoriSpecifics nigori(nigori_node->GetNigoriSpecifics());
// Does not modify nigori.encryption_keybag() if the original decrypted
// data was the same.
if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
NOTREACHED();
if (IsNigoriMigratedToKeystore(nigori)) {
DCHECK(keystore_key_.empty() ||
IsExplicitPassphrase(GetPassphraseType(trans->GetWrappedTrans())));
DVLOG(1) << "Leaving nigori migration state untouched after setting"
<< " passphrase.";
} else {
nigori.set_keybag_is_frozen(
IsExplicitPassphrase(GetPassphraseType(trans->GetWrappedTrans())));
}
// If we set a new custom passphrase, store the timestamp.
if (!custom_passphrase_time_.is_null()) {
nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
nigori_node->SetNigoriSpecifics(nigori);
}
PassphraseType passphrase_type = GetPassphraseType(trans->GetWrappedTrans());
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DVLOG(1) << "Successfully set passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " with key derivation method "
<< KeyDerivationMethodToString(
custom_passphrase_key_derivation_params_.value().method())
<< ".";
} else {
DVLOG(1) << "Successfully set passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " implicitly using old key derivation method.";
}
// Must do this after OnPassphraseTypeChanged, in order to ensure the PSS
// checks the passphrase state after it has been set.
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
// Does nothing if everything is already encrypted.
// TODO(zea): If we just migrated and enabled encryption, this will be
// redundant. Figure out a way to not do this unnecessarily.
ReEncryptEverything(trans);
}
void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
ModelTypeSet new_encrypted_types,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Only UserTypes may be encrypted.
DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types));
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (!encrypted_types->HasAll(new_encrypted_types)) {
*encrypted_types = new_encrypted_types;
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
}
SyncEncryptionHandlerImpl::Vault* SyncEncryptionHandlerImpl::UnlockVaultMutable(
const syncable::BaseTransaction* const trans) {
DCHECK_EQ(user_share_->directory.get(), trans->directory());
return &vault_unsafe_;
}
const SyncEncryptionHandlerImpl::Vault& SyncEncryptionHandlerImpl::UnlockVault(
const syncable::BaseTransaction* const trans) const {
DCHECK_EQ(user_share_->directory.get(), trans->directory());
return vault_unsafe_;
}
SyncEncryptionHandlerImpl::NigoriMigrationReason
SyncEncryptionHandlerImpl::GetMigrationReason(
const sync_pb::NigoriSpecifics& nigori,
const DirectoryCryptographer& cryptographer,
PassphraseType passphrase_type) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Don't migrate if there are pending encryption keys (because data
// encrypted with the pending keys will not be decryptable).
if (cryptographer.has_pending_keys())
return NigoriMigrationReason::kNoReason;
if (!IsNigoriMigratedToKeystore(nigori)) {
if (keystore_key_.empty()) {
// If we haven't already migrated, we don't want to do anything unless
// a keystore key is available (so that those clients without keystore
// encryption enabled aren't forced into new states, e.g. frozen implicit
// passphrase).
return NigoriMigrationReason::kNoReason;
}
if (nigori.encryption_keybag().blob().empty()) {
return NigoriMigrationReason::kInitialization;
}
return NigoriMigrationReason::KNigoriNotMigrated;
}
// If the nigori is already migrated but does not reflect the explicit
// passphrase state, remigrate. Similarly, if the nigori has an explicit
// passphrase but does not have full encryption, or the nigori has an
// implicit passphrase but does have full encryption, re-migrate.
// Note that this is to defend against other clients without keystore
// encryption enabled transitioning to states that are no longer valid.
if (passphrase_type != PassphraseType::kKeystorePassphrase &&
nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
return NigoriMigrationReason::kOldPassphraseType;
}
if (IsExplicitPassphrase(passphrase_type) && !encrypt_everything_) {
return NigoriMigrationReason::kNotEncryptEverythingWithExplicitPassphrase;
}
if (passphrase_type == PassphraseType::kKeystorePassphrase &&
encrypt_everything_) {
return NigoriMigrationReason::kEncryptEverythingWithKeystorePassphrase;
}
if (cryptographer.CanEncrypt() &&
!cryptographer.CanDecryptUsingDefaultKey(nigori.encryption_keybag())) {
// We need to overwrite the keybag. This might involve overwriting the
// keystore decryptor too.
return NigoriMigrationReason::kCannotDecryptUsingDefaultKey;
}
if (old_keystore_keys_.size() > 0 && !keystore_key_.empty()) {
// Check to see if a server key rotation has happened, but the nigori
// node's keys haven't been rotated yet, and hence we should re-migrate.
// Note that once a key rotation has been performed, we no longer
// preserve backwards compatibility, and the keybag will therefore be
// encrypted with the current keystore key.
DirectoryCryptographer temp_cryptographer;
KeyParams keystore_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
temp_cryptographer.AddKey(keystore_params);
if (!temp_cryptographer.CanDecryptUsingDefaultKey(
nigori.encryption_keybag())) {
return NigoriMigrationReason::kServerKeyRotation;
}
}
return NigoriMigrationReason::kNoReason;
}
bool SyncEncryptionHandlerImpl::AttemptToMigrateNigoriToKeystore(
WriteTransaction* trans,
WriteNode* nigori_node,
NigoriMigrationTrigger migration_trigger) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const sync_pb::NigoriSpecifics& old_nigori =
nigori_node->GetNigoriSpecifics();
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans->GetWrappedTrans())->passphrase_type;
NigoriMigrationReason migration_reason =
GetMigrationReason(old_nigori, *cryptographer, *passphrase_type);
if (migration_reason == NigoriMigrationReason::kNoReason)
return false;
migration_attempted_ = true;
DVLOG(1) << "Starting nigori migration to keystore support.";
sync_pb::NigoriSpecifics migrated_nigori(old_nigori);
PassphraseType new_passphrase_type =
GetPassphraseType(trans->GetWrappedTrans());
bool new_encrypt_everything = encrypt_everything_;
if (encrypt_everything_ && !IsExplicitPassphrase(*passphrase_type)) {
DVLOG(1) << "Switching to frozen implicit passphrase due to already having "
<< "full encryption.";
new_passphrase_type = PassphraseType::kFrozenImplicitPassphrase;
migrated_nigori.clear_keystore_decryptor_token();
} else if (IsExplicitPassphrase(*passphrase_type)) {
DVLOG_IF(1, !encrypt_everything_) << "Enabling encrypt everything due to "
<< "explicit passphrase";
new_encrypt_everything = true;
migrated_nigori.clear_keystore_decryptor_token();
} else {
DCHECK(!encrypt_everything_);
new_passphrase_type = PassphraseType::kKeystorePassphrase;
DVLOG(1) << "Switching to keystore passphrase state.";
}
migrated_nigori.set_encrypt_everything(new_encrypt_everything);
migrated_nigori.set_passphrase_type(
EnumPassphraseTypeToProto(new_passphrase_type));
if (new_passphrase_type == PassphraseType::kCustomPassphrase) {
if (!custom_passphrase_key_derivation_params_.has_value()) {
// We ended up in a CUSTOM_PASSPHRASE state, but we went through neither
// SetCustomPassphrase() nor SetDecryptionPassphrase()'s
// "already-migrated" path, which are the only places where
// custom_passphrase_key_derivation_params_ is set. Therefore, we must
// have reached this state by, for example, being updated to
// CUSTOM_PASSPHRASE because the keybag was frozen. In these cases, we
// will fall back to PBKDF2 to ensure backwards compatibility.
custom_passphrase_key_derivation_params_ =
KeyDerivationParams::CreateForPbkdf2();
}
UpdateNigoriSpecificsKeyDerivationParams(
custom_passphrase_key_derivation_params_.value(), &migrated_nigori);
}
migrated_nigori.set_keybag_is_frozen(true);
if (!keystore_key_.empty()) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
if ((old_keystore_keys_.size() > 0 &&
new_passphrase_type == PassphraseType::kKeystorePassphrase) ||
!cryptographer->is_initialized()) {
// Either at least one key rotation has been performed, so we no longer
// care about backwards compatibility, or we're generating keystore-based
// encryption keys without knowing the GAIA password (and therefore the
// cryptographer is not initialized), so we can't support backwards
// compatibility. Ensure the keystore key is the default key.
DVLOG(1) << "Migrating keybag to keystore key.";
bool cryptographer_was_ready = cryptographer->CanEncrypt();
if (!cryptographer->AddKey(key_params)) {
LOG(ERROR) << "Failed to add keystore key as default key";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_SET_DEFAULT_KEYSTORE,
MIGRATION_RESULT_SIZE);
return false;
}
if (!cryptographer_was_ready && cryptographer->CanEncrypt()) {
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
}
} else {
// We're in backwards compatible mode -- either the account has an
// explicit passphrase, or we want to preserve the current GAIA-based key
// as the default because we can (there have been no key rotations since
// the migration).
DVLOG(1) << "Migrating keybag while preserving old key";
if (!cryptographer->AddNonDefaultKey(key_params)) {
LOG(ERROR) << "Failed to add keystore key as non-default key.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_SET_NONDEFAULT_KEYSTORE,
MIGRATION_RESULT_SIZE);
return false;
}
}
}
if (!old_keystore_keys_.empty()) {
// Go through and add all the old keystore keys as non default keys, so
// they'll be preserved in the encryption_keybag when we next write the
// nigori node.
for (std::vector<std::string>::const_iterator iter =
old_keystore_keys_.begin();
iter != old_keystore_keys_.end(); ++iter) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), *iter};
cryptographer->AddNonDefaultKey(key_params);
}
}
if (new_passphrase_type == PassphraseType::kKeystorePassphrase &&
!GetKeystoreDecryptor(
*cryptographer, keystore_key_,
migrated_nigori.mutable_keystore_decryptor_token())) {
LOG(ERROR) << "Failed to extract keystore decryptor token.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_EXTRACT_DECRYPTOR,
MIGRATION_RESULT_SIZE);
return false;
}
if (!cryptographer->GetKeys(migrated_nigori.mutable_encryption_keybag())) {
LOG(ERROR) << "Failed to extract encryption keybag.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_EXTRACT_KEYBAG, MIGRATION_RESULT_SIZE);
return false;
}
if (keystore_migration_time_.is_null()) {
keystore_migration_time_ = base::Time::Now();
}
migrated_nigori.set_keystore_migration_time(
TimeToProtoTime(keystore_migration_time_));
if (!custom_passphrase_time_.is_null()) {
migrated_nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(cryptographer,
cryptographer->has_pending_keys());
}
if (*passphrase_type != new_passphrase_type) {
*passphrase_type = new_passphrase_type;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
if (new_encrypt_everything && !encrypt_everything_) {
EnableEncryptEverythingImpl(trans->GetWrappedTrans());
ReEncryptEverything(trans);
} else if (!cryptographer->CanDecryptUsingDefaultKey(
old_nigori.encryption_keybag())) {
DVLOG(1) << "Rencrypting everything due to key rotation.";
ReEncryptEverything(trans);
}
DVLOG(1) << "Completing nigori migration to keystore support.";
nigori_node->SetNigoriSpecifics(migrated_nigori);
if (new_encrypt_everything &&
(new_passphrase_type == PassphraseType::kFrozenImplicitPassphrase ||
new_passphrase_type == PassphraseType::kCustomPassphrase)) {
NotifyObserversOfLocalCustomPassphrase(trans);
}
switch (new_passphrase_type) {
case PassphraseType::kKeystorePassphrase:
if (old_keystore_keys_.size() > 0) {
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
MIGRATION_RESULT_SIZE);
} else {
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
MIGRATION_RESULT_SIZE);
}
break;
case PassphraseType::kFrozenImplicitPassphrase:
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_FROZEN_IMPLICIT,
MIGRATION_RESULT_SIZE);
break;
case PassphraseType::kCustomPassphrase:
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_CUSTOM,
MIGRATION_RESULT_SIZE);
break;
default:
NOTREACHED();
break;
}
return true;
}
bool SyncEncryptionHandlerImpl::GetKeystoreDecryptor(
const DirectoryCryptographer& cryptographer,
const std::string& keystore_key,
sync_pb::EncryptedData* encrypted_blob) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!keystore_key.empty());
DCHECK(cryptographer.CanEncrypt());
std::string serialized_nigori;
serialized_nigori = cryptographer.GetDefaultNigoriKeyData();
if (serialized_nigori.empty()) {
LOG(ERROR) << "Failed to get cryptographer bootstrap token.";
return false;
}
DirectoryCryptographer temp_cryptographer;
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), keystore_key};
if (!temp_cryptographer.AddKey(key_params))
return false;
if (!temp_cryptographer.EncryptString(serialized_nigori, encrypted_blob))
return false;
return true;
}
bool SyncEncryptionHandlerImpl::AttemptToInstallKeybag(
const sync_pb::EncryptedData& keybag,
bool update_default,
DirectoryCryptographer* cryptographer) {
if (!cryptographer->CanDecrypt(keybag))
return false;
cryptographer->InstallKeys(keybag);
if (update_default)
cryptographer->SetDefaultKey(keybag.key_name());
return true;
}
void SyncEncryptionHandlerImpl::EnableEncryptEverythingImpl(
syncable::BaseTransaction* const trans) {
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (encrypt_everything_) {
DCHECK_EQ(EncryptableUserTypes(), *encrypted_types);
return;
}
encrypt_everything_ = true;
*encrypted_types = EncryptableUserTypes();
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
bool SyncEncryptionHandlerImpl::DecryptPendingKeysWithKeystoreKey(
const sync_pb::EncryptedData& keystore_decryptor_token,
DirectoryCryptographer* cryptographer) {
DCHECK(cryptographer->has_pending_keys());
if (keystore_decryptor_token.blob().empty())
return false;
DirectoryCryptographer temp_cryptographer;
// First, go through and all all the old keystore keys to the temporary
// cryptographer.
for (size_t i = 0; i < old_keystore_keys_.size(); ++i) {
KeyParams old_key_params = {KeyDerivationParams::CreateForPbkdf2(),
old_keystore_keys_[i]};
temp_cryptographer.AddKey(old_key_params);
}
// Then add the current keystore key as the default key and see if we can
// decrypt.
KeyParams keystore_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
if (temp_cryptographer.AddKey(keystore_params) &&
temp_cryptographer.CanDecrypt(keystore_decryptor_token)) {
// Someone else migrated the nigori for us! How generous! Go ahead and
// install both the keystore key and the new default encryption key
// (i.e. the one provided by the keystore decryptor token) into the
// cryptographer.
// The keystore decryptor token is a keystore key encrypted blob containing
// the current serialized default encryption key (and as such should be
// able to decrypt the nigori node's encryption keybag).
// Note: it's possible a key rotation has happened since the migration, and
// we're decrypting using an old keystore key. In that case we need to
// ensure we re-encrypt using the newest key.
DVLOG(1) << "Attempting to decrypt pending keys using "
<< "keystore decryptor token.";
std::string serialized_nigori;
// TODO(crbug.com/908391): what if the decryption below fails?
temp_cryptographer.DecryptToString(keystore_decryptor_token,
&serialized_nigori);
// This will decrypt the pending keys and add them if possible. The key
// within |serialized_nigori| will be the default after.
cryptographer->ImportNigoriKey(serialized_nigori);
if (!temp_cryptographer.CanDecryptUsingDefaultKey(
keystore_decryptor_token)) {
// The keystore decryptor token was derived from an old keystore key.
// A key rotation is necessary, so set the current keystore key as the
// default key (which will trigger a re-migration).
DVLOG(1) << "Pending keys based on old keystore key. Setting newest "
<< "keystore key as default.";
cryptographer->AddKey(keystore_params);
} else {
// Theoretically the encryption keybag should already contain the keystore
// key. We explicitly add it as a safety measure.
DVLOG(1) << "Pending keys based on newest keystore key.";
cryptographer->AddNonDefaultKey(keystore_params);
}
if (cryptographer->CanEncrypt()) {
std::string bootstrap_token;
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
DVLOG(1) << "Keystore decryptor token decrypted pending keys.";
// Note: These are separate loops to match previous functionality and not
// out of explicit knowledge that they must be.
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(bootstrap_token,
PASSPHRASE_BOOTSTRAP_TOKEN);
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(cryptographer,
cryptographer->has_pending_keys());
}
return true;
}
}
return false;
}
base::Time SyncEncryptionHandlerImpl::GetExplicitPassphraseTime(
PassphraseType passphrase_type) const {
if (passphrase_type == PassphraseType::kFrozenImplicitPassphrase)
return GetKeystoreMigrationTime();
else if (passphrase_type == PassphraseType::kCustomPassphrase)
return custom_passphrase_time();
return base::Time();
}
} // namespace syncer
| 86,479 | 27,557 |
#include "Internationalizator.h"
#ifdef _WIN32
#pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable:4996 4251 4275 4800)
#endif
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#ifdef _WIN32
#pragma warning(pop)
#endif
using namespace std;
using boost::recursive_mutex;
using boost::lock_guard;
namespace charliesoft
{
recursive_mutex _internationalizatorMutex;
Internationalizator *Internationalizator::ptr = NULL;
boost::format my_format(const std::string & f_string) {
using namespace boost::io;
boost::format fmter(f_string);
fmter.exceptions(no_error_bits);//no exceptions wanted!
return fmter;
}
Internationalizator::Internationalizator()
{
initTranslations();
}
Internationalizator* Internationalizator::getInstance()
{
lock_guard<recursive_mutex> guard(_internationalizatorMutex);
if (ptr == NULL)
ptr = new Internationalizator();
return ptr;
};
void Internationalizator::releaseInstance()
{
lock_guard<recursive_mutex> guard(_internationalizatorMutex);
if (ptr != NULL)
delete ptr;
ptr = NULL;
};
void Internationalizator::setLang(std::string resourceFile)
{
///\todo
};
std::string Internationalizator::getTranslation(std::string key){
if (translations.find(key) != translations.end())
return translations[key];
else
return key;
};
std::string _STR(std::string key)
{
return Internationalizator::getInstance()->getTranslation(key).c_str();
};
QString _QT(std::string key)
{
QString output = Internationalizator::getInstance()->getTranslation(key).c_str();
return output;
};
void Internationalizator::initTranslations()
{
translations["TRUE"] = "True";
translations["FALSE"] = "False";
translations["ALL_TYPES"] = "All types";
translations["BUTTON_OK"] = "OK";
translations["BUTTON_CANCEL"] = "Cancel";
translations["BUTTON_DELETE"] = "Delete";
translations["BUTTON_BROWSE"] = "Browse...";
translations["BUTTON_UPDATE"] = "Update";
translations["BUTTON_COLOR"] = "Color editor";
translations["BUTTON_MATRIX"] = "Matrix editor";
translations["BUTTON_ADD_INPUT"] = "Add input...";
translations["BUTTON_ADD_OUTPUT"] = "Add output...";
translations["BUTTON_SWITCH_SYNC"] = "Change block rendering type<br/>(currently synchrone)";
translations["BUTTON_SWITCH_ASYNC"] = "Change block rendering type<br/>(currently asyncrone)";
translations["BUTTON_SWITCH_ONESHOT"] = "Change block rendering type<br/>(currently one shot)";
translations["TYPE_DATAS_BOOL"] = "Boolean";
translations["TYPE_DATAS_INT"] = "Int";
translations["TYPE_DATAS_FLOAT"] = "Float";
translations["TYPE_DATAS_COLOR"] = "Color";
translations["TYPE_DATAS_MATRIX"] = "Matrix";
translations["TYPE_DATAS_STRING"] = "String";
translations["TYPE_DATAS_FILE"] = "FilePath";
translations["TYPE_DATAS_LISTBOX"] = "ListBox";
translations["TYPE_DATAS_ERROR"] = "typeError";
translations["CONDITION_EDITOR"] = "Condition editor...";
translations["CONDITION_EDITOR_HELP"] = "You can define here which conditions are needed for block rendering!";
translations["CONDITION_BLOCK_ERROR_INPUT"] = "Condition can't be input of block...";
translations["CONDITION_BLOCK_LEFT"] = "left";
translations["CONDITION_BLOCK_HELP"] = "link to the output's block<br/>whose value will be used in condition";
translations["CONDITION_BLOCK_RIGHT"] = "right";
translations["CONDITION_CARDINAL"] = "#rendering";
translations["CONDITION_IS_EMPTY"] = "is empty";
translations["NOT_INITIALIZED"] = "Not initialized...";
translations["PROCESSING_TIME"] = "Mean processing time: ";
translations["BLOCK_OUTPUT"] = "output";
translations["BLOCK_INPUT"] = "input";
translations["BLOCK_TITLE_INPUT"] = "Input";
translations["BLOCK_TITLE_IMG_PROCESS"] = "2D processing";
translations["BLOCK_TITLE_SIGNAL"] = "Video processing";
translations["BLOCK_TITLE_MATH"] = "Math op.";
translations["BLOCK_TITLE_OUTPUT"] = "Output";
translations["BLOCK_TITLE_INFOS"] = "Infos";
translations["BLOCK_INFOS"] =
"<h1>Statistics</h1>"
"<table><tr><td>Mean processing time:</td><td>%1$s ms</td></tr>"
"<tr><td>Max processing time:</td><td>%2$s ms</td></tr>"
"<tr><td>Min processing time:</td><td>%3$s ms</td></tr>"
"<tr><td>Nb rendering:</td><td>%4$s</td></tr></table>"
"<h1>Errors</h1>"
"<p>%5$s</p>";
translations["ERROR_GENERIC"] = "Error undefined!";
translations["ERROR_GENERIC_TITLE"] = "Error!";
translations["ERROR_CONFIRM_SET_VALUE"] = "Wrong input, are you sure you want to set this value?";
translations["ERROR_TYPE"] = "The type of \"%1$s.%2$s\" (%3$s) doesn't correspond to \"%4$s.%5$s\" (%6$s)";
translations["ERROR_LINK_WRONG_INPUT_OUTPUT"] = "You can't link %1$s to %2$s : same type (%3$s)!";
translations["ERROR_LINK_SAME_BLOCK"] = "You can't link the same block!";
translations["ERROR_PARAM_EXCLUSIF"] = "Params \"%1$s\" and \"%2$s\" are mutually exclusive...";
translations["ERROR_PARAM_NEEDED"] = "Param \"%1$s\" is required...";
translations["ERROR_PARAM_ONLY_POSITIF"] = "Param \"%1$s\":<br/>only positive value are authorized!";
translations["ERROR_PARAM_ONLY_POSITIF_STRICT"] = "Param \"%1$s\":<br/>only strict positive value are authorized!";
translations["ERROR_PARAM_ONLY_NEGATIF"] = "Param \"%1$s\":<br/>only negative value are authorized!";
translations["ERROR_PARAM_ONLY_NEGATIF_STRICT"] = "Param \"%1$s\":<br/>only strict negative value are authorized!";
translations["ERROR_PARAM__valueBETWEEN"] = "Param \"%1$s\" (%2$f):<br/>should be between %3$f and %4$f";
translations["ERROR_PARAM_FOUND"] = "Error! Could not find property of \"%1$s\"";
translations["MENU_FILE"] = "File";
translations["MENU_FILE_OPEN"] = "Open";
translations["MENU_FILE_OPEN_TIP"] = "Open a previous project";
translations["MENU_FILE_CREATE"] = "New";
translations["MENU_FILE_CREATE_TIP"] = "Create a new project";
translations["MENU_FILE_SAVE"] = "Save";
translations["MENU_FILE_SAVE_TIP"] = "Save current project";
translations["MENU_FILE_SAVEAS"] = "Save as...";
translations["MENU_FILE_SAVEAS_TIP"] = "Choose file where to save current project";
translations["MENU_FILE_QUIT"] = "Quit";
translations["MENU_FILE_QUIT_TIP"] = "Quit application";
translations["MENU_EDIT"] = "Edit";
translations["MENU_EDIT_SUBGRAPH"] = "Create subprocess";
translations["MENU_EDIT_SUBGRAPH_TIP"] = "Create a subprocess using every selected widgets";
translations["CREATE_PARAM_TITLE"] = "Parameter creation";
translations["CREATE_PARAM_TYPE"] = "Type of the parameter: ";
translations["CREATE_PARAM_NAME"] = "Short name of the parameter: ";
translations["CREATE_PARAM_NAME_HELP"] = "Short description of the parameter: ";
translations["CREATE_PARAM_INIT_VAL"] = "Initial value of the parameter: ";
translations["MATRIX_EDITOR_TOOLS"] = "Tools";
translations["MATRIX_EDITOR_BLOCKS"] = "Blocks";
translations["MATRIX_EDITOR_DATA_CHOICES"] = "Matrix data type:";
translations["MATRIX_EDITOR_DATA_SIZE"] = "Size (rows, cols, channels):";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL"] = "Initial values:";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_0"] = "zeros";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_1"] = "constant";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_2"] = "eye";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_3"] = "ellipse";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_4"] = "rect";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_5"] = "cross";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_6"] = "random";
translations["MATRIX_EDITOR_SECTION_PEN_COLOR"] = "Color:";
translations["MATRIX_EDITOR_SECTION_PEN_SIZE"] = "Pencil size:";
translations["MATRIX_EDITOR_HELP_LEFT"] = "Panning left (CTRL+arrowLEFT)";
translations["MATRIX_EDITOR_HELP_RIGHT"] = "Panning right (CTRL+arrowRIGHT)";
translations["MATRIX_EDITOR_HELP_UP"] = "Panning up (CTRL+arrowUP)";
translations["MATRIX_EDITOR_HELP_DOWN"] = "Panning down (CTRL+arrowDOWN)";
translations["MATRIX_EDITOR_HELP_ZOOM_X1"] = "Zoom x1 (CTRL+P)";
translations["MATRIX_EDITOR_HELP_ZOOM_IN"] = "Zoom in (CTRL++)";
translations["MATRIX_EDITOR_HELP_ZOOM_OUT"] = "Zoom out (CTRL+-)";
translations["MATRIX_EDITOR_HELP_SAVE"] = "Save current matrix (CTRL+S)";
translations["MATRIX_EDITOR_HELP_LOAD"] = "Load new matrix (CTRL+O)";
translations["MATRIX_EDITOR_HELP_EDIT"] = "Edit matrix (CTRL+E)";
translations["MATRIX_EDITOR_HELP_ONTOP"] = "Always on top (CTRL+T)";
translations["MATRIX_EDITOR_HELP_START"] = "Run graph (Enter)";
translations["MATRIX_EDITOR_HELP_STOP"] = "Stop graph (End)";
translations["MATRIX_EDITOR_HELP_PAUSE"] = "Pause graph (Space)";
translations["MENU_HELP_INFO"] = "Info";
translations["MENU_HELP_HELP"] = "Help";
translations["CONF_FILE_TYPE"] = "imGraph project (*.igp)";
translations["PROJ_LOAD_FILE"] = "Open project file";
translations["PROJ_CREATE_FILE"] = "Create project file";
translations["DOCK_TITLE"] = "Toolbox";
translations["DOCK_PROPERTY_TITLE"] = "Properties";
translations["SUBBLOCK__"] = "Sub graph";
translations["FOR_BLOCK_"] = "for";
translations["FOR_BLOCK_INITVAL"] = "start";
translations["FOR_BLOCK_INITVAL_HELP"] = "Initial value of counter";
translations["FOR_BLOCK_ENDVAL"] = "end";
translations["FOR_BLOCK_ENDVAL_HELP"] = "Final value of counter";
translations["FOR_BLOCK_STEPVAL"] = "step";
translations["FOR_BLOCK_STEPVAL_HELP"] = "Step value of counter";
translations["BLOCK__INPUT_NAME"] = "File Loader";
translations["BLOCK__INPUT_IN_INPUT_TYPE"] = "input";
translations["BLOCK__INPUT_IN_INPUT_TYPE_HELP"] = "Input type|Webcam^Video file^Folder";
translations["BLOCK__INPUT_IN_FILE_HELP"] = "File to load.";
translations["BLOCK__INPUT_IN_FILE_FILTER"] = "media files";
translations["BLOCK__INPUT_IN_FILE_NOT_FOUND"] = "File \"%1$s\" not found!";
translations["BLOCK__INPUT_IN_FILE_NOT_FOLDER"] = "File \"%1$s\" is not a folder!";
translations["BLOCK__INPUT_IN_FILE_PROBLEM"] = "File \"%1$s\" can't be loaded!";
translations["BLOCK__INPUT_IN_LOOP"] = "loop";
translations["BLOCK__INPUT_IN_LOOP_HELP"] = "Loop video file (if <=0, infinite loop)";
translations["BLOCK__INPUT_IN_GREY"] = "grey";
translations["BLOCK__INPUT_IN_GREY_HELP"] = "Convert image to a grayscale one";
translations["BLOCK__INPUT_IN_COLOR"] = "color";
translations["BLOCK__INPUT_IN_COLOR_HELP"] = "Convert image to a color one";
translations["BLOCK__INPUT_OUT_IMAGE"] = "image";
translations["BLOCK__INPUT_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__INPUT_OUT_FRAMERATE"] = "framerate";
translations["BLOCK__INPUT_OUT_FRAMERATE_HELP"] = "Number of frames per second";
translations["BLOCK__INPUT_INOUT_WIDTH"] = "width";
translations["BLOCK__INPUT_INOUT_WIDTH_HELP"] = "Wanted width of images (in pixels)";
translations["BLOCK__INPUT_INOUT_HEIGHT"] = "height";
translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"] = "Wanted height of images (in pixels)";
translations["BLOCK__INPUT_INOUT_POS_FRAMES"] = "position";
translations["BLOCK__INPUT_INOUT_POS_FRAMES_HELP"] = "0-based index of the frame to be decoded/captured";
translations["BLOCK__INPUT_INOUT_POS_RATIO"] = "pos. ratio";
translations["BLOCK__INPUT_INOUT_POS_RATIO_HELP"] = "Relative position in the video file (0-begining, 1-end)";
translations["BLOCK__INPUT_OUT_FORMAT"] = "out format";
translations["BLOCK__INPUT_OUT_FORMAT_HELP"] = "The format of the Mat objects";
translations["BLOCK__OUTPUT_NAME"] = "Display image";
translations["BLOCK__OUTPUT_IN_IMAGE"] = "image";
translations["BLOCK__OUTPUT_IN_IMAGE_HELP"] = "Image to show";
translations["BLOCK__OUTPUT_IN_WIN_NAME"] = "win. title";
translations["BLOCK__OUTPUT_IN_WIN_NAME_HELP"] = "Windows title";
translations["BLOCK__OUTPUT_IN_NORMALIZE"] = "normalize";
translations["BLOCK__OUTPUT_IN_NORMALIZE_HELP"] = "Normalize image before show";
translations["BLOCK__SHOWGRAPH_NAME"] = "Show graph";
translations["BLOCK__SHOWGRAPH_IN_VALUES"] = "values";
translations["BLOCK__SHOWGRAPH_IN_VALUES_HELP"] = "Vector of values to show";
translations["BLOCK__SHOWGRAPH_IN_TITLE"] = "title";
translations["BLOCK__SHOWGRAPH_IN_TITLE_HELP"] = "Graph title";
translations["BLOCK__STRING_CREATION_NAME"] = "String creation";
translations["BLOCK__STRING_CREATION_IN_REGEX"] = "pattern";
translations["BLOCK__STRING_CREATION_IN_REGEX_HELP"] = "Pattern name <br/>(use %i% for input i : <br/>\"img%1%.jpg\"<br/> will concatenate first input<br/> with the pattern...)<br/>%n% can also be used:<br/>it's the number of current frame";
translations["BLOCK__STRING_CREATION_OUT"] = "output";
translations["BLOCK__STRING_CREATION_OUT_HELP"] = "Constructed string";
translations["BLOCK__WRITE_NAME"] = "Write video";
translations["BLOCK__WRITE_IN_IMAGE"] = "image";
translations["BLOCK__WRITE_IN_IMAGE_HELP"] = "Image to add to video file";
translations["BLOCK__WRITE_IN_FILENAME"] = "Filename";
translations["BLOCK__WRITE_IN_FILENAME_HELP"] = "Filename of the video file";
translations["BLOCK__WRITE_IN_FPS"] = "FPS";
translations["BLOCK__WRITE_IN_FPS_HELP"] = "Frames per second";
translations["BLOCK__WRITE_IN_CODEC"] = "codec";
translations["BLOCK__WRITE_IN_CODEC_HELP"] = "FOURCC wanted (XVID, X264...).<br/>Empty if you want no compression,<br/>-1 if you want to choose using IHM!";
translations["BLOCK__IMWRITE_NAME"] = "Write image";
translations["BLOCK__IMWRITE_IN_IMAGE"] = "image";
translations["BLOCK__IMWRITE_IN_IMAGE_HELP"] = "Image to save";
translations["BLOCK__IMWRITE_IN_FILENAME"] = "Filename";
translations["BLOCK__IMWRITE_IN_FILENAME_HELP"] = "Filename of the file";
translations["BLOCK__IMWRITE_IN_QUALITY"] = "Quality";
translations["BLOCK__IMWRITE_IN_QUALITY_HELP"] = "Quality of the output img (0->highest compression, 100->highest quality)";
translations["BLOCK__LINEDRAWER_NAME"] = "Draw lines";
translations["BLOCK__LINEDRAWER_IN_LINES"] = "lines list";
translations["BLOCK__LINEDRAWER_IN_LINES_HELP"] = "Input of lines (4 values per row)";
translations["BLOCK__LINEDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__LINEDRAWER_IN_IMAGE_HELP"] = "Input image to draw on";
translations["BLOCK__LINEDRAWER_IN_COLOR"] = "color";
translations["BLOCK__LINEDRAWER_IN_COLOR_HELP"] = "Color of lines";
translations["BLOCK__LINEDRAWER_IN_SIZE"] = "size";
translations["BLOCK__LINEDRAWER_IN_SIZE_HELP"] = "Size of lines";
translations["BLOCK__LINEDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__LINEDRAWER_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__POINTDRAWER_NAME"] = "Draw points";
translations["BLOCK__POINTDRAWER_IN_POINTS"] = "point list";
translations["BLOCK__POINTDRAWER_IN_POINTS_HELP"] = "Input of points (2 values per row)";
translations["BLOCK__POINTDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__POINTDRAWER_IN_IMAGE_HELP"] = "Input image to draw on";
translations["BLOCK__POINTDRAWER_IN_COLOR"] = "color";
translations["BLOCK__POINTDRAWER_IN_COLOR_HELP"] = "Color of points";
translations["BLOCK__POINTDRAWER_IN_SIZE"] = "size";
translations["BLOCK__POINTDRAWER_IN_SIZE_HELP"] = "Size of points";
translations["BLOCK__POINTDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__POINTDRAWER_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__POINTDRAWER_ERROR_POINT_SIZE"] = "Image and points have different sizes";
translations["BLOCK__CREATEMATRIX_NAME"] = "Create new matrix";
translations["BLOCK__CREATEMATRIX_IN_TYPE"] = "type";
translations["BLOCK__CREATEMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F";
translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL"] = "channels";
translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels";
translations["BLOCK__CREATEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__CREATEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__CREATEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__CREATEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__CREATEMATRIX_IN_INIT"] = "intialisation";
translations["BLOCK__CREATEMATRIX_IN_INIT_HELP"] = "Initial values of matrix|zeros^ones^eye^ellipse^rect^cross^random uniform^random gaussian";
translations["BLOCK__CREATEMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__CREATEMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__NORMALIZ_NAME"] = "Normalize image";
translations["BLOCK__NORMALIZ_IN_IMAGE"] = "image";
translations["BLOCK__NORMALIZ_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__NORMALIZ_OUT_IMAGE"] = "image";
translations["BLOCK__NORMALIZ_OUT_IMAGE_HELP"] = "Normalized image";
translations["BLOCK__OPTICFLOW_NAME"] = "Compute Optical flow";
translations["BLOCK__OPTICFLOW_IN_IMAGE1"] = "image1";
translations["BLOCK__OPTICFLOW_IN_IMAGE1_HELP"] = "First image";
translations["BLOCK__OPTICFLOW_IN_IMAGE2"] = "image2";
translations["BLOCK__OPTICFLOW_IN_IMAGE2_HELP"] = "Second image";
translations["BLOCK__OPTICFLOW_IN_METHOD"] = "method";
translations["BLOCK__OPTICFLOW_IN_METHOD_HELP"] = "Method|LK^Farneback^DualTVL1^DeepFlow";
translations["BLOCK__OPTICFLOW_OUT_IMAGE"] = "flow";
translations["BLOCK__OPTICFLOW_OUT_IMAGE_HELP"] = "Optical flow";
translations["BLOCK__LINE_FINDER_NAME"] = "Find lines";
translations["BLOCK__LINE_FINDER_IN_IMAGE"] = "image";
translations["BLOCK__LINE_FINDER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__LINE_FINDER_OUT_IMAGE"] = "lines";
translations["BLOCK__LINE_FINDER_OUT_IMAGE_HELP"] = "List of detected lines";
translations["BLOCK__POINT_FINDER_NAME"] = "Find points";
translations["BLOCK__POINT_FINDER_IN_IMAGE"] = "image";
translations["BLOCK__POINT_FINDER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__POINT_FINDER_IN_DETECTOR"] = "detector";
translations["BLOCK__POINT_FINDER_IN_DETECTOR_HELP"] = "Method used to detect points|BRISK^FAST^GFTT^HARRIS^MSER^ORB^SIFT^STAR^SURF^KAZE^AKAZE^SimpleBlob"; //^Grid^Dense
translations["BLOCK__POINT_FINDER_IN_EXTRACTOR"] = "extractor";
translations["BLOCK__POINT_FINDER_IN_EXTRACTOR_HELP"] = "Method used to compute descriptor|SIFT^SURF^ORB^BRIEF^BRISK^MSER^FREAK^KAZE^AKAZE";
translations["BLOCK__POINT_FINDER_OUT_DESC"] = "descriptors";
translations["BLOCK__POINT_FINDER_OUT_DESC_HELP"] = "List of corresponding descriptors";
translations["BLOCK__POINT_FINDER_OUT_POINTS"] = "points";
translations["BLOCK__POINT_FINDER_OUT_POINTS_HELP"] = "List of detected points";
translations["BLOCK__POINT_MATCHER_NAME"] = "Match points";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC1"] = "desc1";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC1_HELP"] = "List of first points descriptors";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC2"] = "desc2";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC2_HELP"] = "List of second points descriptors";
translations["BLOCK__POINT_MATCHER_IN_ALGO"] = "method";
translations["BLOCK__POINT_MATCHER_IN_ALGO_HELP"] = "Method used to match feature vector|Brute force^FLANN";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES"] = "matches";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_HELP"] = "List of matched points";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK"] = "mask";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK_HELP"] = "List of correct matched points";
translations["BLOCK__DEINTERLACE_NAME"] = "Deinterlace";
translations["BLOCK__DEINTERLACE_IN_IMAGE"] = "image";
translations["BLOCK__DEINTERLACE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DEINTERLACE_IN_TYPE"] = "Deinterlacing";
translations["BLOCK__DEINTERLACE_IN_TYPE_HELP"] = "Deinterlacing type wanted|Blend^Bob^Discard^Unfold";
translations["BLOCK__DEINTERLACE_OUT_IMAGE"] = "image";
translations["BLOCK__DEINTERLACE_OUT_IMAGE_HELP"] = "Deinterlaced image";
translations["BLOCK__HISTOGRAM_NAME"] = "Histogram";
translations["BLOCK__HISTOGRAM_IN_IMAGE"] = "image";
translations["BLOCK__HISTOGRAM_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__HISTOGRAM_IN_BINS"] = "#bins";
translations["BLOCK__HISTOGRAM_IN_BINS_HELP"] = "number of bins";
translations["BLOCK__HISTOGRAM_IN_ACCUMULATE"] = "accumulate";
translations["BLOCK__HISTOGRAM_IN_ACCUMULATE_HELP"] = "This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time";
translations["BLOCK__HISTOGRAM_OUT_HISTO"] = "histo";
translations["BLOCK__HISTOGRAM_OUT_HISTO_HELP"] = "Histogram of the input image";
translations["BLOCK__SKIP_FRAME_NAME"] = "Keep only 1 frame every N frame";
translations["BLOCK__SKIP_FRAME_IN_IMAGE"] = "image";
translations["BLOCK__SKIP_FRAME_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__SKIP_FRAME_IN_TYPE"] = "nb skip";
translations["BLOCK__SKIP_FRAME_IN_TYPE_HELP"] = "Number of frames to skip";
translations["BLOCK__SKIP_FRAME_OUT_IMAGE"] = "image";
translations["BLOCK__SKIP_FRAME_OUT_IMAGE_HELP"] = "Interlaced image";
translations["BLOCK__DELAY_VIDEO_NAME"] = "Delay the video of N frame";
translations["BLOCK__DELAY_VIDEO_IN_IMAGE"] = "image";
translations["BLOCK__DELAY_VIDEO_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DELAY_VIDEO_IN_DELAY"] = "delay";
translations["BLOCK__DELAY_VIDEO_IN_DELAY_HELP"] = "Number of frames to delay";
translations["BLOCK__DELAY_VIDEO_OUT_IMAGE"] = "image";
translations["BLOCK__DELAY_VIDEO_OUT_IMAGE_HELP"] = "N-th old image";
translations["BLOCK__ADD_NAME"] = "Add";
translations["BLOCK__ADD_IN_PARAM1"] = "input1";
translations["BLOCK__ADD_IN_PARAM1_HELP"] = "First input (Matrix, number...)";
translations["BLOCK__ADD_IN_PARAM2"] = "input2";
translations["BLOCK__ADD_IN_PARAM2_HELP"] = "Second input (Matrix, number...)";
translations["BLOCK__ADD_OUTPUT"] = "sum";
translations["BLOCK__ADD_OUTPUT_HELP"] = "Output sum of the two input (concatenate in case of string)";
translations["BLOCK__CROP_NAME"] = "Crop image";
translations["BLOCK__CROP_IN_IMAGE"] = "image";
translations["BLOCK__CROP_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CROP_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__CROP_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__CROP_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__CROP_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__CROP_IN_X"] = "X";
translations["BLOCK__CROP_IN_X_HELP"] = "Position of top-left corner (X)";
translations["BLOCK__CROP_IN_Y"] = "Y";
translations["BLOCK__CROP_IN_Y_HELP"] = "Position of top-left corner (Y)";
translations["BLOCK__CROP_OUT_IMAGE"] = "image";
translations["BLOCK__CROP_OUT_IMAGE_HELP"] = "Croped image";
translations["BLOCK__ACCUMULATOR_NAME"] = "Accumulator";
translations["BLOCK__ACCUMULATOR_IN_IMAGE"] = "image";
translations["BLOCK__ACCUMULATOR_IN_IMAGE_HELP"] = "Input image to accumulate";
translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY"] = "history";
translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY_HELP"] = "Size of accumulation history";
translations["BLOCK__ACCUMULATOR_OUT_IMAGE"] = "image";
translations["BLOCK__ACCUMULATOR_OUT_IMAGE_HELP"] = "Accumulated image";
translations["BLOCK__MORPHOLOGIC_NAME"] = "Morpho math";
translations["BLOCK__MORPHOLOGIC_IN_IMAGE"] = "image";
translations["BLOCK__MORPHOLOGIC_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__MORPHOLOGIC_ELEMENT"] = "element";
translations["BLOCK__MORPHOLOGIC_ELEMENT_HELP"] = "Structuring element.";
translations["BLOCK__MORPHOLOGIC_OPERATOR"] = "op";
translations["BLOCK__MORPHOLOGIC_OPERATOR_HELP"] = "Operator|open^close^gradient^tophat^blackhat";
translations["BLOCK__MORPHOLOGIC_ITERATIONS"] = "iterations";
translations["BLOCK__MORPHOLOGIC_ITERATIONS_HELP"] = "Number of times erosion and dilation are applied.";
translations["BLOCK__MORPHOLOGIC_OUT_IMAGE"] = "image";
translations["BLOCK__MORPHOLOGIC_OUT_IMAGE_HELP"] = "Filtered image";
translations["BLOCK__CANNY_NAME"] = "Canny";
translations["BLOCK__CANNY_IN_IMAGE"] = "image";
translations["BLOCK__CANNY_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CANNY_OUT_IMAGE"] = "output";
translations["BLOCK__CANNY_OUT_IMAGE_HELP"] = "Canny image";
translations["BLOCK__CANNY_IN_THRESHOLD_1"] = "Threshold 1";
translations["BLOCK__CANNY_IN_THRESHOLD_1_HELP"] = "1er threshold for the hysteresis procedure";
translations["BLOCK__CANNY_IN_THRESHOLD_2"] = "Threshold 2";
translations["BLOCK__CANNY_IN_THRESHOLD_2_HELP"] = "2nd threshold for the hysteresis procedure";
translations["BLOCK__CANNY_IN_APERTURE_SIZE"] = "Aperture Size";
translations["BLOCK__CANNY_IN_APERTURE_SIZE_HELP"] = "aperture size for the Sobel operator";
translations["BLOCK__CANNY_IN_L2_GRADIENT"] = "L2 Gradient";
translations["BLOCK__CANNY_IN_L2_GRADIENT_HELP"] = "Use more accurate L2 gradient";
translations["BLOCK__INPUT_IN_INPUT_FILE"] = "Input";
translations["BLOCK__INPUT_IN_INPUT_FILE_HELP"] = "File Path";
translations["BLOCK__INPUT_RAW_VIDEO_NAME"] = "YUV reader";
translations["BLOCK__OUTPUT_RAW_VIDEO_NAME"] = "YUV writer";
translations["BLOCK__CASCADECLASSIFIER_NAME"] = "Cascade Classifier";
translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE"] = "image";
translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE"] = "mask";
translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE_HELP"] = "Output mask";
translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"] = "classifier";
translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE_HELP"] = "Loads a classifier from a file.";
translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR"] = "scaleFactor";
translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR_HELP"] = "Parameter specifying how much the image size is reduced at each image scale.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS"] = "minNeighbors";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS_HELP"] = "Parameter specifying how many neighbors each candidate rectangle should have to retain it.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH"] = "minWidth";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH_HELP"] = "Minimum possible object width. Objects smaller than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT"] = "minHeight";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT_HELP"] = "Minimum possible object height. Objects smaller than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH"] = "maxWidth";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH_HELP"] = "Maximum possible object width. Objects larger than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT"] = "maxHeight";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT_HELP"] = "Maximum possible object height. Objects larger than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS"] = "#objects";
translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS_HELP"] = "Number of detected objects";
translations["BLOCK__BLUR_NAME"] = "Blurring";
translations["BLOCK__BLUR_IN_METHOD"] = "method";
translations["BLOCK__BLUR_IN_METHOD_HELP"] = "Blurring method|Mean^Gaussian^Median^Bilateral";
translations["BLOCK__BLUR_IN_IMG"] = "image";
translations["BLOCK__BLUR_IN_IMG_HELP"] = "Input image";
translations["BLOCK__BLUR_OUT_IMAGE"] = "image";
translations["BLOCK__BLUR_OUT_IMAGE_HELP"] = "Filtered image";
translations["BLOCK__CONVERTMATRIX_NAME"] = "Convert matrix";
translations["BLOCK__CONVERTMATRIX_IN_IMG"] = "image";
translations["BLOCK__CONVERTMATRIX_IN_IMG_HELP"] = "Input image to convert";
translations["BLOCK__CONVERTMATRIX_IN_TYPE"] = "type";
translations["BLOCK__CONVERTMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F";
translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL"] = "channels";
translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels";
translations["BLOCK__CONVERTMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__CONVERTMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__RESIZEMATRIX_NAME"] = "Resize matrix";
translations["BLOCK__RESIZEMATRIX_IN_IMG"] = "image";
translations["BLOCK__RESIZEMATRIX_IN_IMG_HELP"] = "Input image to resize";
translations["BLOCK__RESIZEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__RESIZEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__RESIZEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__RESIZEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__RESIZEMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__RESIZEMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__CORE_NAME"] = "CORE filter";
translations["BLOCK__CORE_IN_POINTS"] = "points";
translations["BLOCK__CORE_IN_POINTS_HELP"] = "Input points to filter";
translations["BLOCK__CORE_IN_DESC"] = "descriptors";
translations["BLOCK__CORE_IN_DESC_HELP"] = "Input descriptors to filter";
translations["BLOCK__CORE_IN_THRESHOLD"] = "threshold";
translations["BLOCK__CORE_IN_THRESHOLD_HELP"] = "Threshold value (percent)";
translations["BLOCK__CORE_IN_OPTIM_THRESHOLD"] = "optimization";
translations["BLOCK__CORE_IN_OPTIM_THRESHOLD_HELP"] = "Threshold value of optimization (0->1, 1 for no optimization)";
translations["BLOCK__CORE_OUT_POINTS"] = "points";
translations["BLOCK__CORE_OUT_POINTS_HELP"] = "Filtered points";
translations["BLOCK__CORE_OUT_DESC"] = "descriptors";
translations["BLOCK__CORE_OUT_DESC_HELP"] = "Filtered descriptors";
translations["BLOCK__FILTER2D_NAME"] = "Filter2D";
translations["BLOCK__FILTER2D_IN_IMAGE"] = "image";
translations["BLOCK__FILTER2D_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__FILTER2D_IN_KERNEL"] = "kernel";
translations["BLOCK__FILTER2D_IN_KERNEL_HELP"] = "Convolution kernel ";
translations["BLOCK__FILTER2D_OUT_IMAGE"] = "image";
translations["BLOCK__FILTER2D_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__LAPLACIAN_NAME"] = "Laplacian";
translations["BLOCK__LAPLACIAN_IN_IMAGE"] = "image";
translations["BLOCK__LAPLACIAN_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__LAPLACIAN_OUT_IMAGE"] = "image";
translations["BLOCK__LAPLACIAN_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__MASKDRAWER_NAME"] = "Draw mask";
translations["BLOCK__MASKDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__MASKDRAWER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__MASKDRAWER_IN_MASK"] = "mask";
translations["BLOCK__MASKDRAWER_IN_MASK_HELP"] = "Input mask";
translations["BLOCK__MASKDRAWER_IN_PRINTMASK"] = "Masking type";
translations["BLOCK__MASKDRAWER_IN_PRINTMASK_HELP"] = "How to use the mask?|Draw mask^Keep only mask";
translations["BLOCK__MASKDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__MASKDRAWER_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__MASKDRAWER_ERROR_MASK_TYPE"] = "Expected mask of type CV_8UC1";
translations["BLOCK__MASKDRAWER_ERROR_DIFF_SIZE"] = "Image and mask have different sizes";
translations["BLOCK__THINNING_NAME"] = "Thinning img";
translations["BLOCK__THINNING_IN_IMAGE"] = "image";
translations["BLOCK__THINNING_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__THINNING_OUT_IMAGE"] = "image";
translations["BLOCK__THINNING_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__DISTANCE_NAME"] = "Distance transform";
translations["BLOCK__DISTANCE_IN_IMAGE"] = "image";
translations["BLOCK__DISTANCE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DISTANCE_IN_DISTANCETYPE"] = "distance";
translations["BLOCK__DISTANCE_IN_DISTANCETYPE_HELP"] = "distance type|DIST_C^DIST_L1^DIST_L2^DIST_PRECISE";
translations["BLOCK__DISTANCE_OUT_IMAGE"] = "image";
translations["BLOCK__DISTANCE_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__BINARIZE_NAME"] = "Binarize img";
translations["BLOCK__BINARIZE_IN_IMAGE"] = "image";
translations["BLOCK__BINARIZE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__BINARIZE_IN_INVERSE"] = "inverse";
translations["BLOCK__BINARIZE_IN_INVERSE_HELP"] = "Use inverse of binary image";
translations["BLOCK__BINARIZE_IN_METHOD"] = "Method";
translations["BLOCK__BINARIZE_IN_METHOD_HELP"] = "Binarization method|Simple threshold^Otsu^Adaptative^Sauvola";
translations["BLOCK__BINARIZE_IN_THRESHOLD"] = "threshold";
translations["BLOCK__BINARIZE_IN_THRESHOLD_HELP"] = "Threshold value";
translations["BLOCK__BINARIZE_OUT_IMAGE"] = "image";
translations["BLOCK__BINARIZE_OUT_IMAGE_HELP"] = "Output image";
}
}
| 34,114 | 13,003 |
/**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
using namespace std;
std::default_random_engine gen;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 100; // TODO: Set the number of particles
//default_random_engine gen;
double std_x, std_y, std_theta; // Standard deviations for x, y, and theta
std_x = std[0];
std_y = std[1];
std_theta = std[2];
//creates a normal (Gaussian) distribution for x and y and theta
normal_distribution<double> dist_x(x, std_x);
normal_distribution<double> dist_y(y, std_y);
normal_distribution<double> dist_theta(theta,std_theta);
//particles.resize(num_particles);
// Sample from these normal distributions
for (int i = 0; i < num_particles; ++i) {
Particle ptc;
ptc.id = i;
ptc.x = dist_x(gen);
ptc.y = dist_y(gen);
ptc.theta = dist_theta(gen);
ptc.weight = 1.0;
particles.push_back(ptc);
weights.push_back(1.0);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
//creates a normal (Gaussian) distribution
normal_distribution<double> dist_x(0, std_pos[0]);
normal_distribution<double> dist_y(0, std_pos[1]);
normal_distribution<double> dist_theta(0,std_pos[2]);
//default_random_engine gen;
for (int i = 0; i < num_particles; ++i)
{
// when the yaw rate is close to zero:
if (fabs(yaw_rate) < 0.00001)
{
particles[i].x += velocity * delta_t * cos(particles[i].theta);
particles[i].y += velocity * delta_t * sin(particles[i].theta);
}
// when the yaw rate is not zero:
else
{
particles[i].x += velocity/yaw_rate * (sin(particles[i].theta + yaw_rate * delta_t) - sin(particles[i].theta));
particles[i].y += velocity/yaw_rate * (cos(particles[i].theta) - cos(particles[i].theta + yaw_rate * delta_t));
particles[i].theta += yaw_rate * delta_t;
}
// adding noise
particles[i].x += dist_x(gen);
particles[i].y += dist_y(gen);
particles[i].theta += dist_theta(gen);
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
for (unsigned int i = 0; i < observations.size(); i++)
{
// initial the closest distance
double close_dist = numeric_limits<double>::max();
int land_close_id = 0;
for (unsigned int j = 0; j < predicted.size(); j++)
{
// calculate distance between observation and prediction
double estimate_dist = dist(observations[i].x, observations[i].y, predicted[j].x, predicted[j].y);
if (estimate_dist < close_dist)
{
close_dist = estimate_dist;
observations[i].id = land_close_id;
}
land_close_id ++;
}
}//observations[i].id = land_close_id;
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
for(int i=0; i < num_particles; i++)
{
// step 1: transformed observation in the car coordinate to map coordinate
vector<LandmarkObs> transformed_obs;
transformed_obs.clear();
for (int j=0; j<observations.size(); j++)
{
//Homogenous Transformation
double obs_mapX = particles[i].x + cos(particles[i].theta) * observations[j].x - sin(particles[i].theta) * observations[j].y;
double obs_mapY = particles[i].y + sin(particles[i].theta) * observations[j].x + cos(particles[i].theta) * observations[j].y;
transformed_obs.push_back(LandmarkObs{observations[j].id, obs_mapX, obs_mapY});
}
// step 2: landmarks in particles range
vector<LandmarkObs> landmarks_choice;
for (unsigned j=0; j < map_landmarks.landmark_list.size(); j++)
{
double landmarks_x = map_landmarks.landmark_list[j].x_f;
double landmarks_y = map_landmarks.landmark_list[j].y_f;
int landmarks_id = map_landmarks.landmark_list[j].id_i;
if (dist(particles[i].x, particles[i].y, landmarks_x, landmarks_y) <= sensor_range)
{
landmarks_choice.push_back(LandmarkObs{landmarks_id, landmarks_x, landmarks_y});
}
}
if (landmarks_choice.size() == 0)
{
continue;
}
// step 3: data association
dataAssociation(landmarks_choice, transformed_obs);
// step 4: update weight
particles[i].weight = 1.0;
double std_x = std_landmark[0];
double std_y = std_landmark[1];
double cov_x = std_x * std_x;
double cov_y = std_y * std_y;
// calculate normalization term
double gauss_norm = 1 / (2 * M_PI * std_x * std_y);
for (unsigned int j=0; j<transformed_obs.size(); j++)
{
double x_obs = transformed_obs[j].x;
double y_obs = transformed_obs[j].y;
int id_land = transformed_obs[j].id;
//double mu_x;
//double mu_y;
//for(size_t k=0; k<landmarks_choice.size(); k++)
//{
//if(landmarks_choice[k].id == transformed_obs[j].id)
//{
//mu_x = landmarks_choice[k].x;
//mu_y = landmarks_choice[k].y;
//}
//}
double mu_x = landmarks_choice[id_land].x;
double mu_y = landmarks_choice[id_land].y;
double power_x = pow((x_obs - mu_x),2);
double power_y = pow((y_obs - mu_y),2);
double exponent = (power_x/(2 * cov_x)) + (power_y/(2 * cov_y));
//double exponent = (pow(x_obs - mu_x, 2) / (2 * cov_x)) + (pow(y_obs - mu_y, 2) / (2 * cov_y));
particles[i].weight *= gauss_norm * exp(-exponent);
//particles[i].weight = particles[i].weight * weight_est ;
cout << "weight: " << particles[i].weight << endl;
}
weights[i] = particles[i].weight;
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
vector<Particle> resample_particles;
uniform_real_distribution<> uni_dist(0, 1);
int index = rand() % num_particles;
double beta = 0.0;
const double mw = *max_element(weights.cbegin(), weights.cend());
for (int i=0; i < num_particles; i++)
{
beta += uni_dist(gen) * 2.0 * mw;
while (beta > weights[index])
{
beta -= weights[index];
index = (index + 1) % num_particles;
}
resample_particles.push_back(particles[index]);
}
particles = resample_particles;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
} | 10,449 | 3,452 |
#include <iostream>
#include "trie.h"
using std::cout;
using std::endl;
void testBasicsTrie()
{
Trie<int> map;
map.set("babati", 1);
map.set("babati2", 2);
map.set("babati3", 3);
map.set("babati2dyadoti", 4);
map.set("babati2dyadoti", 5);
cout << map.get("babati2dyadoti") << endl;
assert(map.contains("babati2dyadoti"));
assert(map.contains("babati"));
assert(map.contains("babati2"));
assert(!map.contains("baba"));
assert(!map.contains(""));
map.remove("babati");
map.remove("babati2dyadoti");
assert(!map.contains("babati"));
assert(!map.contains("babati2dyadoti"));
}
int main()
{
testBasicsTrie();
return 0;
}
| 644 | 288 |
//
// Copyright © 2018 Roman Sobkuliak <r.sobkuliak@gmail.com>
// This code is released under the license described in the LICENSE file
//
#include "../thirdparty/args/args.hxx"
#include "Filter.h"
#include "FolderCrawler.h"
#include "ImageProcessor.h"
#include "ImageStore.h"
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <memory>
class Hranol
{
std::vector< std::string> folders_;
bool recursive_;
bool ram_friendly_;
std::string fname_regex_;
std::string output_folder_;
// Prefix of filtered folders
std::string folder_prefix_;
// Indicates whether folders starting with folder_prefix_ should be included
bool incl_folder_prefix_;
ImageProcessor img_processor_;
public:
// Defaults
Hranol() :
recursive_(false),
ram_friendly_(false),
fname_regex_(".*\\.(jpe?g|gif|tif|tiff|png|bmp)"),
output_folder_(""),
folder_prefix_("fltrd"),
incl_folder_prefix_(false) { }
void parse_from_cli(int argc, char **argv);
void process();
};
void Hranol::parse_from_cli(int argc, char **argv)
{
args::ArgumentParser parser(
"Hranol -- batch image processing utility. By default only images in given folders are processed "
"and the output is saved to a subfolder with prefix \"" + folder_prefix_ + "\". Writing to subfolders "
"can be overridden with option -o which specifies output folder. Supported filters: static background "
"subtraction, contrast filter (normalization) and mask filter. Each filter is used when a corresponding filter-specific "
"option is set. Only grayscale images are supported.",
"Visit the project page for further information: https://github.com/romeritto/hranol");
parser.Prog(argv[0]);
args::ValueFlag<std::string> mask_file(parser, "file",
"Apply mask to every image. The mask size must match the sizes of all images.",
{ 'm', "mask" });
args::ValueFlag<double> subtraction_factor(parser, "subtraction factor",
"Static background subtraction factor. Computes an average of all images (from single folder) and "
"subtracts this average from each image with given factor. You may use positive floating point "
"values for the factor.",
{ 's', "static-noise" });
args::Group rescale(parser, "Rescaling range [b, e] for contrast filter. Pixel values in range [b, e] will be mapped to [0, 255]:");
args::ValueFlag<int> rescale_beg(rescale, "range begin",
"",
{ 'b', "rescale-begin" });
args::ValueFlag<int> rescale_end(rescale, "range end",
"",
{ 'e', "rescale-end" });
args::ValueFlag<std::string> fname_regex(parser, "filename regex",
"If specified, only files matching given regex will be processed. Default value is \"" + fname_regex_ + "\" "
"(matches common image files). Use ECMAScript regex syntax.",
{'f', "fname-regex"});
args::ValueFlag<std::string> output_folder(parser, "output folder",
"Specifies output folder for filtered images. If used together with recursive option original folder structure "
"will be preserved (folders won't be flattened).",
{ 'o', "output-folder" });
args::ValueFlag<std::string> folder_prefix(parser, "filtered folder prefix",
"Specifies prefix of subfolder that will hold filtered images. Default value is \"" + folder_prefix_ + "\"",
{ 'p', "folder-prefix" });
args::Flag incl_folder_prefix(parser, "include filtered folders",
"If set folders found during recursive traversal starting with folder-prefix (specified with "
"option -p) will be processed. By default these folders are ignored so that they don't "
"get filtered twice.",
{ 'i', "incl-fltrd" });
args::Flag recursive(parser, "recursive",
"Process input folders recursively.",
{ 'r', "recursive" });
args::Flag ram_friendly(parser, "ram friendly",
"By default all images from a single folder are stored in memory when the folder is being processed. If that is not possible "
"due to small RAM space, use this flag.",
{ "ram-friendly" });
args::PositionalList<std::string> folders(parser, "folders", "List of folders to process.");
args::HelpFlag help(parser, "help", "Display this help menu", { 'h', "help" });
try {
parser.ParseCLI(argc, argv);
}
catch (const args::Help & e) {
std::cout << parser;
throw;
}
folders_ = std::vector<std::string>(args::get(folders));
if (recursive)
recursive_ = true;
if (ram_friendly)
ram_friendly_ = true;
if (fname_regex)
fname_regex_ = args::get(fname_regex);
if (output_folder)
output_folder_ = args::get(output_folder);
if (folder_prefix)
folder_prefix_ = args::get(folder_prefix);
if (incl_folder_prefix)
incl_folder_prefix_ = true;
if (mask_file)
img_processor_.add_filter(std::move(MaskFilter::create(args::get(mask_file))));
if (subtraction_factor)
img_processor_.add_filter(std::move(BckgSubFilter::create(args::get(subtraction_factor))));
if (rescale_beg || rescale_end)
{
if (rescale_beg && rescale_end)
img_processor_.add_filter(std::move(ContrastFilter::create(
args::get(rescale_beg),
args::get(rescale_end)
)));
else
throw HranolRuntimeException("Both range begin and end must be specified for rescale filter.");
}
}
void Hranol::process()
{
FolderCrawler crawler(
folders_,
output_folder_,
folder_prefix_,
fname_regex_,
incl_folder_prefix_,
recursive_,
ram_friendly_
);
while (crawler.has_next_run())
{
try {
auto store = crawler.get_next_run();
img_processor_.apply_filters(store.get());
}
catch (const std::exception &e) {
std::cout << "\nError (skipping run):\n" << e.what() << std::endl;
}
}
}
int main(int argc, char **argv)
{
Hranol hranol;
try {
hranol.parse_from_cli(argc, argv);
hranol.process();
}
catch (const args::Help & e) {
// Help page was requested
return 0;
}
catch (const args::Error & e) {
// An exception was thrown while processing arguments
std::cerr << e.what() << std::endl;
return 1;
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
catch (...) {
std::cerr << "Unknown error" << std::endl;
return 1;
}
}
| 6,745 | 2,044 |
/* -*- Mode: c++; -*- */
// copyright (c) 2009 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "FactoredMarkovChain.h"
#include "Random.h"
FactoredMarkovChain::FactoredMarkovChain(int n_actions_, int n_obs_,
int mem_size_)
: T(0),
n_actions(n_actions_),
n_obs(n_obs_),
n_states(n_obs * n_actions),
mem_size(mem_size_),
n_contexts((Context)pow((double)n_states, (double)mem_size)),
transitions(n_contexts, n_obs),
act_history(mem_size),
obs_history(mem_size),
history(mem_size),
threshold(0.5) {
printf(
"# Making FMC with %d actions, %d obs, %d states, %d history, %lld "
"contexts\n",
n_actions, n_obs, n_states, mem_size, n_contexts);
for (int i = 0; i < mem_size; ++i) {
act_history[i] = 0;
obs_history[i] = 0;
history[i] = 0;
}
}
FactoredMarkovChain::~FactoredMarkovChain() {}
/** Calculate the current context.
Calculates the current contexts up to the time the
last action was taken.
*/
FactoredMarkovChain::Context FactoredMarkovChain::CalculateContext() {
#if 0
Context context = 0;
Context n = 1;
for (Context i=0; i<mem_size; i++, n*=n_states) {
context += history[i]*n;
}
#else
Context context = history.get_id(n_states);
#endif
return context;
}
/** Calculate the current context taking into account that there is an extra
observation.
Calculates the current contexts up to the time the
last action was taken.
*/
FactoredMarkovChain::Context FactoredMarkovChain::getContext(int act) {
assert((obs_history.size() == 1 + act_history.size()) &&
(act_history.size() == history.size()));
// first set up the context component due to the most recent observation
// and postulated next action
if (mem_size == 0) {
return 0;
}
Context context = CalculateState(act, obs_history.back());
Context n = n_states;
// continue with the remaining context
for (Context i = 0; i < mem_size - 1; i++, n *= n_states) {
context += history[i] * n;
}
return context;
}
/** Obtain an observation.
This should only be used at the first time step, before any actions are
taken.
@return Probability of having observed the next state.
*/
real FactoredMarkovChain::Observe(int prd) {
PushObservation(prd);
return 1.0 / (real)n_obs;
}
/** Train the chain with a new observation
A side-effect is that it updates the current_context.
@return Probability of having observed the next state.
*/
real FactoredMarkovChain::Observe(int act, int prd) {
PushAction(act);
current_context = CalculateContext();
real Pr = getProbability(current_context, prd);
// printf("%d %d %d %f # act obx ctx P\n", act, prd, current_context, Pr);
transitions.observe(current_context, prd);
PushObservation(prd);
return Pr;
}
/** Probability of a next observation
\return The probability of observing x
*/
real FactoredMarkovChain::ObservationProbability(int x) {
return getProbability(current_context, x);
}
/** Probability of an observation given a particular action.
\return The probability of observing prd given act.
*/
real FactoredMarkovChain::ObservationProbability(int a, int x) {
assert((a >= 0) && (a < n_actions));
return getProbability(getContext(a), x);
}
#if 0
void FactoredMarkovChain::getNextStateProbabilities(int act, std::vector<real>& p)
{
curr_state = CalculateStateID();
return getProbabilities(curr_state, p);
}
#endif
/// Get the number of transitions from \c context to \c prd
real FactoredMarkovChain::getTransition(Context context, int prd) {
assert((context >= 0) && (context < n_contexts));
assert((prd >= 0) && (prd < n_states));
return transitions.get_weight(context, prd);
}
/// Get the transition probability from \c context to \c prd
///
/// Takes into account the threshold.
real FactoredMarkovChain::getProbability(Context context, int prd) {
assert((context >= 0) && (context < n_contexts));
assert((prd >= 0) && (prd < n_obs));
real sum = 0.0;
int N = transitions.nof_destinations();
for (int i = 0; i < N; ++i) {
sum += transitions.get_weight(context, i);
}
return (transitions.get_weight(context, prd) + threshold) /
(sum + threshold * ((real)N));
}
/// Get the transition probabilities
///
/// Takes into account the threshold.
void FactoredMarkovChain::getProbabilities(Context context,
std::vector<real>& p) {
assert((context >= 0) && (context < n_contexts));
assert((int)p.size() == n_states);
real sum = 0.0;
int N = transitions.nof_destinations();
for (int i = 0; i < N; ++i) {
p[i] = threshold + transitions.get_weight(context, i);
sum += p[i];
}
real invsum = 1.0 / sum;
for (int i = 0; i < N; ++i) {
p[i] *= invsum;
}
}
/**
\brief Reset the chain
Sets the state (and history) to 0. Call before training for
distinct sequences and before generating a new
sequence. (Otherwise training and generation will depend on past
sequences).
*/
void FactoredMarkovChain::Reset() {
int i;
for (i = 0; i < mem_size; i++) {
history[i] = 0;
act_history[i] = 0;
obs_history[i] = 0;
}
current_context = 0;
}
/**
\brief Generate values from the chain.
Generates a new observation based on the current state history,
according to the transition tables. Note that you might generate as
many new states as you wish. The state history must be explicitly
updated by calling MarkovChainPushState() with the generated value
(or one of the generated values, if you have called this multiple
times, or if you are selecting a generated value from a number of
different markov chains).
\arg \c chain: A pointer to the chain
\return The ID of the next state, as generated by the MC. Returns -1 if
nothing could be generated.
*/
int FactoredMarkovChain::GenerateStatic() {
real tot = 0.0f;
// int curr = CalculateStateID ();
real sel = urandom();
for (int j = 0; j < n_states; j++) {
real P = 0.0; // Pr[curr + j*tot_states];
tot += P;
if (sel <= tot && P > 0.0f) {
return j;
}
}
return -1;
}
| 6,836 | 2,212 |
#include <iostream>
using namespace std;
/*
10. Перевантажити оператори потокового введення-виведення (>>,<<).
*/
class Fraction
{
protected:
int numerator, denominator;
int nod(int a, int b);
int nok(int a, int b);
public:
Fraction();
Fraction(int num, int den);
Fraction(const Fraction& f);
void addition(const Fraction& f);
void subtraction(const Fraction& f);
void multiplication(const Fraction& f);
void print();
~Fraction();
friend Fraction operator +(const Fraction& a, const Fraction& b);
Fraction& operator =(const Fraction& d);
friend istream& operator >>(istream& s, Fraction& f);
friend ostream& operator <<(ostream& s, const Fraction& f);
};
Fraction::Fraction() {
numerator = 1;
denominator = 2;
}
Fraction::Fraction(int num, int den) {
if (den == 0) {
cout << "Error: division by zero!\n";
cout << 1/0;
}
if (num >= den) {
cout << "Error: fraction must be < 1! Use Any_Fraction fraction.\n";
cout << 1/0;
}
numerator = num;
denominator = den;
}
Fraction::Fraction(const Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
}
int Fraction::nod(int a, int b) {
while (a != 0 && b != 0) {
if (a > b) {
a = a % b;
}
else b = b % a;
}
return a + b;
}
int Fraction::nok(int a, int b) {
return a * b / Fraction::nod(a, b);
}
void Fraction::addition(const Fraction& f) {
int cd = nok(denominator, f.denominator);
numerator = (numerator * (cd / denominator)) + (f.numerator * (cd / f.denominator));
denominator = cd;
}
void Fraction::subtraction(const Fraction& f) {
Fraction f1 = Fraction(f);
f1.numerator *= -1;
Fraction::addition(f1);
}
void Fraction::multiplication(const Fraction& f) {
numerator *= f.numerator;
denominator *= f.denominator;
}
void Fraction::print() {
cout << numerator << "/" << denominator;
}
Fraction::~Fraction() {
numerator = 0;
denominator = 0;
}
Fraction operator +(const Fraction& a, const Fraction& b) {
Fraction c = Fraction(a);
c.addition(b);
return c;
}
Fraction& Fraction::operator =(const Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
return *this;
}
istream& operator >>(istream& s, Fraction& f) {
cout << "Enter fraction:\n";
s >> f.numerator;
cout << "--\n";
s >> f.denominator;
return s;
}
ostream& operator <<(ostream& s, const Fraction& f) {
s << f.numerator << "/" << f.denominator;
return s;
}
class Any_Fraction : public Fraction
{
public:
Any_Fraction();
Any_Fraction(int num, int den);
Any_Fraction(const Any_Fraction& f);
};
Any_Fraction::Any_Fraction() {
numerator = 1;
denominator = 2;
}
Any_Fraction::Any_Fraction(int num, int den) {
if (den == 0) {
cout << "Error: division by zero!\n";
cout << 1/0;
}
numerator = num;
denominator = den;
}
Any_Fraction::Any_Fraction(const Any_Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
}
int main()
{
Fraction f1, f2, f3;
cin >> f1;
cin >> f2;
f3 = f1 + f2;
cout << "f1 + f2: " << f3;
return 0;
}
| 3,328 | 1,217 |
/*
* Jos van Eijndhoven, Vector Fabrics
* The 'com_vectorfabrics_vectorizeLib.h' was generated by 'javah' from the java class interface
*/
#include "com_vectorfabrics_vectorizeLib.h"
#include "Vectorized.h"
extern "C" {
//const char * __stdcall vectorizedVersionName() {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.versionName();
//}
JNIEXPORT jstring JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedVersionName
(JNIEnv *env, jobject obj) {
Vectorized& veclib = VectorizedFactory::get();
const char *name = veclib.versionName();
return env->NewStringUTF(name);
}
//float __stdcall vectorizedInproduct( unsigned int n, const float *a, const float *b) {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.inproduct(n, a, a);
//}
JNIEXPORT jfloat JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedInproduct
(JNIEnv *env, jobject obj, jint n, jfloatArray a, jfloatArray b) {
Vectorized& veclib = VectorizedFactory::get();
float *a_body = env->GetFloatArrayElements( a, 0);
float *b_body = env->GetFloatArrayElements( b, 0);
float r = veclib.inproduct(n, a_body, b_body);
env->ReleaseFloatArrayElements( a, a_body, 0);
env->ReleaseFloatArrayElements( b, b_body, 0);
return (jfloat)r;
}
//float __stdcall vectorizedAverage( unsigned int n, const float *a) {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.average(n, a);
//}
JNIEXPORT jfloat JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedAverage
(JNIEnv *env, jobject obj, jint n, jfloatArray a) {
Vectorized& veclib = VectorizedFactory::get();
float *a_body = env->GetFloatArrayElements( a, 0);
float r = veclib.average(n, a_body);
env->ReleaseFloatArrayElements( a, a_body, 0);
return (jfloat)r;
}
}
| 1,916 | 671 |
/*
* This file is part of
* llreve - Automatic regression verification for LLVM programs
*
* Copyright (C) 2016 Karlsruhe Institute of Technology
*
* The system is published under a BSD license.
* See LICENSE (distributed with this file) for details.
*/
#include "SplitEntryBlockPass.h"
#include "llvm/IR/Instructions.h"
llvm::PreservedAnalyses
SplitBlockPass::run(llvm::Function &Fun, llvm::FunctionAnalysisManager &fam) {
auto &Entry = Fun.getEntryBlock();
Entry.splitBasicBlock(Entry.begin());
std::vector<llvm::Instruction *> splitAt;
for (auto &BB : Fun) {
for (auto &Inst : BB) {
if (const auto CallInst = llvm::dyn_cast<llvm::CallInst>(&Inst)) {
if ((CallInst->getCalledFunction() != nullptr) &&
CallInst->getCalledFunction()->getName() == "__splitmark") {
splitAt.push_back(CallInst);
}
}
}
}
for (auto instr : splitAt) {
llvm::BasicBlock::iterator i(instr);
++i;
i->getParent()->splitBasicBlock(i);
instr->getParent()->splitBasicBlock(instr);
}
return llvm::PreservedAnalyses::none();
}
| 1,186 | 373 |
#include "Material.h"
Material::Material() {
specularIntensity = 0.0f;
shininess = 0.0f;
}
Material::Material(GLfloat sIntensity, GLfloat shine) {
specularIntensity = sIntensity;
shininess = shine;
}
Material::Material(Shader* myShader, Texture* myTexture, GLfloat sIntensity, GLfloat shine) {
shader = myShader;
texture = myTexture;
specularIntensity = sIntensity;
shininess = shine;
}
void Material::UseMaterial() {
glUniform1f(shader->GetSpecularIntensityLocation(), specularIntensity);
glUniform1f(shader->GetShininessLocation(), shininess);
texture->UseTexture();
}
void Material::UseMaterial(GLuint specularIntensityLocation, GLuint shininessLocation) {
glUniform1f(specularIntensityLocation, specularIntensity);
glUniform1f(shininessLocation, shininess);
}
Material::~Material() {
}
| 810 | 301 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Zenject.IProvider
#include "Zenject/IProvider.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: InjectContext
class InjectContext;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
// Forward declaring type: Type
class Type;
// Forward declaring type: Action
class Action;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Zenject.MethodMultipleProviderUntyped
// [NoReflectionBakingAttribute] Offset: DDD0C0
class MethodMultipleProviderUntyped : public ::Il2CppObject/*, public Zenject::IProvider*/ {
public:
// private readonly Zenject.DiContainer _container
// Size: 0x8
// Offset: 0x10
Zenject::DiContainer* container;
// Field size check
static_assert(sizeof(Zenject::DiContainer*) == 0x8);
// private readonly System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> _method
// Size: 0x8
// Offset: 0x18
System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method;
// Field size check
static_assert(sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*) == 0x8);
// Creating value type constructor for type: MethodMultipleProviderUntyped
MethodMultipleProviderUntyped(Zenject::DiContainer* container_ = {}, System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method_ = {}) noexcept : container{container_}, method{method_} {}
// Creating interface conversion operator: operator Zenject::IProvider
operator Zenject::IProvider() noexcept {
return *reinterpret_cast<Zenject::IProvider*>(this);
}
// public System.Void .ctor(System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> method, Zenject.DiContainer container)
// Offset: 0x16C5BA8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MethodMultipleProviderUntyped* New_ctor(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method, Zenject::DiContainer* container) {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::MethodMultipleProviderUntyped::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MethodMultipleProviderUntyped*, creationType>(method, container)));
}
// public System.Boolean get_IsCached()
// Offset: 0x16C5BE0
bool get_IsCached();
// public System.Boolean get_TypeVariesBasedOnMemberType()
// Offset: 0x16C5BE8
bool get_TypeVariesBasedOnMemberType();
// public System.Type GetInstanceType(Zenject.InjectContext context)
// Offset: 0x16C5BF0
System::Type* GetInstanceType(Zenject::InjectContext* context);
// public System.Void GetAllInstancesWithInjectSplit(Zenject.InjectContext context, System.Collections.Generic.List`1<Zenject.TypeValuePair> args, out System.Action injectAction, System.Collections.Generic.List`1<System.Object> buffer)
// Offset: 0x16C5C0C
void GetAllInstancesWithInjectSplit(Zenject::InjectContext* context, System::Collections::Generic::List_1<Zenject::TypeValuePair>* args, System::Action*& injectAction, System::Collections::Generic::List_1<::Il2CppObject*>* buffer);
}; // Zenject.MethodMultipleProviderUntyped
#pragma pack(pop)
static check_size<sizeof(MethodMultipleProviderUntyped), 24 + sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*)> __Zenject_MethodMultipleProviderUntypedSizeCheck;
static_assert(sizeof(MethodMultipleProviderUntyped) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::MethodMultipleProviderUntyped*, "Zenject", "MethodMultipleProviderUntyped");
| 5,013 | 1,624 |
#include "api.h"
#include "inner.h"
#include "randombytes.h"
#include <stddef.h>
#include <string.h>
/*
* Wrapper for implementing the PQClean API.
*/
#define NONCELEN 40
#define SEEDLEN 48
/*
* Encoding formats (nnnn = log of degree, 9 for Falcon-512, 10 for Falcon-1024)
*
* private key:
* header byte: 0101nnnn
* private f (6 or 5 bits by element, depending on degree)
* private g (6 or 5 bits by element, depending on degree)
* private F (8 bits by element)
*
* public key:
* header byte: 0000nnnn
* public h (14 bits by element)
*
* signature:
* header byte: 0011nnnn
* nonce 40 bytes
* value (12 bits by element)
*
* message + signature:
* signature length (2 bytes, big-endian)
* nonce 40 bytes
* message
* header byte: 0010nnnn
* value (12 bits by element)
* (signature length is 1+len(value), not counting the nonce)
*/
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_keypair(unsigned char *pk, unsigned char *sk) {
union {
uint8_t b[FALCON_KEYGEN_TEMP_9];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
int8_t f[512], g[512], F[512];
uint16_t h[512];
unsigned char seed[SEEDLEN];
inner_shake256_context rng;
size_t u, v;
/*
* Generate key pair.
*/
randombytes(seed, sizeof seed);
inner_shake256_init(&rng);
inner_shake256_inject(&rng, seed, sizeof seed);
inner_shake256_flip(&rng);
PQCLEAN_FALCON512_CLEAN_keygen(&rng, f, g, F, NULL, h, 9, tmp.b);
inner_shake256_ctx_release(&rng);
/*
* Encode private key.
*/
sk[0] = 0x50 + 9;
u = 1;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9]);
if (v == 0) {
return -1;
}
u += v;
if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) {
return -1;
}
/*
* Encode public key.
*/
pk[0] = 0x00 + 9;
v = PQCLEAN_FALCON512_CLEAN_modq_encode(
pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1,
h, 9);
if (v != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) {
return -1;
}
return 0;
}
/*
* Compute the signature. nonce[] receives the nonce and must have length
* NONCELEN bytes. sigbuf[] receives the signature value (without nonce
* or header byte), with *sigbuflen providing the maximum value length and
* receiving the actual value length.
*
* If a signature could be computed but not encoded because it would
* exceed the output buffer size, then a new signature is computed. If
* the provided buffer size is too low, this could loop indefinitely, so
* the caller must provide a size that can accommodate signatures with a
* large enough probability.
*
* Return value: 0 on success, -1 on error.
*/
static int
do_sign(uint8_t *nonce, uint8_t *sigbuf, size_t *sigbuflen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
union {
uint8_t b[72 * 512];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
int8_t f[512], g[512], F[512], G[512];
union {
int16_t sig[512];
uint16_t hm[512];
} r;
unsigned char seed[SEEDLEN];
inner_shake256_context sc;
size_t u, v;
/*
* Decode the private key.
*/
if (sk[0] != 0x50 + 9) {
return -1;
}
u = 1;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) {
return -1;
}
if (!PQCLEAN_FALCON512_CLEAN_complete_private(G, f, g, F, 9, tmp.b)) {
return -1;
}
/*
* Create a random nonce (40 bytes).
*/
randombytes(nonce, NONCELEN);
/*
* Hash message nonce + message into a vector.
*/
inner_shake256_init(&sc);
inner_shake256_inject(&sc, nonce, NONCELEN);
inner_shake256_inject(&sc, m, mlen);
inner_shake256_flip(&sc);
PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, r.hm, 9, tmp.b);
inner_shake256_ctx_release(&sc);
/*
* Initialize a RNG.
*/
randombytes(seed, sizeof seed);
inner_shake256_init(&sc);
inner_shake256_inject(&sc, seed, sizeof seed);
inner_shake256_flip(&sc);
/*
* Compute and return the signature. This loops until a signature
* value is found that fits in the provided buffer.
*/
for (;;) {
PQCLEAN_FALCON512_CLEAN_sign_dyn(r.sig, &sc, f, g, F, G, r.hm, 9, tmp.b);
v = PQCLEAN_FALCON512_CLEAN_comp_encode(sigbuf, *sigbuflen, r.sig, 9);
if (v != 0) {
inner_shake256_ctx_release(&sc);
*sigbuflen = v;
return 0;
}
}
}
/*
* Verify a sigature. The nonce has size NONCELEN bytes. sigbuf[]
* (of size sigbuflen) contains the signature value, not including the
* header byte or nonce. Return value is 0 on success, -1 on error.
*/
static int
do_verify(
const uint8_t *nonce, const uint8_t *sigbuf, size_t sigbuflen,
const uint8_t *m, size_t mlen, const uint8_t *pk) {
union {
uint8_t b[2 * 512];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
uint16_t h[512], hm[512];
int16_t sig[512];
inner_shake256_context sc;
/*
* Decode public key.
*/
if (pk[0] != 0x00 + 9) {
return -1;
}
if (PQCLEAN_FALCON512_CLEAN_modq_decode(h, 9,
pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1)
!= PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) {
return -1;
}
PQCLEAN_FALCON512_CLEAN_to_ntt_monty(h, 9);
/*
* Decode signature.
*/
if (sigbuflen == 0) {
return -1;
}
if (PQCLEAN_FALCON512_CLEAN_comp_decode(sig, 9, sigbuf, sigbuflen) != sigbuflen) {
return -1;
}
/*
* Hash nonce + message into a vector.
*/
inner_shake256_init(&sc);
inner_shake256_inject(&sc, nonce, NONCELEN);
inner_shake256_inject(&sc, m, mlen);
inner_shake256_flip(&sc);
PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, hm, 9, tmp.b);
inner_shake256_ctx_release(&sc);
/*
* Verify signature.
*/
if (!PQCLEAN_FALCON512_CLEAN_verify_raw(hm, sig, h, 9, tmp.b)) {
return -1;
}
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_signature(
uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
/*
* The PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES constant is used for
* the signed message object (as produced by PQCLEAN_FALCON512_CLEAN_crypto_sign())
* and includes a two-byte length value, so we take care here
* to only generate signatures that are two bytes shorter than
* the maximum. This is done to ensure that PQCLEAN_FALCON512_CLEAN_crypto_sign()
* and PQCLEAN_FALCON512_CLEAN_crypto_sign_signature() produce the exact same signature
* value, if used on the same message, with the same private key,
* and using the same output from randombytes() (this is for
* reproducibility of tests).
*/
size_t vlen;
vlen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3;
if (do_sign(sig + 1, sig + 1 + NONCELEN, &vlen, m, mlen, sk) < 0) {
return -1;
}
sig[0] = 0x30 + 9;
*siglen = 1 + NONCELEN + vlen;
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(
const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen, const uint8_t *pk) {
if (siglen < 1 + NONCELEN) {
return -1;
}
if (sig[0] != 0x30 + 9) {
return -1;
}
return do_verify(sig + 1,
sig + 1 + NONCELEN, siglen - 1 - NONCELEN, m, mlen, pk);
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign(
uint8_t *sm, size_t *smlen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
uint8_t *pm, *sigbuf;
size_t sigbuflen;
/*
* Move the message to its final location; this is a memmove() so
* it handles overlaps properly.
*/
memmove(sm + 2 + NONCELEN, m, mlen);
pm = sm + 2 + NONCELEN;
sigbuf = pm + 1 + mlen;
sigbuflen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3;
if (do_sign(sm + 2, sigbuf, &sigbuflen, pm, mlen, sk) < 0) {
return -1;
}
pm[mlen] = 0x20 + 9;
sigbuflen ++;
sm[0] = (uint8_t)(sigbuflen >> 8);
sm[1] = (uint8_t)sigbuflen;
*smlen = mlen + 2 + NONCELEN + sigbuflen;
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_open(
uint8_t *m, size_t *mlen,
const uint8_t *sm, size_t smlen, const uint8_t *pk) {
const uint8_t *sigbuf;
size_t pmlen, sigbuflen;
if (smlen < 3 + NONCELEN) {
return -1;
}
sigbuflen = ((size_t)sm[0] << 8) | (size_t)sm[1];
if (sigbuflen < 2 || sigbuflen > (smlen - NONCELEN - 2)) {
return -1;
}
sigbuflen --;
pmlen = smlen - NONCELEN - 3 - sigbuflen;
if (sm[2 + NONCELEN + pmlen] != 0x20 + 9) {
return -1;
}
sigbuf = sm + 2 + NONCELEN + pmlen + 1;
/*
* The 2-byte length header and the one-byte signature header
* have been verified. Nonce is at sm+2, followed by the message
* itself. Message length is in pmlen. sigbuf/sigbuflen point to
* the signature value (excluding the header byte).
*/
if (do_verify(sm + 2, sigbuf, sigbuflen,
sm + 2 + NONCELEN, pmlen, pk) < 0) {
return -1;
}
/*
* Signature is correct, we just have to copy/move the message
* to its final destination. The memmove() properly handles
* overlaps.
*/
memmove(m, sm + 2 + NONCELEN, pmlen);
*mlen = pmlen;
return 0;
}
| 10,961 | 4,773 |
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Routines
char* rstrdup(const char* str);
void reverse_string(char* str);
int
main() {
char str[] = "Atul Patil";
char* rstr = rstrdup(str);
reverse_string(str);
printf("%s ==> %s\n", str, rstr);
return 0;
}
char *
rstrdup(const char *str) {
if (!str) return NULL;
char* rstr = strdup(str);
reverse_string(rstr);
return rstr;
}
void
reverse_string(char *str) {
if (!str) return;
int len = strlen(str);
char* start = str;
char* end = str + len - 1;
while(start < end) {
char tmp = *start;
*start = *end;
*end = tmp;
start++; end--;
}
return;
}
class String {
private:
Array<char, 10> str;
public:
String(): str(""){}
String(const char* str) str(str){}
String(const String s) str(s.str){}
~String(){}
}
| 833 | 351 |
#include "VigilBehavior.h"
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QUrl>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QTcpSocket>
#include <eirExe/Log.h>
#include <eirExe/ResultId.h>
#include <eirNetwork/HttpManager.h>
#include <eirFrameSource/FrameSourceState.h>
#include <eirFrameSource/FrameSourceResult.h>
#include "VigilPlugin.h"
VigilBehavior::VigilBehavior(void)
: _manager(0)
, _reply(0)
, currentGet_mst(MillisecondTime::current())
{
}
FrameSourceBehavior * VigilBehavior::brother(void)
{
return new VigilBehavior();
}
QString VigilBehavior::name(void) const
{
return "vigil";
}
QStringList VigilBehavior::schemeList(void)
{
FUNCTION();
FNRETURN("vigilLive vigilPlay" );
return QStringList() << "vigilLive" << "vigilPlay";
}
bool VigilBehavior::supports(const QUrl & url)
{
FUNCTION();
bool b = ("vigilLive" == url.scheme() || "vigilPlay" == url.scheme());
FNRETURN(b);
return b;
}
bool VigilBehavior::supportsScheme(const QString & scheme)
{
FUNCTION();
bool b = ("vigilLive" == scheme || "vigilPlay" == scheme);
FNRETURN(b);
return b;
}
/*--- common ---*/
void VigilBehavior::getResult(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.size());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
if (FrameSourceState::Grabbing == _plugin->state()
&& "vigilLive" == _plugin->url().scheme())
handleLiveGrab(mst, isError, rset);
else if (FrameSourceState::Grabbing == _plugin->state()
&& "vigilPlay" == _plugin->url().scheme())
handlePlayGrab(mst, isError, rset);
else if (FrameSourceState::Starting == _plugin->state()
&& "vigilPlay" == _plugin->url().scheme())
handlePlayStarting(mst, isError, rset);
else
WATCH("Unhandled getResult()");
}
/*===== Construct =====*/
void VigilBehavior::enterConstruct(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
_socket = new QTcpSocket(_plugin);
_manager = new HttpManager(_plugin);
OBJPOINTER(QTcpSocket, _socket);
OBJPOINTER(HttpManager, _manager);
CONNECT(_socket, SIGNAL(connected()),
_plugin, SLOT(connectResult()));
CONNECT(_socket, SIGNAL(error(QAbstractSocket::SocketError)),
_plugin, SLOT(connectResult()));
ResultSet rset;
rset << Result(FrameSourceResult::Initialized, name());
_plugin->emitInitialized(rset);
}
/*===== Connect =====*/
void VigilBehavior::enterConnecting(void)
{
FUNCTION();
OBJPOINTER(QTcpSocket, _socket);
FSPPOINTER(FrameSourcePlugin, _plugin);
_socket->connectToHost(_plugin->url().host(),
_plugin->url().port(80));
TRACE("connectToHost(%1, %2)", _plugin->url().host(),
_plugin->url().port(80));
}
void VigilBehavior::connectResult(void)
{
FUNCTION();
if (EXPECTNE(0, _socket)) return;
OBJPOINTER(QTcpSocket, _socket);
FSPPOINTER(FrameSourcePlugin, _plugin);
ResultSet rset;
if (EXPECTEQ(QAbstractSocket::ConnectedState, _socket->state()))
{
rset.add(Result(FrameSourceResult::HttpConnectSuccess,
_plugin->url().toString()));
_plugin->emitConnected(rset);
_socket->disconnectFromHost();
}
else
{
rset.add(Result(FrameSourceResult::HttpConnectFailure,
_plugin->url(),
_socket->state(),
_socket->error(),
_socket->errorString()));
_plugin->emitConnectError(rset);
}
RESULTS(rset);
}
void VigilBehavior::exitConnecting(void)
{
FUNCTION();
currentGet_mst = MillisecondTime::null();
if ( ! EXPECTNE(0, _socket)) return;
OBJPOINTER(QTcpSocket, _socket);
_socket->close();
_socket->deleteLater();
_socket = 0;
TODO("GET(xml) if enumeration needed")
}
/*===== Configure =====*/
void VigilBehavior::enterConfiguring(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
VariableSet config = _plugin->configuration();
connect_msec = config.value("ConnectMsec").toInt();
start_msec = config.value("StartMsec").toInt();
get_msec = config.value("GetMsec").toInt();
maxRetry_i = config.value("MaxRetry").toInt();
if ( ! connect_msec) connect_msec = 5000;
if ( ! start_msec) start_msec = 20000;
if ( ! get_msec) get_msec = 5000;
if ( ! maxRetry_i) maxRetry_i = 5;
TODO("Collect configuration: Resolution");
_plugin->emitConfigured(ResultSet());
}
/*===== Start =====*/
void VigilBehavior::enterStarted(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
QUrl url(_plugin->url());
if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "startsession");
url.addQueryItem("camera", QString::number(_plugin->channel()));
if ( ! _plugin->beginMst().isNull())
url.addQueryItem("from", _plugin->beginMst().toString("yyyy-MM-dd hh:mm"));
if ( ! _plugin->endMst().isNull())
url.addQueryItem("to", _plugin->endMst().toString("yyyy-MM-dd hh:mm"));
currentGet_mst = _manager->get(url, start_msec);
TRACE("Start GET done");
session_i = session_n = 0;
}
else if ("vigilLive" == url.scheme())
{
ResultSet rset;
rset << Result(FrameSourceResult::Started, _plugin->url());
_plugin->emitStarted(rset);
}
retry_k = 0;
CONNECT(_manager, SIGNAL(got(MillisecondTime,bool,ResultSet)),
_plugin, SLOT(getResult(MillisecondTime,bool,ResultSet)));
}
void VigilBehavior::handlePlayStarting(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.size());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
EXPECTNOT(session_i);
EXPECTNOT(session_n);
QString sResult;
Result dataRes = rset.find(HttpManager::HttpGotData);
DUMPVAR(dataRes.value("MimeType").toString());
if ( ! dataRes.isNull())
{
sResult = dataRes.value("ByteArray").toByteArray();
if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTNOT(sResult.isEmpty());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
EXPECT("playback" == url.path());
EXPECT("startsession" == url.queryItemValue("cmd"));
QStringList qsl(sResult.split(','));
if (EXPECTEQ(3, qsl.size())
&& EXPECTEQ("result:ok", qsl.at(2)))
{
if (EXPECT(qsl.at(0).startsWith("session:")))
session_i = qsl.at(0).mid(QString("session:").size()).toInt();
if (EXPECT(qsl.at(1).startsWith("totalframes:")))
session_n = qsl.at(1).mid(QString("totalframes:").size()).toInt();
}
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
if (session_i && session_n)
{
currentFrame_i = 1;
ourResult << Result(FrameSourceResult::Started,
_plugin->url(),
session_n);
_plugin->emitStarted(ourResult);
}
else
{
ourResult << Result(FrameSourceResult::StartError,
_plugin->url(), sResult);
_plugin->emitStartError(ourResult);
}
}
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
RESULTS(ourResult);
}
void VigilBehavior::exitRunning(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
DISCONNECT(_manager, SIGNAL(got(MillisecondTime,bool,ResultSet)),
_plugin, SLOT(getResult(MillisecondTime,bool,ResultSet)));
_manager->abort();
QUrl url(_plugin->url());
if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "stopsession");
url.addQueryItem("session", QString::number(session_i));
_manager->get(url);
TRACE("Stop GET done");
currentFrame_i = session_i = session_n = 0;
}
}
void VigilBehavior::enterFinished(void)
{
FUNCTION();
}
/*===== Grab =====*/
bool VigilBehavior::canGrab(void)
{
FUNCTION();
bool b = true;
if ( ! currentGet_mst.isNull())
b = false;
else if ("vigilPlay" == _plugin->url().scheme())
{
if (session_n < currentFrame_i)
{
ResultSet rset;
rset << Result(FrameSourceResult::PlaybackComplete,
session_n,
_plugin->url(),
_plugin->beginMst().toString(),
_plugin->endMst().toString());
_plugin->emitComplete(rset);
b = false;
}
}
FNRETURN(b);
return b;
}
void VigilBehavior::enterGrabbing(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
QUrl url(_plugin->url());
if ("vigilLive" == url.scheme())
{
url.setScheme("http");
url.setPath("live");
url.addQueryItem("camera", QString::number(_plugin->channel()));
url.addQueryItem("resolution", "VGA");
url.addQueryItem("quality", "90");
currentGet_mst = _manager->get(url, get_msec);
TRACE("Grab GET done");
}
else if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "getimage");
url.addQueryItem("frame", QString::number(currentFrame_i));
url.addQueryItem("session", QString::number(session_i));
url.addQueryItem("resolution", "VGA");
currentGet_mst = _manager->get(url, get_msec);
TRACE("Grab GET done");
}
else
{
WARNING("Unhandled scheme: %1", url.scheme());
}
}
void VigilBehavior::handlePlayGrab(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.toStringList());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
Result dataRes = rset.find(HttpManager::HttpGotData);
if ( ! dataRes.isNull())
{
QByteArray ba(dataRes.value("ByteArray").toByteArray());
EXPECTNOT(ba.isEmpty());
EXPECTEQ(ba.size(), dataRes.value("ExpectedBytes").toInt());
DUMPVAR(dataRes.value("MimeType").toString());
if (EXPECT(dataRes.value("MimeType").toString().contains("image/jpeg")))
{
QString FrameId = QString("F%1").arg(currentFrame_i, 7, 10, QChar('0'));
ImageEntity frameEntity
= ImageEntity::fromByteArray(ba,
currentGet_mst,
FrameId);
_plugin->enqueueGrab(frameEntity);
Result goodRes = rset.find(HttpManager::HttpGetSuccess);
EXPECTNOT(goodRes.isNull());
ourResult << goodRes;
_plugin->emitGrabbed(ourResult);
++currentFrame_i;
if (retry_k > 0) --retry_k;
}
else if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QString sResult = dataRes.value("ByteArray").toString();
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
ourResult << Result(HttpManager::HttpGetFailure, -1, sResult);
_plugin->emitGrabError(ourResult);
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
QString sResult = dataRes.value("ByteArray").toString();
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
ourResult << Result(HttpManager::HttpGetFailure, -2, sResult);
_plugin->emitGrabError(ourResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
}
RESULTS(ourResult);
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
}
void VigilBehavior::handleLiveGrab(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.toStringList());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
Result dataRes = rset.find(HttpManager::HttpGotData);
if ( ! dataRes.isNull())
{
QByteArray ba(dataRes.value("ByteArray").toByteArray());
EXPECTNOT(ba.isEmpty());
EXPECTEQ(ba.size(), dataRes.value("ExpectedBytes").toInt());
DUMPVAR(dataRes.value("MimeType").toString());
if (EXPECT(dataRes.value("MimeType").toString().contains("image/jpeg")))
{
ImageEntity frameEntity
= ImageEntity::fromByteArray(ba, currentGet_mst);
_plugin->enqueueGrab(frameEntity);
Result goodRes = rset.find(HttpManager::HttpGetSuccess);
EXPECTNOT(goodRes.isNull());
ourResult << goodRes;
RESULTS(ourResult);
_plugin->emitGrabbed(ourResult);
if (retry_k > 0) --retry_k;
}
else if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QString sResult = dataRes.value("ByteArray").toString();
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
ourResult << Result(HttpManager::HttpGetFailure, -1, sResult);
_plugin->emitGrabError(ourResult);
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
QString sResult = dataRes.value("ByteArray").toString();
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
ourResult << Result(HttpManager::HttpGetFailure, -2, sResult);
_plugin->emitGrabError(ourResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
}
RESULTS(ourResult);
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
}
void VigilBehavior::enterRetry(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
if (++retry_k > maxRetry_i)
{
ResultSet rset;
rset << Result(HttpManager::HttpGetFailure,
-retry_k, "Excessive Timeout");
_plugin->emitGrabError(rset);
}
DUMPVAR(retry_k);
}
| 19,429 | 6,032 |
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/oos/model/ValidateTemplateContentResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Oos;
using namespace AlibabaCloud::Oos::Model;
ValidateTemplateContentResult::ValidateTemplateContentResult() :
ServiceResult()
{}
ValidateTemplateContentResult::ValidateTemplateContentResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ValidateTemplateContentResult::~ValidateTemplateContentResult()
{}
void ValidateTemplateContentResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allTasksNode = value["Tasks"]["Task"];
for (auto valueTasksTask : allTasksNode)
{
Task tasksObject;
if(!valueTasksTask["Name"].isNull())
tasksObject.name = valueTasksTask["Name"].asString();
if(!valueTasksTask["Type"].isNull())
tasksObject.type = valueTasksTask["Type"].asString();
if(!valueTasksTask["Description"].isNull())
tasksObject.description = valueTasksTask["Description"].asString();
if(!valueTasksTask["Properties"].isNull())
tasksObject.properties = valueTasksTask["Properties"].asString();
if(!valueTasksTask["Outputs"].isNull())
tasksObject.outputs = valueTasksTask["Outputs"].asString();
tasks_.push_back(tasksObject);
}
if(!value["Parameters"].isNull())
parameters_ = value["Parameters"].asString();
if(!value["RamRole"].isNull())
ramRole_ = value["RamRole"].asString();
if(!value["Outputs"].isNull())
outputs_ = value["Outputs"].asString();
}
std::vector<ValidateTemplateContentResult::Task> ValidateTemplateContentResult::getTasks()const
{
return tasks_;
}
std::string ValidateTemplateContentResult::getParameters()const
{
return parameters_;
}
std::string ValidateTemplateContentResult::getRamRole()const
{
return ramRole_;
}
std::string ValidateTemplateContentResult::getOutputs()const
{
return outputs_;
}
| 2,555 | 787 |
//================ Copyright (c) 2012, PG, All rights reserved. =================//
//
// Purpose: a simple slider
//
// $NoKeywords: $
//===============================================================================//
#include "CBaseUISlider.h"
#include "Engine.h"
#include "Mouse.h"
#include "AnimationHandler.h"
#include "Keyboard.h"
CBaseUISlider::CBaseUISlider(float xPos, float yPos, float xSize, float ySize, UString name) : CBaseUIElement(xPos,yPos,xSize,ySize,name)
{
m_bDrawFrame = true;
m_bDrawBackground = true;
m_bHorizontal = false;
m_bHasChanged = false;
m_bAnimated = true;
m_bLiveUpdate = false;
m_bAllowMouseWheel = true;
m_backgroundColor = COLOR(255, 0, 0, 0);
m_frameColor = COLOR(255,255,255,255);
m_fCurValue = 0.0f;
m_fCurPercent = 0.0f;
m_fMinValue = 0.0f;
m_fMaxValue = 1.0f;
m_fKeyDelta = 0.1f;
m_vBlockSize = Vector2(xSize < ySize ? xSize : ySize, xSize < ySize ? xSize : ySize);
m_sliderChangeCallback = NULL;
setOrientation(xSize > ySize);
}
void CBaseUISlider::draw(Graphics *g)
{
if (!m_bVisible) return;
// draw background
if (m_bDrawBackground)
{
g->setColor(m_backgroundColor);
g->fillRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1);
}
// draw frame
g->setColor(m_frameColor);
if (m_bDrawFrame)
g->drawRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1);
// draw sliding line
if (!m_bHorizontal)
g->drawLine(m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vBlockSize.y/2.0, m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vSize.y - m_vBlockSize.y/2.0f);
else
g->drawLine(m_vPos.x + (m_vBlockSize.x-1)/2 + 1, m_vPos.y + m_vSize.y/2.0f + 1, m_vPos.x + m_vSize.x - (m_vBlockSize.x-1)/2, m_vPos.y + m_vSize.y/2.0f + 1);
drawBlock(g);
}
void CBaseUISlider::drawBlock(Graphics *g)
{
// draw block
Vector2 center = m_vPos + Vector2(m_vBlockSize.x/2 + (m_vSize.x-m_vBlockSize.x)*getPercent(), m_vSize.y/2);
Vector2 topLeft = center - m_vBlockSize/2;
Vector2 topRight = center + Vector2(m_vBlockSize.x/2 + 1, -m_vBlockSize.y/2);
Vector2 halfLeft = center + Vector2(-m_vBlockSize.x/2, 1);
Vector2 halfRight = center + Vector2(m_vBlockSize.x/2 + 1, 1);
Vector2 bottomLeft = center + Vector2(-m_vBlockSize.x/2, m_vBlockSize.y/2 + 1);
Vector2 bottomRight = center + Vector2(m_vBlockSize.x/2 + 1, m_vBlockSize.y/2 + 1);
g->drawQuad(topLeft,
topRight,
halfRight + Vector2(0,1),
halfLeft + Vector2(0,1),
COLOR(255,255,255,255),
COLOR(255,255,255,255),
COLOR(255,241,241,241),
COLOR(255,241,241,241));
g->drawQuad(halfLeft,
halfRight,
bottomRight,
bottomLeft,
COLOR(255,225,225,225),
COLOR(255,225,225,225),
COLOR(255,255,255,255),
COLOR(255,255,255,255));
/*
g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2),
COLOR(255,255,255,255),
COLOR(255,255,255,255),
COLOR(255,241,241,241),
COLOR(255,241,241,241));
g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))),
COLOR(255,225,225,225),
COLOR(255,225,225,225),
COLOR(255,255,255,255),
COLOR(255,255,255,255));
*/
/*
g->setColor(0xff00ff00);
g->fillRect(m_vPos.x+m_vBlockPos.x+1, m_vPos.y+m_vBlockPos.y+1, m_vBlockSize.x-1, m_vBlockSize.y);
*/
}
void CBaseUISlider::update()
{
CBaseUIElement::update();
if (!m_bVisible) return;
Vector2 mousepos = engine->getMouse()->getPos();
// handle moving
if (m_bActive)
{
// calculate new values
if (!m_bHorizontal)
{
if (m_bAnimated)
anim->moveQuadOut( &m_vBlockPos.y, clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y ), 0.10f, 0, true );
else
m_vBlockPos.y = clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y );
m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f);
}
else
{
if (m_bAnimated)
anim->moveQuadOut( &m_vBlockPos.x, clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x ), 0.10f, 0, true );
else
m_vBlockPos.x = clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x );
m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f);
}
// set new value
if (m_bAnimated)
{
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
else
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
m_bHasChanged = true;
}
else
{
// handle mouse wheel
if (m_bMouseInside && m_bAllowMouseWheel)
{
int wheelDelta = engine->getMouse()->getWheelDeltaVertical();
if (wheelDelta != 0)
{
const int multiplier = std::max(1, std::abs(wheelDelta) / 120);
if (wheelDelta > 0)
setValue(m_fCurValue + m_fKeyDelta*multiplier, m_bAnimated);
else
setValue(m_fCurValue - m_fKeyDelta*multiplier, m_bAnimated);
}
}
}
// handle animation value settings after mouse release
if (!m_bActive)
{
if (anim->isAnimating( &m_vBlockPos.x ))
{
m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f);
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
if (anim->isAnimating( &m_vBlockPos.y ))
{
m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f);
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
}
}
void CBaseUISlider::onKeyDown(KeyboardEvent &e)
{
if (!m_bVisible) return;
if (isMouseInside())
{
if (e == KEY_LEFT)
{
setValue(getFloat() - m_fKeyDelta, false);
e.consume();
}
else if (e == KEY_RIGHT)
{
setValue(getFloat() + m_fKeyDelta, false);
e.consume();
}
}
}
void CBaseUISlider::fireChangeCallback()
{
if (m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::updateBlockPos()
{
if (!m_bHorizontal)
m_vBlockPos.x = m_vSize.x/2.0f - m_vBlockSize.x/2.0f;
else
m_vBlockPos.y = m_vSize.y/2.0f - m_vBlockSize.y/2.0f;
}
CBaseUISlider *CBaseUISlider::setBounds(float minValue, float maxValue)
{
m_fMinValue = minValue;
m_fMaxValue = maxValue;
m_fKeyDelta = (m_fMaxValue - m_fMinValue) / 10.0f;
return this;
}
CBaseUISlider *CBaseUISlider::setValue(float value, bool animate)
{
bool changeCallbackCheck = false;
if (value != m_fCurValue)
{
changeCallbackCheck = true;
m_bHasChanged = true;
}
m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue);
float percent = getPercent();
if (!m_bHorizontal)
{
if (animate)
anim->moveQuadOut( &m_vBlockPos.y, (m_vSize.y-m_vBlockSize.y)*(1.0f-percent), 0.2f, 0, true );
else
m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent);
}
else
{
if (animate)
anim->moveQuadOut( &m_vBlockPos.x, (m_vSize.x-m_vBlockSize.x)*percent, 0.2f, 0, true );
else
m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent;
}
if (changeCallbackCheck && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
updateBlockPos();
return this;
}
CBaseUISlider *CBaseUISlider::setInitialValue(float value)
{
m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue);
float percent = getPercent();
if (m_fCurValue == m_fMaxValue)
percent = 1.0f;
if (!m_bHorizontal)
m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent);
else
m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent;
updateBlockPos();
return this;
}
void CBaseUISlider::setBlockSize(float xSize, float ySize)
{
m_vBlockSize = Vector2(xSize, ySize);
}
float CBaseUISlider::getPercent()
{
return clamp<float>((m_fCurValue-m_fMinValue) / (std::abs(m_fMaxValue-m_fMinValue)), 0.0f, 1.0f);
}
bool CBaseUISlider::hasChanged()
{
if (anim->isAnimating(&m_vBlockPos.x))
return true;
if (m_bHasChanged)
{
m_bHasChanged = false;
return true;
}
return false;
}
void CBaseUISlider::onFocusStolen()
{
m_bBusy = false;
}
void CBaseUISlider::onMouseUpInside()
{
m_bBusy = false;
if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::onMouseUpOutside()
{
m_bBusy = false;
if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::onMouseDownInside()
{
m_fPrevValue = m_fCurValue;
if (McRect(m_vPos.x+m_vBlockPos.x,m_vPos.y+m_vBlockPos.y,m_vBlockSize.x,m_vBlockSize.y).contains(engine->getMouse()->getPos()))
m_vGrabBackup = engine->getMouse()->getPos()-m_vBlockPos;
else
m_vGrabBackup = m_vPos + m_vBlockSize/2;
m_bBusy = true;
}
void CBaseUISlider::onResized()
{
setValue(getFloat(), false);
}
| 9,796 | 4,921 |
/***************************************************************************
* Copyright (C) 2005 by *
* Alejandro Perez Mendez alex@um.es *
* Pedro J. Fernandez Ruiz pedroj@um.es *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "authgeneratorbtns.h"
namespace openikev2 {
AuthGeneratorBtns::AuthGeneratorBtns( ) {}
AuthGeneratorBtns::~AuthGeneratorBtns( ) {}
auto_ptr< AuthGenerator > AuthGeneratorBtns::clone() const {
return auto_ptr<AuthGenerator> ( new AuthGeneratorBtns( ) );
}
auto_ptr< Payload_AUTH > AuthGeneratorBtns::generateAuthPayload( const IkeSa& ike_sa ) {
auto_ptr<ByteArray> auth_field (new ByteArray ("BTNS", 4) );
return auto_ptr<Payload_AUTH> ( new Payload_AUTH( (Enums::AUTH_METHOD) 201, auth_field ) );
}
AutoVector<Payload_CERT> AuthGeneratorBtns::generateCertificatePayloads( const IkeSa& ike_sa, const vector< Payload_CERT_REQ * > payload_cert_req_r ) {
AutoVector<Payload_CERT> result;
return result;
}
string AuthGeneratorBtns::toStringTab( uint8_t tabs ) const {
ostringstream oss;
oss << Printable::generateTabs( tabs ) << "<AUTH_GENERATOR_BTNS> {\n";
oss << Printable::generateTabs( tabs ) << "}\n";
return oss.str();
}
}
| 1,673 | 498 |
#include "ShaderStorageBuffer.h"
#include "GlobalDeviceObjects.h"
bool ShaderStorageBuffer::Init(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ShaderStorageBuffer>& pSelf, uint32_t numBytes)
{
VkBufferCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
uint32_t minAlign = (uint32_t)GetPhysicalDevice()->GetPhysicalDeviceProperties().limits.minStorageBufferOffsetAlignment;
uint32_t totalUniformBytes = numBytes / minAlign * minAlign + (numBytes % minAlign > 0 ? minAlign : 0);
info.size = totalUniformBytes;
if (!SharedBuffer::Init(pDevice, pSelf, info))
return false;
// FIXME: add them back when necessary
m_accessStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
//VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
//VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
//VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
m_accessFlags = VK_ACCESS_SHADER_READ_BIT;
return true;
}
std::shared_ptr<ShaderStorageBuffer> ShaderStorageBuffer::Create(const std::shared_ptr<Device>& pDevice, uint32_t numBytes)
{
std::shared_ptr<ShaderStorageBuffer> pSSBO = std::make_shared<ShaderStorageBuffer>();
if (pSSBO.get() && pSSBO->Init(pDevice, pSSBO, numBytes))
return pSSBO;
return nullptr;
}
std::shared_ptr<BufferKey> ShaderStorageBuffer::AcquireBuffer(uint32_t numBytes)
{
return ShaderStorageBufferMgr()->AllocateBuffer(numBytes);
} | 1,515 | 609 |